oauth_user.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package login
  2. import "gorm.io/gorm"
  3. type OAuthUser interface {
  4. FindUserByOAuthUserID(db *gorm.DB, model interface{}, provider string, oid string) (user interface{}, err error)
  5. FindUserByOAuthIdentifier(db *gorm.DB, model interface{}, provider string, identifier string) (user interface{}, err error)
  6. InitOAuthUserID(db *gorm.DB, model interface{}, provider string, identifier string, oid string) error
  7. SetAvatar(v string)
  8. GetAvatar() string
  9. }
  10. type OAuthInfo struct {
  11. OAuthProvider string `gorm:"index:uidx_users_oauth_provider_user_id,unique,where:o_auth_provider!='' and o_auth_user_id!='' and deleted_at is null;index:uidx_users_oauth_provider_identifier,unique,where:o_auth_provider!='' and o_auth_identifier!='' and deleted_at is null"`
  12. OAuthUserID string `gorm:"index:uidx_users_oauth_provider_user_id,unique,where:o_auth_provider!='' and o_auth_user_id!='' and deleted_at is null"`
  13. // users use this value to log into their account
  14. // in most cases is email or account name
  15. // it is used to find the user record on the first login
  16. OAuthIdentifier string `gorm:"index:uidx_users_oauth_provider_identifier,unique,where:o_auth_provider!='' and o_auth_identifier!='' and deleted_at is null"`
  17. OAuthAvatar string `gorm:"-"`
  18. }
  19. var _ OAuthUser = (*OAuthInfo)(nil)
  20. func (oa *OAuthInfo) FindUserByOAuthUserID(db *gorm.DB, model interface{}, provider string, oid string) (user interface{}, err error) {
  21. err = db.Where("o_auth_provider = ? and o_auth_user_id = ?", provider, oid).
  22. First(model).
  23. Error
  24. if err != nil {
  25. return nil, err
  26. }
  27. return model, nil
  28. }
  29. func (oa *OAuthInfo) FindUserByOAuthIdentifier(db *gorm.DB, model interface{}, provider string, identifier string) (user interface{}, err error) {
  30. err = db.Where("o_auth_provider = ? and o_auth_identifier = ?", provider, identifier).
  31. First(model).
  32. Error
  33. if err != nil {
  34. return nil, err
  35. }
  36. return model, nil
  37. }
  38. func (oa *OAuthInfo) InitOAuthUserID(db *gorm.DB, model interface{}, provider string, identifier string, oid string) error {
  39. err := db.Model(model).
  40. Where("o_auth_provider = ? and o_auth_identifier = ?", provider, identifier).
  41. Updates(map[string]interface{}{
  42. "o_auth_user_id": oid,
  43. }).
  44. Error
  45. if err != nil {
  46. return err
  47. }
  48. oa.OAuthUserID = oid
  49. return nil
  50. }
  51. func (oa *OAuthInfo) SetAvatar(v string) {
  52. oa.OAuthAvatar = v
  53. }
  54. func (oa *OAuthInfo) GetAvatar() string {
  55. return oa.OAuthAvatar
  56. }