oauth2.go 1012 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package models
  2. import (
  3. "errors"
  4. "fmt"
  5. )
  6. // OT: Oauth2 Type
  7. const (
  8. OT_GITHUB = iota + 1
  9. OT_GOOGLE
  10. OT_TWITTER
  11. )
  12. var (
  13. ErrOauth2RecordNotExists = errors.New("not exists oauth2 record")
  14. ErrOauth2NotAssociatedWithUser = errors.New("not associated with user")
  15. )
  16. type Oauth2 struct {
  17. Id int64
  18. Uid int64 `xorm:"pk"` // userId
  19. User *User `xorm:"-"`
  20. Type int `xorm:"pk unique(oauth)"` // twitter,github,google...
  21. Identity string `xorm:"pk unique(oauth)"` // id..
  22. Token string `xorm:"VARCHAR(200) not null"`
  23. }
  24. func AddOauth2(oa *Oauth2) (err error) {
  25. if _, err = orm.Insert(oa); err != nil {
  26. return err
  27. }
  28. return nil
  29. }
  30. func GetOauth2(identity string) (oa *Oauth2, err error) {
  31. oa = &Oauth2{}
  32. oa.Identity = identity
  33. exists, err := orm.Get(oa)
  34. if err != nil {
  35. return
  36. }
  37. if !exists {
  38. err = fmt.Errorf("not exists oauth2: %s", identity)
  39. return
  40. }
  41. if oa.Uid == 0 {
  42. return oa, ErrOauth2NotAssociatedWithUser
  43. }
  44. oa.User, err = GetUserById(oa.Uid)
  45. return
  46. }