users.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. // Copyright 2020 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 db
  5. import (
  6. "fmt"
  7. "strings"
  8. "time"
  9. "github.com/jinzhu/gorm"
  10. "github.com/pkg/errors"
  11. "gogs.io/gogs/internal/cryptoutil"
  12. "gogs.io/gogs/internal/errutil"
  13. )
  14. // UsersStore is the persistent interface for users.
  15. //
  16. // NOTE: All methods are sorted in alphabetical order.
  17. type UsersStore interface {
  18. // Authenticate validates username and password via given login source ID.
  19. // It returns ErrUserNotExist when the user was not found.
  20. //
  21. // When the "loginSourceID" is negative, it aborts the process and returns
  22. // ErrUserNotExist if the user was not found in the database.
  23. //
  24. // When the "loginSourceID" is non-negative, it returns ErrLoginSourceMismatch
  25. // if the user has different login source ID than the "loginSourceID".
  26. //
  27. // When the "loginSourceID" is positive, it tries to authenticate via given
  28. // login source and creates a new user when not yet exists in the database.
  29. Authenticate(username, password string, loginSourceID int64) (*User, error)
  30. // Create creates a new user and persist to database.
  31. // It returns ErrUserAlreadyExist when a user with same name already exists,
  32. // or ErrEmailAlreadyUsed if the email has been used by another user.
  33. Create(opts CreateUserOpts) (*User, error)
  34. // GetByEmail returns the user (not organization) with given email.
  35. // It ignores records with unverified emails and returns ErrUserNotExist when not found.
  36. GetByEmail(email string) (*User, error)
  37. // GetByID returns the user with given ID. It returns ErrUserNotExist when not found.
  38. GetByID(id int64) (*User, error)
  39. // GetByUsername returns the user with given username. It returns ErrUserNotExist when not found.
  40. GetByUsername(username string) (*User, error)
  41. }
  42. var Users UsersStore
  43. // NOTE: This is a GORM create hook.
  44. func (u *User) BeforeCreate() {
  45. u.CreatedUnix = gorm.NowFunc().Unix()
  46. u.UpdatedUnix = u.CreatedUnix
  47. }
  48. // NOTE: This is a GORM query hook.
  49. func (u *User) AfterFind() {
  50. u.Created = time.Unix(u.CreatedUnix, 0).Local()
  51. u.Updated = time.Unix(u.UpdatedUnix, 0).Local()
  52. }
  53. var _ UsersStore = (*users)(nil)
  54. type users struct {
  55. *gorm.DB
  56. }
  57. type ErrLoginSourceMismatch struct {
  58. args errutil.Args
  59. }
  60. func (err ErrLoginSourceMismatch) Error() string {
  61. return fmt.Sprintf("login source mismatch: %v", err.args)
  62. }
  63. func (db *users) Authenticate(login, password string, loginSourceID int64) (*User, error) {
  64. login = strings.ToLower(login)
  65. var query *gorm.DB
  66. if strings.Contains(login, "@") {
  67. query = db.Where("email = ?", login)
  68. } else {
  69. query = db.Where("lower_name = ?", login)
  70. }
  71. user := new(User)
  72. err := query.First(user).Error
  73. if err != nil && err != gorm.ErrRecordNotFound {
  74. return nil, errors.Wrap(err, "get user")
  75. }
  76. // User found in the database
  77. if err == nil {
  78. // Note: This check is unnecessary but to reduce user confusion at login page
  79. // and make it more consistent from user's perspective.
  80. if loginSourceID >= 0 && user.LoginSource != loginSourceID {
  81. return nil, ErrLoginSourceMismatch{args: errutil.Args{"expect": loginSourceID, "actual": user.LoginSource}}
  82. }
  83. // Validate password hash fetched from database for local accounts.
  84. if user.IsLocal() {
  85. if user.ValidatePassword(password) {
  86. return user, nil
  87. }
  88. return nil, ErrUserNotExist{args: map[string]interface{}{"userID": user.ID, "name": user.Name}}
  89. }
  90. source, err := LoginSources.GetByID(user.LoginSource)
  91. if err != nil {
  92. return nil, errors.Wrap(err, "get login source")
  93. }
  94. _, err = authenticateViaLoginSource(source, login, password, false)
  95. if err != nil {
  96. return nil, errors.Wrap(err, "authenticate via login source")
  97. }
  98. return user, nil
  99. }
  100. // Non-local login source is always greater than 0.
  101. if loginSourceID <= 0 {
  102. return nil, ErrUserNotExist{args: map[string]interface{}{"login": login}}
  103. }
  104. source, err := LoginSources.GetByID(loginSourceID)
  105. if err != nil {
  106. return nil, errors.Wrap(err, "get login source")
  107. }
  108. user, err = authenticateViaLoginSource(source, login, password, true)
  109. if err != nil {
  110. return nil, errors.Wrap(err, "authenticate via login source")
  111. }
  112. return user, nil
  113. }
  114. type CreateUserOpts struct {
  115. Name string
  116. Email string
  117. Password string
  118. LoginSource int64
  119. Activated bool
  120. }
  121. type ErrUserAlreadyExist struct {
  122. args errutil.Args
  123. }
  124. func IsErrUserAlreadyExist(err error) bool {
  125. _, ok := err.(ErrUserAlreadyExist)
  126. return ok
  127. }
  128. func (err ErrUserAlreadyExist) Error() string {
  129. return fmt.Sprintf("user already exists: %v", err.args)
  130. }
  131. type ErrEmailAlreadyUsed struct {
  132. args errutil.Args
  133. }
  134. func IsErrEmailAlreadyUsed(err error) bool {
  135. _, ok := err.(ErrEmailAlreadyUsed)
  136. return ok
  137. }
  138. func (err ErrEmailAlreadyUsed) Email() string {
  139. email, ok := err.args["email"].(string)
  140. if ok {
  141. return email
  142. }
  143. return "<email not found>"
  144. }
  145. func (err ErrEmailAlreadyUsed) Error() string {
  146. return fmt.Sprintf("email has been used: %v", err.args)
  147. }
  148. func (db *users) Create(opts CreateUserOpts) (*User, error) {
  149. err := isUsernameAllowed(opts.Name)
  150. if err != nil {
  151. return nil, err
  152. }
  153. _, err = db.GetByUsername(opts.Name)
  154. if err == nil {
  155. return nil, ErrUserAlreadyExist{args: errutil.Args{"name": opts.Name}}
  156. } else if !IsErrUserNotExist(err) {
  157. return nil, err
  158. }
  159. _, err = db.GetByEmail(opts.Email)
  160. if err == nil {
  161. return nil, ErrEmailAlreadyUsed{args: errutil.Args{"email": opts.Email}}
  162. } else if !IsErrUserNotExist(err) {
  163. return nil, err
  164. }
  165. user := &User{
  166. LowerName: strings.ToLower(opts.Name),
  167. Name: opts.Name,
  168. Email: opts.Email,
  169. Passwd: opts.Password,
  170. LoginSource: opts.LoginSource,
  171. MaxRepoCreation: -1,
  172. IsActive: opts.Activated,
  173. Avatar: cryptoutil.MD5(opts.Email),
  174. AvatarEmail: opts.Email,
  175. }
  176. user.Rands, err = GetUserSalt()
  177. if err != nil {
  178. return nil, err
  179. }
  180. user.Salt, err = GetUserSalt()
  181. if err != nil {
  182. return nil, err
  183. }
  184. user.EncodePassword()
  185. return user, db.DB.Create(user).Error
  186. }
  187. var _ errutil.NotFound = (*ErrUserNotExist)(nil)
  188. type ErrUserNotExist struct {
  189. args errutil.Args
  190. }
  191. func IsErrUserNotExist(err error) bool {
  192. _, ok := err.(ErrUserNotExist)
  193. return ok
  194. }
  195. func (err ErrUserNotExist) Error() string {
  196. return fmt.Sprintf("user does not exist: %v", err.args)
  197. }
  198. func (ErrUserNotExist) NotFound() bool {
  199. return true
  200. }
  201. func (db *users) GetByEmail(email string) (*User, error) {
  202. email = strings.ToLower(email)
  203. if len(email) == 0 {
  204. return nil, ErrUserNotExist{args: errutil.Args{"email": email}}
  205. }
  206. // First try to find the user by primary email
  207. user := new(User)
  208. err := db.Where("email = ? AND type = ? AND is_active = ?", email, UserIndividual, true).First(user).Error
  209. if err == nil {
  210. return user, nil
  211. } else if !gorm.IsRecordNotFoundError(err) {
  212. return nil, err
  213. }
  214. // Otherwise, check activated email addresses
  215. emailAddress := new(EmailAddress)
  216. err = db.Where("email = ? AND is_activated = ?", email, true).First(emailAddress).Error
  217. if err != nil {
  218. if gorm.IsRecordNotFoundError(err) {
  219. return nil, ErrUserNotExist{args: errutil.Args{"email": email}}
  220. }
  221. return nil, err
  222. }
  223. return db.GetByID(emailAddress.UID)
  224. }
  225. func (db *users) GetByID(id int64) (*User, error) {
  226. user := new(User)
  227. err := db.Where("id = ?", id).First(user).Error
  228. if err != nil {
  229. if gorm.IsRecordNotFoundError(err) {
  230. return nil, ErrUserNotExist{args: errutil.Args{"userID": id}}
  231. }
  232. return nil, err
  233. }
  234. return user, nil
  235. }
  236. func (db *users) GetByUsername(username string) (*User, error) {
  237. user := new(User)
  238. err := db.Where("lower_name = ?", strings.ToLower(username)).First(user).Error
  239. if err != nil {
  240. if gorm.IsRecordNotFoundError(err) {
  241. return nil, ErrUserNotExist{args: errutil.Args{"name": username}}
  242. }
  243. return nil, err
  244. }
  245. return user, nil
  246. }