oauth2.go 1.6 KB

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