users.go 26 KB

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