oauth2.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. type OauthType int
  9. const (
  10. GITHUB OauthType = iota + 1
  11. GOOGLE
  12. TWITTER
  13. QQ
  14. WEIBO
  15. BITBUCKET
  16. FACEBOOK
  17. )
  18. var (
  19. ErrOauth2RecordNotExist = errors.New("OAuth2 record does not exist")
  20. ErrOauth2NotAssociated = errors.New("OAuth2 is not associated with user")
  21. )
  22. type Oauth2 struct {
  23. Id int64
  24. Uid int64 `xorm:"unique(s)"` // userId
  25. User *User `xorm:"-"`
  26. Type int `xorm:"unique(s) unique(oauth)"` // twitter,github,google...
  27. Identity string `xorm:"unique(s) unique(oauth)"` // id..
  28. Token string `xorm:"TEXT not null"`
  29. }
  30. func BindUserOauth2(userId, oauthId int64) error {
  31. _, err := x.Id(oauthId).Update(&Oauth2{Uid: userId})
  32. return err
  33. }
  34. func AddOauth2(oa *Oauth2) error {
  35. _, err := x.Insert(oa)
  36. return err
  37. }
  38. func GetOauth2(identity string) (oa *Oauth2, err error) {
  39. oa = &Oauth2{Identity: identity}
  40. isExist, err := x.Get(oa)
  41. if err != nil {
  42. return
  43. } else if !isExist {
  44. return nil, ErrOauth2RecordNotExist
  45. } else if oa.Uid == -1 {
  46. return oa, ErrOauth2NotAssociated
  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 := x.Id(id).Get(oa)
  54. if err != nil {
  55. return nil, err
  56. } else if !has {
  57. return nil, ErrOauth2RecordNotExist
  58. }
  59. return oa, nil
  60. }
  61. // GetOauthByUserId returns list of oauthes that are releated to given user.
  62. func GetOauthByUserId(uid int64) (oas []*Oauth2, err error) {
  63. err = x.Find(&oas, Oauth2{Uid: uid})
  64. return oas, err
  65. }
  66. // DeleteOauth2ById deletes a oauth2 by ID.
  67. func DeleteOauth2ById(id int64) error {
  68. _, err := x.Delete(&Oauth2{Id: id})
  69. return err
  70. }
  71. // CleanUnbindOauth deletes all unbind OAuthes.
  72. func CleanUnbindOauth() error {
  73. _, err := x.Delete(&Oauth2{Uid: -1})
  74. return err
  75. }