oauth2.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. OT_QQ
  14. )
  15. var (
  16. ErrOauth2RecordNotExists = errors.New("not exists oauth2 record")
  17. ErrOauth2NotAssociatedWithUser = errors.New("not associated with user")
  18. )
  19. type Oauth2 struct {
  20. Id int64
  21. Uid int64 `xorm:"unique(s)"` // userId
  22. User *User `xorm:"-"`
  23. Type int `xorm:"unique(s) unique(oauth)"` // twitter,github,google...
  24. Identity string `xorm:"unique(s) unique(oauth)"` // id..
  25. Token string `xorm:"TEXT not null"`
  26. }
  27. func BindUserOauth2(userId, oauthId int64) error {
  28. _, err := orm.Id(oauthId).Update(&Oauth2{Uid: userId})
  29. return err
  30. }
  31. func AddOauth2(oa *Oauth2) (err error) {
  32. if _, err = orm.Insert(oa); err != nil {
  33. return err
  34. }
  35. return nil
  36. }
  37. func GetOauth2(identity string) (oa *Oauth2, err error) {
  38. oa = &Oauth2{Identity: identity}
  39. isExist, err := orm.Get(oa)
  40. if err != nil {
  41. return
  42. } else if !isExist {
  43. return nil, ErrOauth2RecordNotExists
  44. } else if oa.Uid == -1 {
  45. return oa, ErrOauth2NotAssociatedWithUser
  46. }
  47. oa.User, err = GetUserById(oa.Uid)
  48. return oa, err
  49. }
  50. func GetOauth2ById(id int64) (oa *Oauth2, err error) {
  51. oa = new(Oauth2)
  52. has, err := orm.Id(id).Get(oa)
  53. if err != nil {
  54. return nil, err
  55. }
  56. if !has {
  57. return nil, ErrOauth2RecordNotExists
  58. }
  59. return oa, nil
  60. }