users.go 8.7 KB

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