users.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  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. "github.com/go-macaron/binding"
  12. api "github.com/gogs/go-gogs-client"
  13. "github.com/pkg/errors"
  14. "gorm.io/gorm"
  15. log "unknwon.dev/clog/v2"
  16. "gogs.io/gogs/internal/auth"
  17. "gogs.io/gogs/internal/conf"
  18. "gogs.io/gogs/internal/cryptoutil"
  19. "gogs.io/gogs/internal/dbutil"
  20. "gogs.io/gogs/internal/errutil"
  21. "gogs.io/gogs/internal/osutil"
  22. "gogs.io/gogs/internal/strutil"
  23. "gogs.io/gogs/internal/tool"
  24. "gogs.io/gogs/internal/userutil"
  25. )
  26. // UsersStore is the persistent interface for users.
  27. //
  28. // NOTE: All methods are sorted in alphabetical order.
  29. type UsersStore interface {
  30. // Authenticate validates username and password via given login source ID. It
  31. // returns ErrUserNotExist when the user was not found.
  32. //
  33. // When the "loginSourceID" is negative, it aborts the process and returns
  34. // ErrUserNotExist if the user was not found in the database.
  35. //
  36. // When the "loginSourceID" is non-negative, it returns ErrLoginSourceMismatch
  37. // if the user has different login source ID than the "loginSourceID".
  38. //
  39. // When the "loginSourceID" is positive, it tries to authenticate via given
  40. // login source and creates a new user when not yet exists in the database.
  41. Authenticate(ctx context.Context, username, password string, loginSourceID int64) (*User, error)
  42. // Create creates a new user and persists to database. It returns
  43. // ErrUserAlreadyExist when a user with same name already exists, or
  44. // ErrEmailAlreadyUsed if the email has been used by another user.
  45. Create(ctx context.Context, username, email string, opts CreateUserOptions) (*User, error)
  46. // DeleteCustomAvatar deletes the current user custom avatar and falls back to
  47. // use look up avatar by email.
  48. DeleteCustomAvatar(ctx context.Context, userID int64) error
  49. // GetByEmail returns the user (not organization) with given email. It ignores
  50. // records with unverified emails and returns ErrUserNotExist when not found.
  51. GetByEmail(ctx context.Context, email string) (*User, error)
  52. // GetByID returns the user with given ID. It returns ErrUserNotExist when not
  53. // found.
  54. GetByID(ctx context.Context, id int64) (*User, error)
  55. // GetByUsername returns the user with given username. It returns
  56. // ErrUserNotExist when not found.
  57. GetByUsername(ctx context.Context, username string) (*User, error)
  58. // HasForkedRepository returns true if the user has forked given repository.
  59. HasForkedRepository(ctx context.Context, userID, repoID int64) bool
  60. // IsUsernameUsed returns true if the given username has been used.
  61. IsUsernameUsed(ctx context.Context, username string) bool
  62. // ListFollowers returns a list of users that are following the given user.
  63. // Results are paginated by given page and page size, and sorted by the time of
  64. // follow in descending order.
  65. ListFollowers(ctx context.Context, userID int64, page, pageSize int) ([]*User, error)
  66. // ListFollowings returns a list of users that are followed by the given user.
  67. // Results are paginated by given page and page size, and sorted by the time of
  68. // follow in descending order.
  69. ListFollowings(ctx context.Context, userID int64, page, pageSize int) ([]*User, error)
  70. // UseCustomAvatar uses the given avatar as the user custom avatar.
  71. UseCustomAvatar(ctx context.Context, userID int64, avatar []byte) error
  72. }
  73. var Users UsersStore
  74. var _ UsersStore = (*users)(nil)
  75. type users struct {
  76. *gorm.DB
  77. }
  78. // NewUsersStore returns a persistent interface for users with given database
  79. // connection.
  80. func NewUsersStore(db *gorm.DB) UsersStore {
  81. return &users{DB: db}
  82. }
  83. type ErrLoginSourceMismatch struct {
  84. args errutil.Args
  85. }
  86. func (err ErrLoginSourceMismatch) Error() string {
  87. return fmt.Sprintf("login source mismatch: %v", err.args)
  88. }
  89. func (db *users) Authenticate(ctx context.Context, login, password string, loginSourceID int64) (*User, error) {
  90. login = strings.ToLower(login)
  91. query := db.WithContext(ctx)
  92. if strings.Contains(login, "@") {
  93. query = query.Where("email = ?", login)
  94. } else {
  95. query = query.Where("lower_name = ?", login)
  96. }
  97. user := new(User)
  98. err := query.First(user).Error
  99. if err != nil && err != gorm.ErrRecordNotFound {
  100. return nil, errors.Wrap(err, "get user")
  101. }
  102. var authSourceID int64 // The login source ID will be used to authenticate the user
  103. createNewUser := false // Whether to create a new user after successful authentication
  104. // User found in the database
  105. if err == nil {
  106. // Note: This check is unnecessary but to reduce user confusion at login page
  107. // and make it more consistent from user's perspective.
  108. if loginSourceID >= 0 && user.LoginSource != loginSourceID {
  109. return nil, ErrLoginSourceMismatch{args: errutil.Args{"expect": loginSourceID, "actual": user.LoginSource}}
  110. }
  111. // Validate password hash fetched from database for local accounts.
  112. if user.IsLocal() {
  113. if userutil.ValidatePassword(user.Password, user.Salt, password) {
  114. return user, nil
  115. }
  116. return nil, auth.ErrBadCredentials{Args: map[string]interface{}{"login": login, "userID": user.ID}}
  117. }
  118. authSourceID = user.LoginSource
  119. } else {
  120. // Non-local login source is always greater than 0.
  121. if loginSourceID <= 0 {
  122. return nil, auth.ErrBadCredentials{Args: map[string]interface{}{"login": login}}
  123. }
  124. authSourceID = loginSourceID
  125. createNewUser = true
  126. }
  127. source, err := LoginSources.GetByID(ctx, authSourceID)
  128. if err != nil {
  129. return nil, errors.Wrap(err, "get login source")
  130. }
  131. if !source.IsActived {
  132. return nil, errors.Errorf("login source %d is not activated", source.ID)
  133. }
  134. extAccount, err := source.Provider.Authenticate(login, password)
  135. if err != nil {
  136. return nil, err
  137. }
  138. if !createNewUser {
  139. return user, nil
  140. }
  141. // Validate username make sure it satisfies requirement.
  142. if binding.AlphaDashDotPattern.MatchString(extAccount.Name) {
  143. return nil, fmt.Errorf("invalid pattern for attribute 'username' [%s]: must be valid alpha or numeric or dash(-_) or dot characters", extAccount.Name)
  144. }
  145. return db.Create(ctx, extAccount.Name, extAccount.Email,
  146. CreateUserOptions{
  147. FullName: extAccount.FullName,
  148. LoginSource: authSourceID,
  149. LoginName: extAccount.Login,
  150. Location: extAccount.Location,
  151. Website: extAccount.Website,
  152. Activated: true,
  153. Admin: extAccount.Admin,
  154. },
  155. )
  156. }
  157. type CreateUserOptions struct {
  158. FullName string
  159. Password string
  160. LoginSource int64
  161. LoginName string
  162. Location string
  163. Website string
  164. Activated bool
  165. Admin bool
  166. }
  167. type ErrUserAlreadyExist struct {
  168. args errutil.Args
  169. }
  170. func IsErrUserAlreadyExist(err error) bool {
  171. _, ok := err.(ErrUserAlreadyExist)
  172. return ok
  173. }
  174. func (err ErrUserAlreadyExist) Error() string {
  175. return fmt.Sprintf("user already exists: %v", err.args)
  176. }
  177. type ErrEmailAlreadyUsed struct {
  178. args errutil.Args
  179. }
  180. func IsErrEmailAlreadyUsed(err error) bool {
  181. _, ok := err.(ErrEmailAlreadyUsed)
  182. return ok
  183. }
  184. func (err ErrEmailAlreadyUsed) Email() string {
  185. email, ok := err.args["email"].(string)
  186. if ok {
  187. return email
  188. }
  189. return "<email not found>"
  190. }
  191. func (err ErrEmailAlreadyUsed) Error() string {
  192. return fmt.Sprintf("email has been used: %v", err.args)
  193. }
  194. func (db *users) Create(ctx context.Context, username, email string, opts CreateUserOptions) (*User, error) {
  195. err := isUsernameAllowed(username)
  196. if err != nil {
  197. return nil, err
  198. }
  199. if db.IsUsernameUsed(ctx, username) {
  200. return nil, ErrUserAlreadyExist{args: errutil.Args{"name": username}}
  201. }
  202. _, err = db.GetByEmail(ctx, email)
  203. if err == nil {
  204. return nil, ErrEmailAlreadyUsed{args: errutil.Args{"email": email}}
  205. } else if !IsErrUserNotExist(err) {
  206. return nil, err
  207. }
  208. user := &User{
  209. LowerName: strings.ToLower(username),
  210. Name: username,
  211. FullName: opts.FullName,
  212. Email: email,
  213. Password: opts.Password,
  214. LoginSource: opts.LoginSource,
  215. LoginName: opts.LoginName,
  216. Location: opts.Location,
  217. Website: opts.Website,
  218. MaxRepoCreation: -1,
  219. IsActive: opts.Activated,
  220. IsAdmin: opts.Admin,
  221. Avatar: cryptoutil.MD5(email),
  222. AvatarEmail: email,
  223. }
  224. user.Rands, err = userutil.RandomSalt()
  225. if err != nil {
  226. return nil, err
  227. }
  228. user.Salt, err = userutil.RandomSalt()
  229. if err != nil {
  230. return nil, err
  231. }
  232. user.Password = userutil.EncodePassword(user.Password, user.Salt)
  233. return user, db.WithContext(ctx).Create(user).Error
  234. }
  235. func (db *users) DeleteCustomAvatar(ctx context.Context, userID int64) error {
  236. _ = os.Remove(userutil.CustomAvatarPath(userID))
  237. return db.WithContext(ctx).
  238. Model(&User{}).
  239. Where("id = ?", userID).
  240. Updates(map[string]interface{}{
  241. "use_custom_avatar": false,
  242. "updated_unix": db.NowFunc().Unix(),
  243. }).
  244. Error
  245. }
  246. var _ errutil.NotFound = (*ErrUserNotExist)(nil)
  247. type ErrUserNotExist struct {
  248. args errutil.Args
  249. }
  250. func IsErrUserNotExist(err error) bool {
  251. _, ok := err.(ErrUserNotExist)
  252. return ok
  253. }
  254. func (err ErrUserNotExist) Error() string {
  255. return fmt.Sprintf("user does not exist: %v", err.args)
  256. }
  257. func (ErrUserNotExist) NotFound() bool {
  258. return true
  259. }
  260. func (db *users) GetByEmail(ctx context.Context, email string) (*User, error) {
  261. email = strings.ToLower(email)
  262. if email == "" {
  263. return nil, ErrUserNotExist{args: errutil.Args{"email": email}}
  264. }
  265. // First try to find the user by primary email
  266. user := new(User)
  267. err := db.WithContext(ctx).
  268. Where("email = ? AND type = ? AND is_active = ?", email, UserTypeIndividual, true).
  269. First(user).
  270. Error
  271. if err == nil {
  272. return user, nil
  273. } else if err != gorm.ErrRecordNotFound {
  274. return nil, err
  275. }
  276. // Otherwise, check activated email addresses
  277. emailAddress := new(EmailAddress)
  278. err = db.WithContext(ctx).
  279. Where("email = ? AND is_activated = ?", email, true).
  280. First(emailAddress).
  281. Error
  282. if err != nil {
  283. if err == gorm.ErrRecordNotFound {
  284. return nil, ErrUserNotExist{args: errutil.Args{"email": email}}
  285. }
  286. return nil, err
  287. }
  288. return db.GetByID(ctx, emailAddress.UID)
  289. }
  290. func (db *users) GetByID(ctx context.Context, id int64) (*User, error) {
  291. user := new(User)
  292. err := db.WithContext(ctx).Where("id = ?", id).First(user).Error
  293. if err != nil {
  294. if err == gorm.ErrRecordNotFound {
  295. return nil, ErrUserNotExist{args: errutil.Args{"userID": id}}
  296. }
  297. return nil, err
  298. }
  299. return user, nil
  300. }
  301. func (db *users) GetByUsername(ctx context.Context, username string) (*User, error) {
  302. user := new(User)
  303. err := db.WithContext(ctx).Where("lower_name = ?", strings.ToLower(username)).First(user).Error
  304. if err != nil {
  305. if err == gorm.ErrRecordNotFound {
  306. return nil, ErrUserNotExist{args: errutil.Args{"name": username}}
  307. }
  308. return nil, err
  309. }
  310. return user, nil
  311. }
  312. func (db *users) HasForkedRepository(ctx context.Context, userID, repoID int64) bool {
  313. var count int64
  314. db.WithContext(ctx).Model(new(Repository)).Where("owner_id = ? AND fork_id = ?", userID, repoID).Count(&count)
  315. return count > 0
  316. }
  317. func (db *users) IsUsernameUsed(ctx context.Context, username string) bool {
  318. if username == "" {
  319. return false
  320. }
  321. return db.WithContext(ctx).
  322. Select("id").
  323. Where("lower_name = ?", strings.ToLower(username)).
  324. First(&User{}).
  325. Error != gorm.ErrRecordNotFound
  326. }
  327. func (db *users) ListFollowers(ctx context.Context, userID int64, page, pageSize int) ([]*User, error) {
  328. /*
  329. Equivalent SQL for PostgreSQL:
  330. SELECT * FROM "user"
  331. LEFT JOIN follow ON follow.user_id = "user".id
  332. WHERE follow.follow_id = @userID
  333. ORDER BY follow.id DESC
  334. LIMIT @limit OFFSET @offset
  335. */
  336. users := make([]*User, 0, pageSize)
  337. return users, db.WithContext(ctx).
  338. Joins(dbutil.Quote("LEFT JOIN follow ON follow.user_id = %s.id", "user")).
  339. Where("follow.follow_id = ?", userID).
  340. Limit(pageSize).Offset((page - 1) * pageSize).
  341. Order("follow.id DESC").
  342. Find(&users).
  343. Error
  344. }
  345. func (db *users) ListFollowings(ctx context.Context, userID int64, page, pageSize int) ([]*User, error) {
  346. /*
  347. Equivalent SQL for PostgreSQL:
  348. SELECT * FROM "user"
  349. LEFT JOIN follow ON follow.user_id = "user".id
  350. WHERE follow.user_id = @userID
  351. ORDER BY follow.id DESC
  352. LIMIT @limit OFFSET @offset
  353. */
  354. users := make([]*User, 0, pageSize)
  355. return users, db.WithContext(ctx).
  356. Joins(dbutil.Quote("LEFT JOIN follow ON follow.follow_id = %s.id", "user")).
  357. Where("follow.user_id = ?", userID).
  358. Limit(pageSize).Offset((page - 1) * pageSize).
  359. Order("follow.id DESC").
  360. Find(&users).
  361. Error
  362. }
  363. func (db *users) UseCustomAvatar(ctx context.Context, userID int64, avatar []byte) error {
  364. err := userutil.SaveAvatar(userID, avatar)
  365. if err != nil {
  366. return errors.Wrap(err, "save avatar")
  367. }
  368. return db.WithContext(ctx).
  369. Model(&User{}).
  370. Where("id = ?", userID).
  371. Updates(map[string]interface{}{
  372. "use_custom_avatar": true,
  373. "updated_unix": db.NowFunc().Unix(),
  374. }).
  375. Error
  376. }
  377. // UserType indicates the type of the user account.
  378. type UserType int
  379. const (
  380. UserTypeIndividual UserType = iota // NOTE: Historic reason to make it starts at 0.
  381. UserTypeOrganization
  382. )
  383. // User represents the object of an individual or an organization.
  384. type User struct {
  385. ID int64 `gorm:"primaryKey"`
  386. LowerName string `xorm:"UNIQUE NOT NULL" gorm:"unique;not null"`
  387. Name string `xorm:"UNIQUE NOT NULL" gorm:"not null"`
  388. FullName string
  389. // Email is the primary email address (to be used for communication)
  390. Email string `xorm:"NOT NULL" gorm:"not null"`
  391. Password string `xorm:"passwd NOT NULL" gorm:"column:passwd;not null"`
  392. LoginSource int64 `xorm:"NOT NULL DEFAULT 0" gorm:"not null;default:0"`
  393. LoginName string
  394. Type UserType
  395. Location string
  396. Website string
  397. Rands string `xorm:"VARCHAR(10)" gorm:"type:VARCHAR(10)"`
  398. Salt string `xorm:"VARCHAR(10)" gorm:"type:VARCHAR(10)"`
  399. Created time.Time `xorm:"-" gorm:"-" json:"-"`
  400. CreatedUnix int64
  401. Updated time.Time `xorm:"-" gorm:"-" json:"-"`
  402. UpdatedUnix int64
  403. // Remember visibility choice for convenience, true for private
  404. LastRepoVisibility bool
  405. // Maximum repository creation limit, -1 means use global default
  406. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1" gorm:"not null;default:-1"`
  407. // Permissions
  408. IsActive bool // Activate primary email
  409. IsAdmin bool
  410. AllowGitHook bool
  411. AllowImportLocal bool // Allow migrate repository by local path
  412. ProhibitLogin bool
  413. // Avatar
  414. Avatar string `xorm:"VARCHAR(2048) NOT NULL" gorm:"type:VARCHAR(2048);not null"`
  415. AvatarEmail string `xorm:"NOT NULL" gorm:"not null"`
  416. UseCustomAvatar bool
  417. // Counters
  418. NumFollowers int
  419. NumFollowing int `xorm:"NOT NULL DEFAULT 0" gorm:"not null;default:0"`
  420. NumStars int
  421. NumRepos int
  422. // For organization
  423. Description string
  424. NumTeams int
  425. NumMembers int
  426. Teams []*Team `xorm:"-" gorm:"-" json:"-"`
  427. Members []*User `xorm:"-" gorm:"-" json:"-"`
  428. }
  429. // BeforeCreate implements the GORM create hook.
  430. func (u *User) BeforeCreate(tx *gorm.DB) error {
  431. if u.CreatedUnix == 0 {
  432. u.CreatedUnix = tx.NowFunc().Unix()
  433. u.UpdatedUnix = u.CreatedUnix
  434. }
  435. return nil
  436. }
  437. // AfterFind implements the GORM query hook.
  438. func (u *User) AfterFind(_ *gorm.DB) error {
  439. u.Created = time.Unix(u.CreatedUnix, 0).Local()
  440. u.Updated = time.Unix(u.UpdatedUnix, 0).Local()
  441. return nil
  442. }
  443. // IsLocal returns true if the user is created as local account.
  444. func (u *User) IsLocal() bool {
  445. return u.LoginSource <= 0
  446. }
  447. // IsOrganization returns true if the user is an organization.
  448. func (u *User) IsOrganization() bool {
  449. return u.Type == UserTypeOrganization
  450. }
  451. // IsMailable returns true if the user is eligible to receive emails.
  452. func (u *User) IsMailable() bool {
  453. return u.IsActive
  454. }
  455. // APIFormat returns the API format of a user.
  456. func (u *User) APIFormat() *api.User {
  457. return &api.User{
  458. ID: u.ID,
  459. UserName: u.Name,
  460. Login: u.Name,
  461. FullName: u.FullName,
  462. Email: u.Email,
  463. AvatarUrl: u.AvatarURL(),
  464. }
  465. }
  466. // maxNumRepos returns the maximum number of repositories that the user can have
  467. // direct ownership.
  468. func (u *User) maxNumRepos() int {
  469. if u.MaxRepoCreation <= -1 {
  470. return conf.Repository.MaxCreationLimit
  471. }
  472. return u.MaxRepoCreation
  473. }
  474. // canCreateRepo returns true if the user can create a repository.
  475. func (u *User) canCreateRepo() bool {
  476. return u.maxNumRepos() <= -1 || u.NumRepos < u.maxNumRepos()
  477. }
  478. // CanCreateOrganization returns true if user can create organizations.
  479. func (u *User) CanCreateOrganization() bool {
  480. return !conf.Admin.DisableRegularOrgCreation || u.IsAdmin
  481. }
  482. // CanEditGitHook returns true if user can edit Git hooks.
  483. func (u *User) CanEditGitHook() bool {
  484. return u.IsAdmin || u.AllowGitHook
  485. }
  486. // CanImportLocal returns true if user can migrate repositories by local path.
  487. func (u *User) CanImportLocal() bool {
  488. return conf.Repository.EnableLocalPathMigration && (u.IsAdmin || u.AllowImportLocal)
  489. }
  490. // DisplayName returns the full name of the user if it's not empty, returns the
  491. // username otherwise.
  492. func (u *User) DisplayName() string {
  493. if len(u.FullName) > 0 {
  494. return u.FullName
  495. }
  496. return u.Name
  497. }
  498. // NewGhostUser creates and returns a fake user for people who has deleted their
  499. // accounts.
  500. func NewGhostUser() *User {
  501. return &User{
  502. ID: -1,
  503. Name: "Ghost",
  504. LowerName: "ghost",
  505. }
  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. }