users.go 26 KB

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