users.go 23 KB

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