users.go 31 KB

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