users.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  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/errutil"
  20. "gogs.io/gogs/internal/osutil"
  21. "gogs.io/gogs/internal/strutil"
  22. "gogs.io/gogs/internal/tool"
  23. "gogs.io/gogs/internal/userutil"
  24. )
  25. // UsersStore is the persistent interface for users.
  26. //
  27. // NOTE: All methods are sorted in alphabetical order.
  28. type UsersStore interface {
  29. // Authenticate validates username and password via given login source ID. It
  30. // returns ErrUserNotExist when the user was not found.
  31. //
  32. // When the "loginSourceID" is negative, it aborts the process and returns
  33. // ErrUserNotExist if the user was not found in the database.
  34. //
  35. // When the "loginSourceID" is non-negative, it returns ErrLoginSourceMismatch
  36. // if the user has different login source ID than the "loginSourceID".
  37. //
  38. // When the "loginSourceID" is positive, it tries to authenticate via given
  39. // login source and creates a new user when not yet exists in the database.
  40. Authenticate(ctx context.Context, username, password string, loginSourceID int64) (*User, error)
  41. // Create creates a new user and persists to database. It returns
  42. // ErrUserAlreadyExist when a user with same name already exists, or
  43. // ErrEmailAlreadyUsed if the email has been used by another user.
  44. Create(ctx context.Context, username, email string, opts CreateUserOptions) (*User, error)
  45. // DeleteCustomAvatar deletes the current user custom avatar and falls back to
  46. // use look up avatar by email.
  47. DeleteCustomAvatar(ctx context.Context, userID int64) error
  48. // GetByEmail returns the user (not organization) with given email. It ignores
  49. // records with unverified emails and returns ErrUserNotExist when not found.
  50. GetByEmail(ctx context.Context, email string) (*User, error)
  51. // GetByID returns the user with given ID. It returns ErrUserNotExist when not
  52. // found.
  53. GetByID(ctx context.Context, id int64) (*User, error)
  54. // GetByUsername returns the user with given username. It returns
  55. // ErrUserNotExist when not found.
  56. GetByUsername(ctx context.Context, username string) (*User, error)
  57. // HasForkedRepository returns true if the user has forked given repository.
  58. HasForkedRepository(ctx context.Context, userID, repoID int64) bool
  59. // ListFollowers returns a list of users that are following the given user.
  60. // Results are paginated by given page and page size, and sorted by the time of
  61. // follow in descending order.
  62. ListFollowers(ctx context.Context, userID int64, page, pageSize int) ([]*User, error)
  63. // ListFollowings returns a list of users that are followed by 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. ListFollowings(ctx context.Context, userID int64, page, pageSize int) ([]*User, error)
  67. // UseCustomAvatar uses the given avatar as the user custom avatar.
  68. UseCustomAvatar(ctx context.Context, userID int64, avatar []byte) error
  69. }
  70. var Users UsersStore
  71. var _ UsersStore = (*users)(nil)
  72. type users struct {
  73. *gorm.DB
  74. }
  75. // NewUsersStore returns a persistent interface for users with given database
  76. // connection.
  77. func NewUsersStore(db *gorm.DB) UsersStore {
  78. return &users{DB: db}
  79. }
  80. type ErrLoginSourceMismatch struct {
  81. args errutil.Args
  82. }
  83. func (err ErrLoginSourceMismatch) Error() string {
  84. return fmt.Sprintf("login source mismatch: %v", err.args)
  85. }
  86. func (db *users) Authenticate(ctx context.Context, login, password string, loginSourceID int64) (*User, error) {
  87. login = strings.ToLower(login)
  88. query := db.WithContext(ctx)
  89. if strings.Contains(login, "@") {
  90. query = query.Where("email = ?", login)
  91. } else {
  92. query = query.Where("lower_name = ?", login)
  93. }
  94. user := new(User)
  95. err := query.First(user).Error
  96. if err != nil && err != gorm.ErrRecordNotFound {
  97. return nil, errors.Wrap(err, "get user")
  98. }
  99. var authSourceID int64 // The login source ID will be used to authenticate the user
  100. createNewUser := false // Whether to create a new user after successful authentication
  101. // User found in the database
  102. if err == nil {
  103. // Note: This check is unnecessary but to reduce user confusion at login page
  104. // and make it more consistent from user's perspective.
  105. if loginSourceID >= 0 && user.LoginSource != loginSourceID {
  106. return nil, ErrLoginSourceMismatch{args: errutil.Args{"expect": loginSourceID, "actual": user.LoginSource}}
  107. }
  108. // Validate password hash fetched from database for local accounts.
  109. if user.IsLocal() {
  110. if userutil.ValidatePassword(user.Password, user.Salt, password) {
  111. return user, nil
  112. }
  113. return nil, auth.ErrBadCredentials{Args: map[string]interface{}{"login": login, "userID": user.ID}}
  114. }
  115. authSourceID = user.LoginSource
  116. } else {
  117. // Non-local login source is always greater than 0.
  118. if loginSourceID <= 0 {
  119. return nil, auth.ErrBadCredentials{Args: map[string]interface{}{"login": login}}
  120. }
  121. authSourceID = loginSourceID
  122. createNewUser = true
  123. }
  124. source, err := LoginSources.GetByID(ctx, authSourceID)
  125. if err != nil {
  126. return nil, errors.Wrap(err, "get login source")
  127. }
  128. if !source.IsActived {
  129. return nil, errors.Errorf("login source %d is not activated", source.ID)
  130. }
  131. extAccount, err := source.Provider.Authenticate(login, password)
  132. if err != nil {
  133. return nil, err
  134. }
  135. if !createNewUser {
  136. return user, nil
  137. }
  138. // Validate username make sure it satisfies requirement.
  139. if binding.AlphaDashDotPattern.MatchString(extAccount.Name) {
  140. return nil, fmt.Errorf("invalid pattern for attribute 'username' [%s]: must be valid alpha or numeric or dash(-_) or dot characters", extAccount.Name)
  141. }
  142. return db.Create(ctx, extAccount.Name, extAccount.Email,
  143. CreateUserOptions{
  144. FullName: extAccount.FullName,
  145. LoginSource: authSourceID,
  146. LoginName: extAccount.Login,
  147. Location: extAccount.Location,
  148. Website: extAccount.Website,
  149. Activated: true,
  150. Admin: extAccount.Admin,
  151. },
  152. )
  153. }
  154. type CreateUserOptions struct {
  155. FullName string
  156. Password string
  157. LoginSource int64
  158. LoginName string
  159. Location string
  160. Website string
  161. Activated bool
  162. Admin bool
  163. }
  164. type ErrUserAlreadyExist struct {
  165. args errutil.Args
  166. }
  167. func IsErrUserAlreadyExist(err error) bool {
  168. _, ok := err.(ErrUserAlreadyExist)
  169. return ok
  170. }
  171. func (err ErrUserAlreadyExist) Error() string {
  172. return fmt.Sprintf("user already exists: %v", err.args)
  173. }
  174. type ErrEmailAlreadyUsed struct {
  175. args errutil.Args
  176. }
  177. func IsErrEmailAlreadyUsed(err error) bool {
  178. _, ok := err.(ErrEmailAlreadyUsed)
  179. return ok
  180. }
  181. func (err ErrEmailAlreadyUsed) Email() string {
  182. email, ok := err.args["email"].(string)
  183. if ok {
  184. return email
  185. }
  186. return "<email not found>"
  187. }
  188. func (err ErrEmailAlreadyUsed) Error() string {
  189. return fmt.Sprintf("email has been used: %v", err.args)
  190. }
  191. func (db *users) Create(ctx context.Context, username, email string, opts CreateUserOptions) (*User, error) {
  192. err := isUsernameAllowed(username)
  193. if err != nil {
  194. return nil, err
  195. }
  196. _, err = db.GetByUsername(ctx, username)
  197. if err == nil {
  198. return nil, ErrUserAlreadyExist{args: errutil.Args{"name": username}}
  199. } else if !IsErrUserNotExist(err) {
  200. return nil, err
  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 = GetUserSalt()
  225. if err != nil {
  226. return nil, err
  227. }
  228. user.Salt, err = GetUserSalt()
  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) ListFollowers(ctx context.Context, userID int64, page, pageSize int) ([]*User, error) {
  318. /*
  319. Equivalent SQL for PostgreSQL:
  320. SELECT * FROM "user"
  321. LEFT JOIN follow ON follow.user_id = "user".id
  322. WHERE follow.follow_id = @userID
  323. ORDER BY follow.id DESC
  324. LIMIT @limit OFFSET @offset
  325. */
  326. users := make([]*User, 0, pageSize)
  327. tx := db.WithContext(ctx).
  328. Where("follow.follow_id = ?", userID).
  329. Limit(pageSize).Offset((page - 1) * pageSize).
  330. Order("follow.id DESC")
  331. if conf.UsePostgreSQL {
  332. tx.Joins(`LEFT JOIN follow ON follow.user_id = "user".id`)
  333. } else {
  334. tx.Joins(`LEFT JOIN follow ON follow.user_id = user.id`)
  335. }
  336. return users, tx.Find(&users).Error
  337. }
  338. func (db *users) ListFollowings(ctx context.Context, userID int64, page, pageSize int) ([]*User, error) {
  339. /*
  340. Equivalent SQL for PostgreSQL:
  341. SELECT * FROM "user"
  342. LEFT JOIN follow ON follow.user_id = "user".id
  343. WHERE follow.user_id = @userID
  344. ORDER BY follow.id DESC
  345. LIMIT @limit OFFSET @offset
  346. */
  347. users := make([]*User, 0, pageSize)
  348. tx := db.WithContext(ctx).
  349. Where("follow.user_id = ?", userID).
  350. Limit(pageSize).Offset((page - 1) * pageSize).
  351. Order("follow.id DESC")
  352. if conf.UsePostgreSQL {
  353. tx.Joins(`LEFT JOIN follow ON follow.follow_id = "user".id`)
  354. } else {
  355. tx.Joins(`LEFT JOIN follow ON follow.follow_id = user.id`)
  356. }
  357. return users, tx.Find(&users).Error
  358. }
  359. func (db *users) UseCustomAvatar(ctx context.Context, userID int64, avatar []byte) error {
  360. err := userutil.SaveAvatar(userID, avatar)
  361. if err != nil {
  362. return errors.Wrap(err, "save avatar")
  363. }
  364. return db.WithContext(ctx).
  365. Model(&User{}).
  366. Where("id = ?", userID).
  367. Updates(map[string]interface{}{
  368. "use_custom_avatar": true,
  369. "updated_unix": db.NowFunc().Unix(),
  370. }).
  371. Error
  372. }
  373. // UserType indicates the type of the user account.
  374. type UserType int
  375. const (
  376. UserTypeIndividual UserType = iota // NOTE: Historic reason to make it starts at 0.
  377. UserTypeOrganization
  378. )
  379. // User represents the object of an individual or an organization.
  380. type User struct {
  381. ID int64 `gorm:"primaryKey"`
  382. LowerName string `xorm:"UNIQUE NOT NULL" gorm:"unique;not null"`
  383. Name string `xorm:"UNIQUE NOT NULL" gorm:"not null"`
  384. FullName string
  385. // Email is the primary email address (to be used for communication)
  386. Email string `xorm:"NOT NULL" gorm:"not null"`
  387. Password string `xorm:"passwd NOT NULL" gorm:"column:passwd;not null"`
  388. LoginSource int64 `xorm:"NOT NULL DEFAULT 0" gorm:"not null;default:0"`
  389. LoginName string
  390. Type UserType
  391. Orgs []*User `xorm:"-" gorm:"-" json:"-"`
  392. Location string
  393. Website string
  394. Rands string `xorm:"VARCHAR(10)" gorm:"type:VARCHAR(10)"`
  395. Salt string `xorm:"VARCHAR(10)" gorm:"type:VARCHAR(10)"`
  396. Created time.Time `xorm:"-" gorm:"-" json:"-"`
  397. CreatedUnix int64
  398. Updated time.Time `xorm:"-" gorm:"-" json:"-"`
  399. UpdatedUnix int64
  400. // Remember visibility choice for convenience, true for private
  401. LastRepoVisibility bool
  402. // Maximum repository creation limit, -1 means use global default
  403. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1" gorm:"not null;default:-1"`
  404. // Permissions
  405. IsActive bool // Activate primary email
  406. IsAdmin bool
  407. AllowGitHook bool
  408. AllowImportLocal bool // Allow migrate repository by local path
  409. ProhibitLogin bool
  410. // Avatar
  411. Avatar string `xorm:"VARCHAR(2048) NOT NULL" gorm:"type:VARCHAR(2048);not null"`
  412. AvatarEmail string `xorm:"NOT NULL" gorm:"not null"`
  413. UseCustomAvatar bool
  414. // Counters
  415. NumFollowers int
  416. NumFollowing int `xorm:"NOT NULL DEFAULT 0" gorm:"not null;default:0"`
  417. NumStars int
  418. NumRepos int
  419. // For organization
  420. Description string
  421. NumTeams int
  422. NumMembers int
  423. Teams []*Team `xorm:"-" gorm:"-" json:"-"`
  424. Members []*User `xorm:"-" gorm:"-" json:"-"`
  425. }
  426. // BeforeCreate implements the GORM create hook.
  427. func (u *User) BeforeCreate(tx *gorm.DB) error {
  428. if u.CreatedUnix == 0 {
  429. u.CreatedUnix = tx.NowFunc().Unix()
  430. u.UpdatedUnix = u.CreatedUnix
  431. }
  432. return nil
  433. }
  434. // AfterFind implements the GORM query hook.
  435. func (u *User) AfterFind(_ *gorm.DB) error {
  436. u.Created = time.Unix(u.CreatedUnix, 0).Local()
  437. u.Updated = time.Unix(u.UpdatedUnix, 0).Local()
  438. return nil
  439. }
  440. // IsLocal returns true if the user is created as local account.
  441. func (u *User) IsLocal() bool {
  442. return u.LoginSource <= 0
  443. }
  444. // IsOrganization returns true if the user is an organization.
  445. func (u *User) IsOrganization() bool {
  446. return u.Type == UserTypeOrganization
  447. }
  448. // IsMailable returns true if the user is eligible to receive emails.
  449. func (u *User) IsMailable() bool {
  450. return u.IsActive
  451. }
  452. // APIFormat returns the API format of a user.
  453. func (u *User) APIFormat() *api.User {
  454. return &api.User{
  455. ID: u.ID,
  456. UserName: u.Name,
  457. Login: u.Name,
  458. FullName: u.FullName,
  459. Email: u.Email,
  460. AvatarUrl: u.AvatarURL(),
  461. }
  462. }
  463. // maxNumRepos returns the maximum number of repositories that the user can have
  464. // direct ownership.
  465. func (u *User) maxNumRepos() int {
  466. if u.MaxRepoCreation <= -1 {
  467. return conf.Repository.MaxCreationLimit
  468. }
  469. return u.MaxRepoCreation
  470. }
  471. // canCreateRepo returns true if the user can create a repository.
  472. func (u *User) canCreateRepo() bool {
  473. return u.maxNumRepos() <= -1 || u.NumRepos < u.maxNumRepos()
  474. }
  475. // CanCreateOrganization returns true if user can create organizations.
  476. func (u *User) CanCreateOrganization() bool {
  477. return !conf.Admin.DisableRegularOrgCreation || u.IsAdmin
  478. }
  479. // CanEditGitHook returns true if user can edit Git hooks.
  480. func (u *User) CanEditGitHook() bool {
  481. return u.IsAdmin || u.AllowGitHook
  482. }
  483. // CanImportLocal returns true if user can migrate repositories by local path.
  484. func (u *User) CanImportLocal() bool {
  485. return conf.Repository.EnableLocalPathMigration && (u.IsAdmin || u.AllowImportLocal)
  486. }
  487. // DisplayName returns the full name of the user if it's not empty, returns the
  488. // username otherwise.
  489. func (u *User) DisplayName() string {
  490. if len(u.FullName) > 0 {
  491. return u.FullName
  492. }
  493. return u.Name
  494. }
  495. // HomeURLPath returns the URL path to the user or organization home page.
  496. //
  497. // TODO(unknwon): This is also used in templates, which should be fixed by
  498. // having a dedicated type `template.User` and move this to the "userutil"
  499. // package.
  500. func (u *User) HomeURLPath() string {
  501. return conf.Server.Subpath + "/" + u.Name
  502. }
  503. // HTMLURL returns the full URL to the user or organization home page.
  504. //
  505. // TODO(unknwon): This is also used in templates, which should be fixed by
  506. // having a dedicated type `template.User` and move this to the "userutil"
  507. // package.
  508. func (u *User) HTMLURL() string {
  509. return conf.Server.ExternalURL + u.Name
  510. }
  511. // AvatarURLPath returns the URL path to the user or organization avatar. If the
  512. // user enables Gravatar-like service, then an external URL will be returned.
  513. //
  514. // TODO(unknwon): This is also used in templates, which should be fixed by
  515. // having a dedicated type `template.User` and move this to the "userutil"
  516. // package.
  517. func (u *User) AvatarURLPath() string {
  518. defaultURLPath := conf.UserDefaultAvatarURLPath()
  519. if u.ID <= 0 {
  520. return defaultURLPath
  521. }
  522. hasCustomAvatar := osutil.IsFile(userutil.CustomAvatarPath(u.ID))
  523. switch {
  524. case u.UseCustomAvatar:
  525. if !hasCustomAvatar {
  526. return defaultURLPath
  527. }
  528. return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, conf.UsersAvatarPathPrefix, u.ID)
  529. case conf.Picture.DisableGravatar:
  530. if !hasCustomAvatar {
  531. if err := userutil.GenerateRandomAvatar(u.ID, u.Name, u.Email); err != nil {
  532. log.Error("Failed to generate random avatar [user_id: %d]: %v", u.ID, err)
  533. }
  534. }
  535. return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, conf.UsersAvatarPathPrefix, u.ID)
  536. }
  537. return tool.AvatarLink(u.AvatarEmail)
  538. }
  539. // AvatarURL returns the full URL to the user or organization avatar. If the
  540. // user enables Gravatar-like service, then an external URL will be returned.
  541. //
  542. // TODO(unknwon): This is also used in templates, which should be fixed by
  543. // having a dedicated type `template.User` and move this to the "userutil"
  544. // package.
  545. func (u *User) AvatarURL() string {
  546. link := u.AvatarURLPath()
  547. if link[0] == '/' && link[1] != '/' {
  548. return conf.Server.ExternalURL + strings.TrimPrefix(link, conf.Server.Subpath)[1:]
  549. }
  550. return link
  551. }
  552. // IsFollowing returns true if the user is following the given user.
  553. //
  554. // TODO(unknwon): This is also used in templates, which should be fixed by
  555. // having a dedicated type `template.User`.
  556. func (u *User) IsFollowing(followID int64) bool {
  557. return Follows.IsFollowing(context.TODO(), u.ID, followID)
  558. }
  559. // IsUserOrgOwner returns true if the user is in the owner team of the given
  560. // organization.
  561. //
  562. // TODO(unknwon): This is also used in templates, which should be fixed by
  563. // having a dedicated type `template.User`.
  564. func (u *User) IsUserOrgOwner(orgId int64) bool {
  565. return IsOrganizationOwner(orgId, u.ID)
  566. }
  567. // IsPublicMember returns true if the user has public membership of the given
  568. // organization.
  569. //
  570. // TODO(unknwon): This is also used in templates, which should be fixed by
  571. // having a dedicated type `template.User`.
  572. func (u *User) IsPublicMember(orgId int64) bool {
  573. return IsPublicMembership(orgId, u.ID)
  574. }
  575. // GetOrganizationCount returns the count of organization membership that the
  576. // user has.
  577. //
  578. // TODO(unknwon): This is also used in templates, which should be fixed by
  579. // having a dedicated type `template.User`.
  580. func (u *User) GetOrganizationCount() (int64, error) {
  581. return OrgUsers.CountByUser(context.TODO(), u.ID)
  582. }
  583. // ShortName truncates and returns the username at most in given length.
  584. //
  585. // TODO(unknwon): This is also used in templates, which should be fixed by
  586. // having a dedicated type `template.User`.
  587. func (u *User) ShortName(length int) string {
  588. return strutil.Ellipsis(u.Name, length)
  589. }