You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

oauth2.go 1.5 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "errors"
  7. )
  8. // OT: Oauth2 Type
  9. const (
  10. OT_GITHUB = iota + 1
  11. OT_GOOGLE
  12. OT_TWITTER
  13. )
  14. var (
  15. ErrOauth2RecordNotExists = errors.New("not exists oauth2 record")
  16. ErrOauth2NotAssociatedWithUser = errors.New("not associated with user")
  17. )
  18. type Oauth2 struct {
  19. Id int64
  20. Uid int64 `xorm:"unique(s)"` // userId
  21. User *User `xorm:"-"`
  22. Type int `xorm:"unique(s) unique(oauth)"` // twitter,github,google...
  23. Identity string `xorm:"unique(s) unique(oauth)"` // id..
  24. Token string `xorm:"TEXT not null"`
  25. }
  26. func BindUserOauth2(userId, oauthId int64) error {
  27. _, err := orm.Id(oauthId).Update(&Oauth2{Uid: userId})
  28. return err
  29. }
  30. func AddOauth2(oa *Oauth2) (err error) {
  31. if _, err = orm.Insert(oa); err != nil {
  32. return err
  33. }
  34. return nil
  35. }
  36. func GetOauth2(identity string) (oa *Oauth2, err error) {
  37. oa = &Oauth2{Identity: identity}
  38. isExist, err := orm.Get(oa)
  39. if err != nil {
  40. return
  41. } else if !isExist {
  42. return nil, ErrOauth2RecordNotExists
  43. } else if oa.Uid == -1 {
  44. return oa, ErrOauth2NotAssociatedWithUser
  45. }
  46. oa.User, err = GetUserById(oa.Uid)
  47. return oa, err
  48. }
  49. func GetOauth2ById(id int64) (oa *Oauth2, err error) {
  50. oa = new(Oauth2)
  51. has, err := orm.Id(id).Get(oa)
  52. if err != nil {
  53. return nil, err
  54. }
  55. if !has {
  56. return nil, ErrOauth2RecordNotExists
  57. }
  58. return oa, nil
  59. }