users.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095
  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. "context"
  7. "fmt"
  8. "os"
  9. "strings"
  10. "time"
  11. "unicode/utf8"
  12. "github.com/go-macaron/binding"
  13. api "github.com/gogs/go-gogs-client"
  14. "github.com/pkg/errors"
  15. "gorm.io/gorm"
  16. log "unknwon.dev/clog/v2"
  17. "gogs.io/gogs/internal/auth"
  18. "gogs.io/gogs/internal/conf"
  19. "gogs.io/gogs/internal/cryptoutil"
  20. "gogs.io/gogs/internal/dbutil"
  21. "gogs.io/gogs/internal/errutil"
  22. "gogs.io/gogs/internal/osutil"
  23. "gogs.io/gogs/internal/repoutil"
  24. "gogs.io/gogs/internal/strutil"
  25. "gogs.io/gogs/internal/tool"
  26. "gogs.io/gogs/internal/userutil"
  27. )
  28. // UsersStore is the persistent interface for users.
  29. //
  30. // NOTE: All methods are sorted in alphabetical order.
  31. type UsersStore interface {
  32. // Authenticate validates username and password via given login source ID. It
  33. // returns ErrUserNotExist when the user was not found.
  34. //
  35. // When the "loginSourceID" is negative, it aborts the process and returns
  36. // ErrUserNotExist if the user was not found in the database.
  37. //
  38. // When the "loginSourceID" is non-negative, it returns ErrLoginSourceMismatch
  39. // if the user has different login source ID than the "loginSourceID".
  40. //
  41. // When the "loginSourceID" is positive, it tries to authenticate via given
  42. // login source and creates a new user when not yet exists in the database.
  43. Authenticate(ctx context.Context, username, password string, loginSourceID int64) (*User, error)
  44. // ChangeUsername changes the username of the given user and updates all
  45. // references to the old username. It returns ErrNameNotAllowed if the given
  46. // name or pattern of the name is not allowed as a username, or
  47. // ErrUserAlreadyExist when another user with same name already exists.
  48. ChangeUsername(ctx context.Context, userID int64, newUsername string) error
  49. // Count returns the total number of users.
  50. Count(ctx context.Context) int64
  51. // Create creates a new user and persists to database. It returns
  52. // ErrNameNotAllowed if the given name or pattern of the name is not allowed as
  53. // a username, or ErrUserAlreadyExist when a user with same name already exists,
  54. // or ErrEmailAlreadyUsed if the email has been used by another user.
  55. Create(ctx context.Context, username, email string, opts CreateUserOptions) (*User, error)
  56. // DeleteCustomAvatar deletes the current user custom avatar and falls back to
  57. // use look up avatar by email.
  58. DeleteCustomAvatar(ctx context.Context, userID int64) error
  59. // GetByEmail returns the user (not organization) with given email. It ignores
  60. // records with unverified emails and returns ErrUserNotExist when not found.
  61. GetByEmail(ctx context.Context, email string) (*User, error)
  62. // GetByID returns the user with given ID. It returns ErrUserNotExist when not
  63. // found.
  64. GetByID(ctx context.Context, id int64) (*User, error)
  65. // GetByUsername returns the user with given username. It returns
  66. // ErrUserNotExist when not found.
  67. GetByUsername(ctx context.Context, username string) (*User, error)
  68. // GetByKeyID returns the owner of given public key ID. It returns
  69. // ErrUserNotExist when not found.
  70. GetByKeyID(ctx context.Context, keyID int64) (*User, error)
  71. // HasForkedRepository returns true if the user has forked given repository.
  72. HasForkedRepository(ctx context.Context, userID, repoID int64) bool
  73. // IsUsernameUsed returns true if the given username has been used other than
  74. // the excluded user (a non-positive ID effectively meaning check against all
  75. // users).
  76. IsUsernameUsed(ctx context.Context, username string, excludeUserId int64) bool
  77. // List returns a list of users. Results are paginated by given page and page
  78. // size, and sorted by primary key (id) in ascending order.
  79. List(ctx context.Context, page, pageSize int) ([]*User, error)
  80. // ListFollowers returns a list of users that are following the given user.
  81. // Results are paginated by given page and page size, and sorted by the time of
  82. // follow in descending order.
  83. ListFollowers(ctx context.Context, userID int64, page, pageSize int) ([]*User, error)
  84. // ListFollowings returns a list of users that are followed by the given user.
  85. // Results are paginated by given page and page size, and sorted by the time of
  86. // follow in descending order.
  87. ListFollowings(ctx context.Context, userID int64, page, pageSize int) ([]*User, error)
  88. // SearchByName returns a list of users whose username or full name matches the
  89. // given keyword case-insensitively. Results are paginated by given page and
  90. // page size, and sorted by the given order (e.g. "id DESC"). A total count of
  91. // all results is also returned. If the order is not given, it's up to the
  92. // database to decide.
  93. SearchByName(ctx context.Context, keyword string, page, pageSize int, orderBy string) ([]*User, int64, error)
  94. // Update updates fields for the given user.
  95. Update(ctx context.Context, userID int64, opts UpdateUserOptions) error
  96. // UseCustomAvatar uses the given avatar as the user custom avatar.
  97. UseCustomAvatar(ctx context.Context, userID int64, avatar []byte) error
  98. }
  99. var Users UsersStore
  100. var _ UsersStore = (*users)(nil)
  101. type users struct {
  102. *gorm.DB
  103. }
  104. // NewUsersStore returns a persistent interface for users with given database
  105. // connection.
  106. func NewUsersStore(db *gorm.DB) UsersStore {
  107. return &users{DB: db}
  108. }
  109. type ErrLoginSourceMismatch struct {
  110. args errutil.Args
  111. }
  112. // IsErrLoginSourceMismatch returns true if the underlying error has the type
  113. // ErrLoginSourceMismatch.
  114. func IsErrLoginSourceMismatch(err error) bool {
  115. _, ok := errors.Cause(err).(ErrLoginSourceMismatch)
  116. return ok
  117. }
  118. func (err ErrLoginSourceMismatch) Error() string {
  119. return fmt.Sprintf("login source mismatch: %v", err.args)
  120. }
  121. func (db *users) Authenticate(ctx context.Context, login, password string, loginSourceID int64) (*User, error) {
  122. login = strings.ToLower(login)
  123. query := db.WithContext(ctx)
  124. if strings.Contains(login, "@") {
  125. query = query.Where("email = ?", login)
  126. } else {
  127. query = query.Where("lower_name = ?", login)
  128. }
  129. user := new(User)
  130. err := query.First(user).Error
  131. if err != nil && err != gorm.ErrRecordNotFound {
  132. return nil, errors.Wrap(err, "get user")
  133. }
  134. var authSourceID int64 // The login source ID will be used to authenticate the user
  135. createNewUser := false // Whether to create a new user after successful authentication
  136. // User found in the database
  137. if err == nil {
  138. // Note: This check is unnecessary but to reduce user confusion at login page
  139. // and make it more consistent from user's perspective.
  140. if loginSourceID >= 0 && user.LoginSource != loginSourceID {
  141. return nil, ErrLoginSourceMismatch{args: errutil.Args{"expect": loginSourceID, "actual": user.LoginSource}}
  142. }
  143. // Validate password hash fetched from database for local accounts.
  144. if user.IsLocal() {
  145. if userutil.ValidatePassword(user.Password, user.Salt, password) {
  146. return user, nil
  147. }
  148. return nil, auth.ErrBadCredentials{Args: map[string]any{"login": login, "userID": user.ID}}
  149. }
  150. authSourceID = user.LoginSource
  151. } else {
  152. // Non-local login source is always greater than 0.
  153. if loginSourceID <= 0 {
  154. return nil, auth.ErrBadCredentials{Args: map[string]any{"login": login}}
  155. }
  156. authSourceID = loginSourceID
  157. createNewUser = true
  158. }
  159. source, err := LoginSources.GetByID(ctx, authSourceID)
  160. if err != nil {
  161. return nil, errors.Wrap(err, "get login source")
  162. }
  163. if !source.IsActived {
  164. return nil, errors.Errorf("login source %d is not activated", source.ID)
  165. }
  166. extAccount, err := source.Provider.Authenticate(login, password)
  167. if err != nil {
  168. return nil, err
  169. }
  170. if !createNewUser {
  171. return user, nil
  172. }
  173. // Validate username make sure it satisfies requirement.
  174. if binding.AlphaDashDotPattern.MatchString(extAccount.Name) {
  175. return nil, fmt.Errorf("invalid pattern for attribute 'username' [%s]: must be valid alpha or numeric or dash(-_) or dot characters", extAccount.Name)
  176. }
  177. return db.Create(ctx, extAccount.Name, extAccount.Email,
  178. CreateUserOptions{
  179. FullName: extAccount.FullName,
  180. LoginSource: authSourceID,
  181. LoginName: extAccount.Login,
  182. Location: extAccount.Location,
  183. Website: extAccount.Website,
  184. Activated: true,
  185. Admin: extAccount.Admin,
  186. },
  187. )
  188. }
  189. func (db *users) ChangeUsername(ctx context.Context, userID int64, newUsername string) error {
  190. err := isUsernameAllowed(newUsername)
  191. if err != nil {
  192. return err
  193. }
  194. if db.IsUsernameUsed(ctx, newUsername, userID) {
  195. return ErrUserAlreadyExist{
  196. args: errutil.Args{
  197. "name": newUsername,
  198. },
  199. }
  200. }
  201. user, err := db.GetByID(ctx, userID)
  202. if err != nil {
  203. return errors.Wrap(err, "get user")
  204. }
  205. return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  206. err := tx.Model(&User{}).
  207. Where("id = ?", user.ID).
  208. Updates(map[string]any{
  209. "lower_name": strings.ToLower(newUsername),
  210. "name": newUsername,
  211. "updated_unix": tx.NowFunc().Unix(),
  212. }).Error
  213. if err != nil {
  214. return errors.Wrap(err, "update user name")
  215. }
  216. // Stop here if it's just a case-change of the username
  217. if strings.EqualFold(user.Name, newUsername) {
  218. return nil
  219. }
  220. // Update all references to the user name in pull requests
  221. err = tx.Model(&PullRequest{}).
  222. Where("head_user_name = ?", user.LowerName).
  223. Update("head_user_name", strings.ToLower(newUsername)).
  224. Error
  225. if err != nil {
  226. return errors.Wrap(err, `update "pull_request.head_user_name"`)
  227. }
  228. // Delete local copies of repositories and their wikis that are owned by the user
  229. rows, err := tx.Model(&Repository{}).Where("owner_id = ?", user.ID).Rows()
  230. if err != nil {
  231. return errors.Wrap(err, "iterate repositories")
  232. }
  233. defer func() { _ = rows.Close() }()
  234. for rows.Next() {
  235. var repo struct {
  236. ID int64
  237. }
  238. err = tx.ScanRows(rows, &repo)
  239. if err != nil {
  240. return errors.Wrap(err, "scan rows")
  241. }
  242. deleteRepoLocalCopy(repo.ID)
  243. RemoveAllWithNotice(fmt.Sprintf("Delete repository %d wiki local copy", repo.ID), repoutil.RepositoryLocalWikiPath(repo.ID))
  244. }
  245. if err = rows.Err(); err != nil {
  246. return errors.Wrap(err, "check rows.Err")
  247. }
  248. // Rename user directory if exists
  249. userPath := repoutil.UserPath(user.Name)
  250. if osutil.IsExist(userPath) {
  251. newUserPath := repoutil.UserPath(newUsername)
  252. err = os.Rename(userPath, newUserPath)
  253. if err != nil {
  254. return errors.Wrap(err, "rename user directory")
  255. }
  256. }
  257. return nil
  258. })
  259. }
  260. func (db *users) Count(ctx context.Context) int64 {
  261. var count int64
  262. db.WithContext(ctx).Model(&User{}).Where("type = ?", UserTypeIndividual).Count(&count)
  263. return count
  264. }
  265. type CreateUserOptions struct {
  266. FullName string
  267. Password string
  268. LoginSource int64
  269. LoginName string
  270. Location string
  271. Website string
  272. Activated bool
  273. Admin bool
  274. }
  275. type ErrUserAlreadyExist struct {
  276. args errutil.Args
  277. }
  278. // IsErrUserAlreadyExist returns true if the underlying error has the type
  279. // ErrUserAlreadyExist.
  280. func IsErrUserAlreadyExist(err error) bool {
  281. _, ok := errors.Cause(err).(ErrUserAlreadyExist)
  282. return ok
  283. }
  284. func (err ErrUserAlreadyExist) Error() string {
  285. return fmt.Sprintf("user already exists: %v", err.args)
  286. }
  287. type ErrEmailAlreadyUsed struct {
  288. args errutil.Args
  289. }
  290. // IsErrEmailAlreadyUsed returns true if the underlying error has the type
  291. // ErrEmailAlreadyUsed.
  292. func IsErrEmailAlreadyUsed(err error) bool {
  293. _, ok := errors.Cause(err).(ErrEmailAlreadyUsed)
  294. return ok
  295. }
  296. func (err ErrEmailAlreadyUsed) Email() string {
  297. email, ok := err.args["email"].(string)
  298. if ok {
  299. return email
  300. }
  301. return "<email not found>"
  302. }
  303. func (err ErrEmailAlreadyUsed) Error() string {
  304. return fmt.Sprintf("email has been used: %v", err.args)
  305. }
  306. func (db *users) Create(ctx context.Context, username, email string, opts CreateUserOptions) (*User, error) {
  307. err := isUsernameAllowed(username)
  308. if err != nil {
  309. return nil, err
  310. }
  311. if db.IsUsernameUsed(ctx, username, 0) {
  312. return nil, ErrUserAlreadyExist{
  313. args: errutil.Args{
  314. "name": username,
  315. },
  316. }
  317. }
  318. email = strings.ToLower(email)
  319. _, err = db.GetByEmail(ctx, email)
  320. if err == nil {
  321. return nil, ErrEmailAlreadyUsed{
  322. args: errutil.Args{
  323. "email": email,
  324. },
  325. }
  326. } else if !IsErrUserNotExist(err) {
  327. return nil, err
  328. }
  329. user := &User{
  330. LowerName: strings.ToLower(username),
  331. Name: username,
  332. FullName: opts.FullName,
  333. Email: email,
  334. Password: opts.Password,
  335. LoginSource: opts.LoginSource,
  336. LoginName: opts.LoginName,
  337. Location: opts.Location,
  338. Website: opts.Website,
  339. MaxRepoCreation: -1,
  340. IsActive: opts.Activated,
  341. IsAdmin: opts.Admin,
  342. Avatar: cryptoutil.MD5(email), // Gravatar URL uses the MD5 hash of the email, see https://en.gravatar.com/site/implement/hash/
  343. AvatarEmail: email,
  344. }
  345. user.Rands, err = userutil.RandomSalt()
  346. if err != nil {
  347. return nil, err
  348. }
  349. user.Salt, err = userutil.RandomSalt()
  350. if err != nil {
  351. return nil, err
  352. }
  353. user.Password = userutil.EncodePassword(user.Password, user.Salt)
  354. return user, db.WithContext(ctx).Create(user).Error
  355. }
  356. func (db *users) DeleteCustomAvatar(ctx context.Context, userID int64) error {
  357. _ = os.Remove(userutil.CustomAvatarPath(userID))
  358. return db.WithContext(ctx).
  359. Model(&User{}).
  360. Where("id = ?", userID).
  361. Updates(map[string]any{
  362. "use_custom_avatar": false,
  363. "updated_unix": db.NowFunc().Unix(),
  364. }).
  365. Error
  366. }
  367. var _ errutil.NotFound = (*ErrUserNotExist)(nil)
  368. type ErrUserNotExist struct {
  369. args errutil.Args
  370. }
  371. // IsErrUserNotExist returns true if the underlying error has the type
  372. // ErrUserNotExist.
  373. func IsErrUserNotExist(err error) bool {
  374. _, ok := errors.Cause(err).(ErrUserNotExist)
  375. return ok
  376. }
  377. func (err ErrUserNotExist) Error() string {
  378. return fmt.Sprintf("user does not exist: %v", err.args)
  379. }
  380. func (ErrUserNotExist) NotFound() bool {
  381. return true
  382. }
  383. func (db *users) GetByEmail(ctx context.Context, email string) (*User, error) {
  384. if email == "" {
  385. return nil, ErrUserNotExist{args: errutil.Args{"email": email}}
  386. }
  387. email = strings.ToLower(email)
  388. // First try to find the user by primary email
  389. user := new(User)
  390. err := db.WithContext(ctx).
  391. Where("email = ? AND type = ? AND is_active = ?", email, UserTypeIndividual, true).
  392. First(user).
  393. Error
  394. if err == nil {
  395. return user, nil
  396. } else if err != gorm.ErrRecordNotFound {
  397. return nil, err
  398. }
  399. // Otherwise, check activated email addresses
  400. emailAddress, err := NewEmailAddressesStore(db.DB).GetByEmail(ctx, email, true)
  401. if err != nil {
  402. if IsErrEmailAddressNotExist(err) {
  403. return nil, ErrUserNotExist{args: errutil.Args{"email": email}}
  404. }
  405. return nil, err
  406. }
  407. return db.GetByID(ctx, emailAddress.UserID)
  408. }
  409. func (db *users) GetByID(ctx context.Context, id int64) (*User, error) {
  410. user := new(User)
  411. err := db.WithContext(ctx).Where("id = ?", id).First(user).Error
  412. if err != nil {
  413. if err == gorm.ErrRecordNotFound {
  414. return nil, ErrUserNotExist{args: errutil.Args{"userID": id}}
  415. }
  416. return nil, err
  417. }
  418. return user, nil
  419. }
  420. func (db *users) GetByUsername(ctx context.Context, username string) (*User, error) {
  421. user := new(User)
  422. err := db.WithContext(ctx).Where("lower_name = ?", strings.ToLower(username)).First(user).Error
  423. if err != nil {
  424. if err == gorm.ErrRecordNotFound {
  425. return nil, ErrUserNotExist{args: errutil.Args{"name": username}}
  426. }
  427. return nil, err
  428. }
  429. return user, nil
  430. }
  431. func (db *users) GetByKeyID(ctx context.Context, keyID int64) (*User, error) {
  432. user := new(User)
  433. err := db.WithContext(ctx).
  434. Joins(dbutil.Quote("JOIN public_key ON public_key.owner_id = %s.id", "user")).
  435. Where("public_key.id = ?", keyID).
  436. First(user).
  437. Error
  438. if err != nil {
  439. if err == gorm.ErrRecordNotFound {
  440. return nil, ErrUserNotExist{args: errutil.Args{"keyID": keyID}}
  441. }
  442. return nil, err
  443. }
  444. return user, nil
  445. }
  446. func (db *users) HasForkedRepository(ctx context.Context, userID, repoID int64) bool {
  447. var count int64
  448. db.WithContext(ctx).Model(new(Repository)).Where("owner_id = ? AND fork_id = ?", userID, repoID).Count(&count)
  449. return count > 0
  450. }
  451. func (db *users) IsUsernameUsed(ctx context.Context, username string, excludeUserId int64) bool {
  452. if username == "" {
  453. return false
  454. }
  455. return db.WithContext(ctx).
  456. Select("id").
  457. Where("lower_name = ? AND id != ?", strings.ToLower(username), excludeUserId).
  458. First(&User{}).
  459. Error != gorm.ErrRecordNotFound
  460. }
  461. func (db *users) List(ctx context.Context, page, pageSize int) ([]*User, error) {
  462. users := make([]*User, 0, pageSize)
  463. return users, db.WithContext(ctx).
  464. Where("type = ?", UserTypeIndividual).
  465. Limit(pageSize).Offset((page - 1) * pageSize).
  466. Order("id ASC").
  467. Find(&users).
  468. Error
  469. }
  470. func (db *users) ListFollowers(ctx context.Context, userID int64, page, pageSize int) ([]*User, error) {
  471. /*
  472. Equivalent SQL for PostgreSQL:
  473. SELECT * FROM "user"
  474. LEFT JOIN follow ON follow.user_id = "user".id
  475. WHERE follow.follow_id = @userID
  476. ORDER BY follow.id DESC
  477. LIMIT @limit OFFSET @offset
  478. */
  479. users := make([]*User, 0, pageSize)
  480. return users, db.WithContext(ctx).
  481. Joins(dbutil.Quote("LEFT JOIN follow ON follow.user_id = %s.id", "user")).
  482. Where("follow.follow_id = ?", userID).
  483. Limit(pageSize).Offset((page - 1) * pageSize).
  484. Order("follow.id DESC").
  485. Find(&users).
  486. Error
  487. }
  488. func (db *users) ListFollowings(ctx context.Context, userID int64, page, pageSize int) ([]*User, error) {
  489. /*
  490. Equivalent SQL for PostgreSQL:
  491. SELECT * FROM "user"
  492. LEFT JOIN follow ON follow.user_id = "user".id
  493. WHERE follow.user_id = @userID
  494. ORDER BY follow.id DESC
  495. LIMIT @limit OFFSET @offset
  496. */
  497. users := make([]*User, 0, pageSize)
  498. return users, db.WithContext(ctx).
  499. Joins(dbutil.Quote("LEFT JOIN follow ON follow.follow_id = %s.id", "user")).
  500. Where("follow.user_id = ?", userID).
  501. Limit(pageSize).Offset((page - 1) * pageSize).
  502. Order("follow.id DESC").
  503. Find(&users).
  504. Error
  505. }
  506. func searchUserByName(ctx context.Context, db *gorm.DB, userType UserType, keyword string, page, pageSize int, orderBy string) ([]*User, int64, error) {
  507. if keyword == "" {
  508. return []*User{}, 0, nil
  509. }
  510. keyword = "%" + strings.ToLower(keyword) + "%"
  511. tx := db.WithContext(ctx).
  512. Where("type = ? AND (lower_name LIKE ? OR LOWER(full_name) LIKE ?)", userType, keyword, keyword)
  513. var count int64
  514. err := tx.Model(&User{}).Count(&count).Error
  515. if err != nil {
  516. return nil, 0, errors.Wrap(err, "count")
  517. }
  518. users := make([]*User, 0, pageSize)
  519. return users, count, tx.Order(orderBy).Limit(pageSize).Offset((page - 1) * pageSize).Find(&users).Error
  520. }
  521. func (db *users) SearchByName(ctx context.Context, keyword string, page, pageSize int, orderBy string) ([]*User, int64, error) {
  522. return searchUserByName(ctx, db.DB, UserTypeIndividual, keyword, page, pageSize, orderBy)
  523. }
  524. type UpdateUserOptions struct {
  525. LoginSource *int64
  526. LoginName *string
  527. Password *string
  528. // GenerateNewRands indicates whether to force generate new rands for the user.
  529. GenerateNewRands bool
  530. FullName *string
  531. Email *string
  532. Website *string
  533. Location *string
  534. Description *string
  535. MaxRepoCreation *int
  536. LastRepoVisibility *bool
  537. IsActivated *bool
  538. IsAdmin *bool
  539. AllowGitHook *bool
  540. AllowImportLocal *bool
  541. ProhibitLogin *bool
  542. Avatar *string
  543. AvatarEmail *string
  544. }
  545. func (db *users) Update(ctx context.Context, userID int64, opts UpdateUserOptions) error {
  546. updates := map[string]any{
  547. "updated_unix": db.NowFunc().Unix(),
  548. }
  549. if opts.LoginSource != nil {
  550. updates["login_source"] = *opts.LoginSource
  551. }
  552. if opts.LoginName != nil {
  553. updates["login_name"] = *opts.LoginName
  554. }
  555. if opts.Password != nil {
  556. salt, err := userutil.RandomSalt()
  557. if err != nil {
  558. return errors.Wrap(err, "generate salt")
  559. }
  560. updates["salt"] = salt
  561. updates["passwd"] = userutil.EncodePassword(*opts.Password, salt)
  562. opts.GenerateNewRands = true
  563. }
  564. if opts.GenerateNewRands {
  565. rands, err := userutil.RandomSalt()
  566. if err != nil {
  567. return errors.Wrap(err, "generate rands")
  568. }
  569. updates["rands"] = rands
  570. }
  571. if opts.FullName != nil {
  572. updates["full_name"] = strutil.Truncate(*opts.FullName, 255)
  573. }
  574. if opts.Email != nil {
  575. _, err := db.GetByEmail(ctx, *opts.Email)
  576. if err == nil {
  577. return ErrEmailAlreadyUsed{args: errutil.Args{"email": *opts.Email}}
  578. } else if !IsErrUserNotExist(err) {
  579. return errors.Wrap(err, "check email")
  580. }
  581. updates["email"] = *opts.Email
  582. }
  583. if opts.Website != nil {
  584. updates["website"] = strutil.Truncate(*opts.Website, 255)
  585. }
  586. if opts.Location != nil {
  587. updates["location"] = strutil.Truncate(*opts.Location, 255)
  588. }
  589. if opts.Description != nil {
  590. updates["description"] = strutil.Truncate(*opts.Description, 255)
  591. }
  592. if opts.MaxRepoCreation != nil {
  593. if *opts.MaxRepoCreation < -1 {
  594. *opts.MaxRepoCreation = -1
  595. }
  596. updates["max_repo_creation"] = *opts.MaxRepoCreation
  597. }
  598. if opts.LastRepoVisibility != nil {
  599. updates["last_repo_visibility"] = *opts.LastRepoVisibility
  600. }
  601. if opts.IsActivated != nil {
  602. updates["is_active"] = *opts.IsActivated
  603. }
  604. if opts.IsAdmin != nil {
  605. updates["is_admin"] = *opts.IsAdmin
  606. }
  607. if opts.AllowGitHook != nil {
  608. updates["allow_git_hook"] = *opts.AllowGitHook
  609. }
  610. if opts.AllowImportLocal != nil {
  611. updates["allow_import_local"] = *opts.AllowImportLocal
  612. }
  613. if opts.ProhibitLogin != nil {
  614. updates["prohibit_login"] = *opts.ProhibitLogin
  615. }
  616. if opts.Avatar != nil {
  617. updates["avatar"] = strutil.Truncate(*opts.Avatar, 2048)
  618. }
  619. if opts.AvatarEmail != nil {
  620. updates["avatar_email"] = strutil.Truncate(*opts.AvatarEmail, 255)
  621. }
  622. return db.WithContext(ctx).Model(&User{}).Where("id = ?", userID).Updates(updates).Error
  623. }
  624. func (db *users) UseCustomAvatar(ctx context.Context, userID int64, avatar []byte) error {
  625. err := userutil.SaveAvatar(userID, avatar)
  626. if err != nil {
  627. return errors.Wrap(err, "save avatar")
  628. }
  629. return db.WithContext(ctx).
  630. Model(&User{}).
  631. Where("id = ?", userID).
  632. Updates(map[string]any{
  633. "use_custom_avatar": true,
  634. "updated_unix": db.NowFunc().Unix(),
  635. }).
  636. Error
  637. }
  638. // UserType indicates the type of the user account.
  639. type UserType int
  640. const (
  641. UserTypeIndividual UserType = iota // NOTE: Historic reason to make it starts at 0.
  642. UserTypeOrganization
  643. )
  644. // User represents the object of an individual or an organization.
  645. type User struct {
  646. ID int64 `gorm:"primaryKey"`
  647. LowerName string `xorm:"UNIQUE NOT NULL" gorm:"unique;not null"`
  648. Name string `xorm:"UNIQUE NOT NULL" gorm:"not null"`
  649. FullName string
  650. // Email is the primary email address (to be used for communication)
  651. Email string `xorm:"NOT NULL" gorm:"not null"`
  652. Password string `xorm:"passwd NOT NULL" gorm:"column:passwd;not null"`
  653. LoginSource int64 `xorm:"NOT NULL DEFAULT 0" gorm:"not null;default:0"`
  654. LoginName string
  655. Type UserType
  656. Location string
  657. Website string
  658. Rands string `xorm:"VARCHAR(10)" gorm:"type:VARCHAR(10)"`
  659. Salt string `xorm:"VARCHAR(10)" gorm:"type:VARCHAR(10)"`
  660. Created time.Time `xorm:"-" gorm:"-" json:"-"`
  661. CreatedUnix int64
  662. Updated time.Time `xorm:"-" gorm:"-" json:"-"`
  663. UpdatedUnix int64
  664. // Remember visibility choice for convenience, true for private
  665. LastRepoVisibility bool
  666. // Maximum repository creation limit, -1 means use global default
  667. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1" gorm:"not null;default:-1"`
  668. // Permissions
  669. IsActive bool // Activate primary email
  670. IsAdmin bool
  671. AllowGitHook bool
  672. AllowImportLocal bool // Allow migrate repository by local path
  673. ProhibitLogin bool
  674. // Avatar
  675. Avatar string `xorm:"VARCHAR(2048) NOT NULL" gorm:"type:VARCHAR(2048);not null"`
  676. AvatarEmail string `xorm:"NOT NULL" gorm:"not null"`
  677. UseCustomAvatar bool
  678. // Counters
  679. NumFollowers int
  680. NumFollowing int `xorm:"NOT NULL DEFAULT 0" gorm:"not null;default:0"`
  681. NumStars int
  682. NumRepos int
  683. // For organization
  684. Description string
  685. NumTeams int
  686. NumMembers int
  687. Teams []*Team `xorm:"-" gorm:"-" json:"-"`
  688. Members []*User `xorm:"-" gorm:"-" json:"-"`
  689. }
  690. // BeforeCreate implements the GORM create hook.
  691. func (u *User) BeforeCreate(tx *gorm.DB) error {
  692. if u.CreatedUnix == 0 {
  693. u.CreatedUnix = tx.NowFunc().Unix()
  694. u.UpdatedUnix = u.CreatedUnix
  695. }
  696. return nil
  697. }
  698. // AfterFind implements the GORM query hook.
  699. func (u *User) AfterFind(_ *gorm.DB) error {
  700. u.Created = time.Unix(u.CreatedUnix, 0).Local()
  701. u.Updated = time.Unix(u.UpdatedUnix, 0).Local()
  702. return nil
  703. }
  704. // IsLocal returns true if the user is created as local account.
  705. func (u *User) IsLocal() bool {
  706. return u.LoginSource <= 0
  707. }
  708. // IsOrganization returns true if the user is an organization.
  709. func (u *User) IsOrganization() bool {
  710. return u.Type == UserTypeOrganization
  711. }
  712. // IsMailable returns true if the user is eligible to receive emails.
  713. func (u *User) IsMailable() bool {
  714. return u.IsActive
  715. }
  716. // APIFormat returns the API format of a user.
  717. func (u *User) APIFormat() *api.User {
  718. return &api.User{
  719. ID: u.ID,
  720. UserName: u.Name,
  721. Login: u.Name,
  722. FullName: u.FullName,
  723. Email: u.Email,
  724. AvatarUrl: u.AvatarURL(),
  725. }
  726. }
  727. // maxNumRepos returns the maximum number of repositories that the user can have
  728. // direct ownership.
  729. func (u *User) maxNumRepos() int {
  730. if u.MaxRepoCreation <= -1 {
  731. return conf.Repository.MaxCreationLimit
  732. }
  733. return u.MaxRepoCreation
  734. }
  735. // canCreateRepo returns true if the user can create a repository.
  736. func (u *User) canCreateRepo() bool {
  737. return u.maxNumRepos() <= -1 || u.NumRepos < u.maxNumRepos()
  738. }
  739. // CanCreateOrganization returns true if user can create organizations.
  740. func (u *User) CanCreateOrganization() bool {
  741. return !conf.Admin.DisableRegularOrgCreation || u.IsAdmin
  742. }
  743. // CanEditGitHook returns true if user can edit Git hooks.
  744. func (u *User) CanEditGitHook() bool {
  745. return u.IsAdmin || u.AllowGitHook
  746. }
  747. // CanImportLocal returns true if user can migrate repositories by local path.
  748. func (u *User) CanImportLocal() bool {
  749. return conf.Repository.EnableLocalPathMigration && (u.IsAdmin || u.AllowImportLocal)
  750. }
  751. // DisplayName returns the full name of the user if it's not empty, returns the
  752. // username otherwise.
  753. func (u *User) DisplayName() string {
  754. if len(u.FullName) > 0 {
  755. return u.FullName
  756. }
  757. return u.Name
  758. }
  759. // HomeURLPath returns the URL path to the user or organization home page.
  760. //
  761. // TODO(unknwon): This is also used in templates, which should be fixed by
  762. // having a dedicated type `template.User` and move this to the "userutil"
  763. // package.
  764. func (u *User) HomeURLPath() string {
  765. return conf.Server.Subpath + "/" + u.Name
  766. }
  767. // HTMLURL returns the full URL to the user or organization home page.
  768. //
  769. // TODO(unknwon): This is also used in templates, which should be fixed by
  770. // having a dedicated type `template.User` and move this to the "userutil"
  771. // package.
  772. func (u *User) HTMLURL() string {
  773. return conf.Server.ExternalURL + u.Name
  774. }
  775. // AvatarURLPath returns the URL path to the user or organization avatar. If the
  776. // user enables Gravatar-like service, then an external URL will be returned.
  777. //
  778. // TODO(unknwon): This is also used in templates, which should be fixed by
  779. // having a dedicated type `template.User` and move this to the "userutil"
  780. // package.
  781. func (u *User) AvatarURLPath() string {
  782. defaultURLPath := conf.UserDefaultAvatarURLPath()
  783. if u.ID <= 0 {
  784. return defaultURLPath
  785. }
  786. hasCustomAvatar := osutil.IsFile(userutil.CustomAvatarPath(u.ID))
  787. switch {
  788. case u.UseCustomAvatar:
  789. if !hasCustomAvatar {
  790. return defaultURLPath
  791. }
  792. return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, conf.UsersAvatarPathPrefix, u.ID)
  793. case conf.Picture.DisableGravatar:
  794. if !hasCustomAvatar {
  795. if err := userutil.GenerateRandomAvatar(u.ID, u.Name, u.Email); err != nil {
  796. log.Error("Failed to generate random avatar [user_id: %d]: %v", u.ID, err)
  797. }
  798. }
  799. return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, conf.UsersAvatarPathPrefix, u.ID)
  800. }
  801. return tool.AvatarLink(u.AvatarEmail)
  802. }
  803. // AvatarURL returns the full URL to the user or organization avatar. If the
  804. // user enables Gravatar-like service, then an external URL will be returned.
  805. //
  806. // TODO(unknwon): This is also used in templates, which should be fixed by
  807. // having a dedicated type `template.User` and move this to the "userutil"
  808. // package.
  809. func (u *User) AvatarURL() string {
  810. link := u.AvatarURLPath()
  811. if link[0] == '/' && link[1] != '/' {
  812. return conf.Server.ExternalURL + strings.TrimPrefix(link, conf.Server.Subpath)[1:]
  813. }
  814. return link
  815. }
  816. // IsFollowing returns true if the user is following the given user.
  817. //
  818. // TODO(unknwon): This is also used in templates, which should be fixed by
  819. // having a dedicated type `template.User`.
  820. func (u *User) IsFollowing(followID int64) bool {
  821. return Follows.IsFollowing(context.TODO(), u.ID, followID)
  822. }
  823. // IsUserOrgOwner returns true if the user is in the owner team of the given
  824. // organization.
  825. //
  826. // TODO(unknwon): This is also used in templates, which should be fixed by
  827. // having a dedicated type `template.User`.
  828. func (u *User) IsUserOrgOwner(orgId int64) bool {
  829. return IsOrganizationOwner(orgId, u.ID)
  830. }
  831. // IsPublicMember returns true if the user has public membership of the given
  832. // organization.
  833. //
  834. // TODO(unknwon): This is also used in templates, which should be fixed by
  835. // having a dedicated type `template.User`.
  836. func (u *User) IsPublicMember(orgId int64) bool {
  837. return IsPublicMembership(orgId, u.ID)
  838. }
  839. // GetOrganizationCount returns the count of organization membership that the
  840. // user has.
  841. //
  842. // TODO(unknwon): This is also used in templates, which should be fixed by
  843. // having a dedicated type `template.User`.
  844. func (u *User) GetOrganizationCount() (int64, error) {
  845. return OrgUsers.CountByUser(context.TODO(), u.ID)
  846. }
  847. // ShortName truncates and returns the username at most in given length.
  848. //
  849. // TODO(unknwon): This is also used in templates, which should be fixed by
  850. // having a dedicated type `template.User`.
  851. func (u *User) ShortName(length int) string {
  852. return strutil.Ellipsis(u.Name, length)
  853. }
  854. // NewGhostUser creates and returns a fake user for people who has deleted their
  855. // accounts.
  856. //
  857. // TODO: Once migrated to unknwon.dev/i18n, pass in the `i18n.Locale` to
  858. // translate the text to local language.
  859. func NewGhostUser() *User {
  860. return &User{
  861. ID: -1,
  862. Name: "Ghost",
  863. LowerName: "ghost",
  864. }
  865. }
  866. var (
  867. reservedUsernames = map[string]struct{}{
  868. "-": {},
  869. "explore": {},
  870. "create": {},
  871. "assets": {},
  872. "css": {},
  873. "img": {},
  874. "js": {},
  875. "less": {},
  876. "plugins": {},
  877. "debug": {},
  878. "raw": {},
  879. "install": {},
  880. "api": {},
  881. "avatar": {},
  882. "user": {},
  883. "org": {},
  884. "help": {},
  885. "stars": {},
  886. "issues": {},
  887. "pulls": {},
  888. "commits": {},
  889. "repo": {},
  890. "template": {},
  891. "admin": {},
  892. "new": {},
  893. ".": {},
  894. "..": {},
  895. }
  896. reservedUsernamePatterns = []string{"*.keys"}
  897. )
  898. type ErrNameNotAllowed struct {
  899. args errutil.Args
  900. }
  901. // IsErrNameNotAllowed returns true if the underlying error has the type
  902. // ErrNameNotAllowed.
  903. func IsErrNameNotAllowed(err error) bool {
  904. _, ok := errors.Cause(err).(ErrNameNotAllowed)
  905. return ok
  906. }
  907. func (err ErrNameNotAllowed) Value() string {
  908. val, ok := err.args["name"].(string)
  909. if ok {
  910. return val
  911. }
  912. val, ok = err.args["pattern"].(string)
  913. if ok {
  914. return val
  915. }
  916. return "<value not found>"
  917. }
  918. func (err ErrNameNotAllowed) Error() string {
  919. return fmt.Sprintf("name is not allowed: %v", err.args)
  920. }
  921. // isNameAllowed checks if the name is reserved or pattern of the name is not
  922. // allowed based on given reserved names and patterns. Names are exact match,
  923. // patterns can be prefix or suffix match with the wildcard ("*").
  924. func isNameAllowed(names map[string]struct{}, patterns []string, name string) error {
  925. name = strings.TrimSpace(strings.ToLower(name))
  926. if utf8.RuneCountInString(name) == 0 {
  927. return ErrNameNotAllowed{
  928. args: errutil.Args{
  929. "reason": "empty name",
  930. },
  931. }
  932. }
  933. if _, ok := names[name]; ok {
  934. return ErrNameNotAllowed{
  935. args: errutil.Args{
  936. "reason": "reserved",
  937. "name": name,
  938. },
  939. }
  940. }
  941. for _, pattern := range patterns {
  942. if pattern[0] == '*' && strings.HasSuffix(name, pattern[1:]) ||
  943. (pattern[len(pattern)-1] == '*' && strings.HasPrefix(name, pattern[:len(pattern)-1])) {
  944. return ErrNameNotAllowed{
  945. args: errutil.Args{
  946. "reason": "reserved",
  947. "pattern": pattern,
  948. },
  949. }
  950. }
  951. }
  952. return nil
  953. }
  954. // isUsernameAllowed returns ErrNameNotAllowed if the given name or pattern of
  955. // the name is not allowed as a username.
  956. func isUsernameAllowed(name string) error {
  957. return isNameAllowed(reservedUsernames, reservedUsernamePatterns, name)
  958. }