users.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  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. // ListFollowers returns a list of users that are following the given user.
  61. // Results are paginated by given page and page size, and sorted by the time of
  62. // follow in descending order.
  63. ListFollowers(ctx context.Context, userID int64, page, pageSize int) ([]*User, error)
  64. // ListFollowings returns a list of users that are followed by the given user.
  65. // Results are paginated by given page and page size, and sorted by the time of
  66. // follow in descending order.
  67. ListFollowings(ctx context.Context, userID int64, page, pageSize int) ([]*User, error)
  68. // UseCustomAvatar uses the given avatar as the user custom avatar.
  69. UseCustomAvatar(ctx context.Context, userID int64, avatar []byte) error
  70. }
  71. var Users UsersStore
  72. var _ UsersStore = (*users)(nil)
  73. type users struct {
  74. *gorm.DB
  75. }
  76. // NewUsersStore returns a persistent interface for users with given database
  77. // connection.
  78. func NewUsersStore(db *gorm.DB) UsersStore {
  79. return &users{DB: db}
  80. }
  81. type ErrLoginSourceMismatch struct {
  82. args errutil.Args
  83. }
  84. func (err ErrLoginSourceMismatch) Error() string {
  85. return fmt.Sprintf("login source mismatch: %v", err.args)
  86. }
  87. func (db *users) Authenticate(ctx context.Context, login, password string, loginSourceID int64) (*User, error) {
  88. login = strings.ToLower(login)
  89. query := db.WithContext(ctx)
  90. if strings.Contains(login, "@") {
  91. query = query.Where("email = ?", login)
  92. } else {
  93. query = query.Where("lower_name = ?", login)
  94. }
  95. user := new(User)
  96. err := query.First(user).Error
  97. if err != nil && err != gorm.ErrRecordNotFound {
  98. return nil, errors.Wrap(err, "get user")
  99. }
  100. var authSourceID int64 // The login source ID will be used to authenticate the user
  101. createNewUser := false // Whether to create a new user after successful authentication
  102. // User found in the database
  103. if err == nil {
  104. // Note: This check is unnecessary but to reduce user confusion at login page
  105. // and make it more consistent from user's perspective.
  106. if loginSourceID >= 0 && user.LoginSource != loginSourceID {
  107. return nil, ErrLoginSourceMismatch{args: errutil.Args{"expect": loginSourceID, "actual": user.LoginSource}}
  108. }
  109. // Validate password hash fetched from database for local accounts.
  110. if user.IsLocal() {
  111. if userutil.ValidatePassword(user.Password, user.Salt, password) {
  112. return user, nil
  113. }
  114. return nil, auth.ErrBadCredentials{Args: map[string]interface{}{"login": login, "userID": user.ID}}
  115. }
  116. authSourceID = user.LoginSource
  117. } else {
  118. // Non-local login source is always greater than 0.
  119. if loginSourceID <= 0 {
  120. return nil, auth.ErrBadCredentials{Args: map[string]interface{}{"login": login}}
  121. }
  122. authSourceID = loginSourceID
  123. createNewUser = true
  124. }
  125. source, err := LoginSources.GetByID(ctx, authSourceID)
  126. if err != nil {
  127. return nil, errors.Wrap(err, "get login source")
  128. }
  129. if !source.IsActived {
  130. return nil, errors.Errorf("login source %d is not activated", source.ID)
  131. }
  132. extAccount, err := source.Provider.Authenticate(login, password)
  133. if err != nil {
  134. return nil, err
  135. }
  136. if !createNewUser {
  137. return user, nil
  138. }
  139. // Validate username make sure it satisfies requirement.
  140. if binding.AlphaDashDotPattern.MatchString(extAccount.Name) {
  141. return nil, fmt.Errorf("invalid pattern for attribute 'username' [%s]: must be valid alpha or numeric or dash(-_) or dot characters", extAccount.Name)
  142. }
  143. return db.Create(ctx, extAccount.Name, extAccount.Email,
  144. CreateUserOptions{
  145. FullName: extAccount.FullName,
  146. LoginSource: authSourceID,
  147. LoginName: extAccount.Login,
  148. Location: extAccount.Location,
  149. Website: extAccount.Website,
  150. Activated: true,
  151. Admin: extAccount.Admin,
  152. },
  153. )
  154. }
  155. type CreateUserOptions struct {
  156. FullName string
  157. Password string
  158. LoginSource int64
  159. LoginName string
  160. Location string
  161. Website string
  162. Activated bool
  163. Admin bool
  164. }
  165. type ErrUserAlreadyExist struct {
  166. args errutil.Args
  167. }
  168. func IsErrUserAlreadyExist(err error) bool {
  169. _, ok := err.(ErrUserAlreadyExist)
  170. return ok
  171. }
  172. func (err ErrUserAlreadyExist) Error() string {
  173. return fmt.Sprintf("user already exists: %v", err.args)
  174. }
  175. type ErrEmailAlreadyUsed struct {
  176. args errutil.Args
  177. }
  178. func IsErrEmailAlreadyUsed(err error) bool {
  179. _, ok := err.(ErrEmailAlreadyUsed)
  180. return ok
  181. }
  182. func (err ErrEmailAlreadyUsed) Email() string {
  183. email, ok := err.args["email"].(string)
  184. if ok {
  185. return email
  186. }
  187. return "<email not found>"
  188. }
  189. func (err ErrEmailAlreadyUsed) Error() string {
  190. return fmt.Sprintf("email has been used: %v", err.args)
  191. }
  192. func (db *users) Create(ctx context.Context, username, email string, opts CreateUserOptions) (*User, error) {
  193. err := isUsernameAllowed(username)
  194. if err != nil {
  195. return nil, err
  196. }
  197. _, err = db.GetByUsername(ctx, username)
  198. if err == nil {
  199. return nil, ErrUserAlreadyExist{args: errutil.Args{"name": username}}
  200. } else if !IsErrUserNotExist(err) {
  201. return nil, err
  202. }
  203. _, err = db.GetByEmail(ctx, email)
  204. if err == nil {
  205. return nil, ErrEmailAlreadyUsed{args: errutil.Args{"email": email}}
  206. } else if !IsErrUserNotExist(err) {
  207. return nil, err
  208. }
  209. user := &User{
  210. LowerName: strings.ToLower(username),
  211. Name: username,
  212. FullName: opts.FullName,
  213. Email: email,
  214. Password: opts.Password,
  215. LoginSource: opts.LoginSource,
  216. LoginName: opts.LoginName,
  217. Location: opts.Location,
  218. Website: opts.Website,
  219. MaxRepoCreation: -1,
  220. IsActive: opts.Activated,
  221. IsAdmin: opts.Admin,
  222. Avatar: cryptoutil.MD5(email),
  223. AvatarEmail: email,
  224. }
  225. user.Rands, err = GetUserSalt()
  226. if err != nil {
  227. return nil, err
  228. }
  229. user.Salt, err = GetUserSalt()
  230. if err != nil {
  231. return nil, err
  232. }
  233. user.Password = userutil.EncodePassword(user.Password, user.Salt)
  234. return user, db.WithContext(ctx).Create(user).Error
  235. }
  236. func (db *users) DeleteCustomAvatar(ctx context.Context, userID int64) error {
  237. _ = os.Remove(userutil.CustomAvatarPath(userID))
  238. return db.WithContext(ctx).
  239. Model(&User{}).
  240. Where("id = ?", userID).
  241. Updates(map[string]interface{}{
  242. "use_custom_avatar": false,
  243. "updated_unix": db.NowFunc().Unix(),
  244. }).
  245. Error
  246. }
  247. var _ errutil.NotFound = (*ErrUserNotExist)(nil)
  248. type ErrUserNotExist struct {
  249. args errutil.Args
  250. }
  251. func IsErrUserNotExist(err error) bool {
  252. _, ok := err.(ErrUserNotExist)
  253. return ok
  254. }
  255. func (err ErrUserNotExist) Error() string {
  256. return fmt.Sprintf("user does not exist: %v", err.args)
  257. }
  258. func (ErrUserNotExist) NotFound() bool {
  259. return true
  260. }
  261. func (db *users) GetByEmail(ctx context.Context, email string) (*User, error) {
  262. email = strings.ToLower(email)
  263. if email == "" {
  264. return nil, ErrUserNotExist{args: errutil.Args{"email": email}}
  265. }
  266. // First try to find the user by primary email
  267. user := new(User)
  268. err := db.WithContext(ctx).
  269. Where("email = ? AND type = ? AND is_active = ?", email, UserTypeIndividual, true).
  270. First(user).
  271. Error
  272. if err == nil {
  273. return user, nil
  274. } else if err != gorm.ErrRecordNotFound {
  275. return nil, err
  276. }
  277. // Otherwise, check activated email addresses
  278. emailAddress := new(EmailAddress)
  279. err = db.WithContext(ctx).
  280. Where("email = ? AND is_activated = ?", email, true).
  281. First(emailAddress).
  282. Error
  283. if err != nil {
  284. if err == gorm.ErrRecordNotFound {
  285. return nil, ErrUserNotExist{args: errutil.Args{"email": email}}
  286. }
  287. return nil, err
  288. }
  289. return db.GetByID(ctx, emailAddress.UID)
  290. }
  291. func (db *users) GetByID(ctx context.Context, id int64) (*User, error) {
  292. user := new(User)
  293. err := db.WithContext(ctx).Where("id = ?", id).First(user).Error
  294. if err != nil {
  295. if err == gorm.ErrRecordNotFound {
  296. return nil, ErrUserNotExist{args: errutil.Args{"userID": id}}
  297. }
  298. return nil, err
  299. }
  300. return user, nil
  301. }
  302. func (db *users) GetByUsername(ctx context.Context, username string) (*User, error) {
  303. user := new(User)
  304. err := db.WithContext(ctx).Where("lower_name = ?", strings.ToLower(username)).First(user).Error
  305. if err != nil {
  306. if err == gorm.ErrRecordNotFound {
  307. return nil, ErrUserNotExist{args: errutil.Args{"name": username}}
  308. }
  309. return nil, err
  310. }
  311. return user, nil
  312. }
  313. func (db *users) HasForkedRepository(ctx context.Context, userID, repoID int64) bool {
  314. var count int64
  315. db.WithContext(ctx).Model(new(Repository)).Where("owner_id = ? AND fork_id = ?", userID, repoID).Count(&count)
  316. return count > 0
  317. }
  318. func (db *users) ListFollowers(ctx context.Context, userID int64, page, pageSize int) ([]*User, error) {
  319. /*
  320. Equivalent SQL for PostgreSQL:
  321. SELECT * FROM "user"
  322. LEFT JOIN follow ON follow.user_id = "user".id
  323. WHERE follow.follow_id = @userID
  324. ORDER BY follow.id DESC
  325. LIMIT @limit OFFSET @offset
  326. */
  327. users := make([]*User, 0, pageSize)
  328. return users, db.WithContext(ctx).
  329. Joins(dbutil.Quote("LEFT JOIN follow ON follow.user_id = %s.id", "user")).
  330. Where("follow.follow_id = ?", userID).
  331. Limit(pageSize).Offset((page - 1) * pageSize).
  332. Order("follow.id DESC").
  333. Find(&users).
  334. Error
  335. }
  336. func (db *users) ListFollowings(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.user_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.follow_id = %s.id", "user")).
  348. Where("follow.user_id = ?", userID).
  349. Limit(pageSize).Offset((page - 1) * pageSize).
  350. Order("follow.id DESC").
  351. Find(&users).
  352. Error
  353. }
  354. func (db *users) UseCustomAvatar(ctx context.Context, userID int64, avatar []byte) error {
  355. err := userutil.SaveAvatar(userID, avatar)
  356. if err != nil {
  357. return errors.Wrap(err, "save avatar")
  358. }
  359. return db.WithContext(ctx).
  360. Model(&User{}).
  361. Where("id = ?", userID).
  362. Updates(map[string]interface{}{
  363. "use_custom_avatar": true,
  364. "updated_unix": db.NowFunc().Unix(),
  365. }).
  366. Error
  367. }
  368. // UserType indicates the type of the user account.
  369. type UserType int
  370. const (
  371. UserTypeIndividual UserType = iota // NOTE: Historic reason to make it starts at 0.
  372. UserTypeOrganization
  373. )
  374. // User represents the object of an individual or an organization.
  375. type User struct {
  376. ID int64 `gorm:"primaryKey"`
  377. LowerName string `xorm:"UNIQUE NOT NULL" gorm:"unique;not null"`
  378. Name string `xorm:"UNIQUE NOT NULL" gorm:"not null"`
  379. FullName string
  380. // Email is the primary email address (to be used for communication)
  381. Email string `xorm:"NOT NULL" gorm:"not null"`
  382. Password string `xorm:"passwd NOT NULL" gorm:"column:passwd;not null"`
  383. LoginSource int64 `xorm:"NOT NULL DEFAULT 0" gorm:"not null;default:0"`
  384. LoginName string
  385. Type UserType
  386. Location string
  387. Website string
  388. Rands string `xorm:"VARCHAR(10)" gorm:"type:VARCHAR(10)"`
  389. Salt string `xorm:"VARCHAR(10)" gorm:"type:VARCHAR(10)"`
  390. Created time.Time `xorm:"-" gorm:"-" json:"-"`
  391. CreatedUnix int64
  392. Updated time.Time `xorm:"-" gorm:"-" json:"-"`
  393. UpdatedUnix int64
  394. // Remember visibility choice for convenience, true for private
  395. LastRepoVisibility bool
  396. // Maximum repository creation limit, -1 means use global default
  397. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1" gorm:"not null;default:-1"`
  398. // Permissions
  399. IsActive bool // Activate primary email
  400. IsAdmin bool
  401. AllowGitHook bool
  402. AllowImportLocal bool // Allow migrate repository by local path
  403. ProhibitLogin bool
  404. // Avatar
  405. Avatar string `xorm:"VARCHAR(2048) NOT NULL" gorm:"type:VARCHAR(2048);not null"`
  406. AvatarEmail string `xorm:"NOT NULL" gorm:"not null"`
  407. UseCustomAvatar bool
  408. // Counters
  409. NumFollowers int
  410. NumFollowing int `xorm:"NOT NULL DEFAULT 0" gorm:"not null;default:0"`
  411. NumStars int
  412. NumRepos int
  413. // For organization
  414. Description string
  415. NumTeams int
  416. NumMembers int
  417. Teams []*Team `xorm:"-" gorm:"-" json:"-"`
  418. Members []*User `xorm:"-" gorm:"-" json:"-"`
  419. }
  420. // BeforeCreate implements the GORM create hook.
  421. func (u *User) BeforeCreate(tx *gorm.DB) error {
  422. if u.CreatedUnix == 0 {
  423. u.CreatedUnix = tx.NowFunc().Unix()
  424. u.UpdatedUnix = u.CreatedUnix
  425. }
  426. return nil
  427. }
  428. // AfterFind implements the GORM query hook.
  429. func (u *User) AfterFind(_ *gorm.DB) error {
  430. u.Created = time.Unix(u.CreatedUnix, 0).Local()
  431. u.Updated = time.Unix(u.UpdatedUnix, 0).Local()
  432. return nil
  433. }
  434. // IsLocal returns true if the user is created as local account.
  435. func (u *User) IsLocal() bool {
  436. return u.LoginSource <= 0
  437. }
  438. // IsOrganization returns true if the user is an organization.
  439. func (u *User) IsOrganization() bool {
  440. return u.Type == UserTypeOrganization
  441. }
  442. // IsMailable returns true if the user is eligible to receive emails.
  443. func (u *User) IsMailable() bool {
  444. return u.IsActive
  445. }
  446. // APIFormat returns the API format of a user.
  447. func (u *User) APIFormat() *api.User {
  448. return &api.User{
  449. ID: u.ID,
  450. UserName: u.Name,
  451. Login: u.Name,
  452. FullName: u.FullName,
  453. Email: u.Email,
  454. AvatarUrl: u.AvatarURL(),
  455. }
  456. }
  457. // maxNumRepos returns the maximum number of repositories that the user can have
  458. // direct ownership.
  459. func (u *User) maxNumRepos() int {
  460. if u.MaxRepoCreation <= -1 {
  461. return conf.Repository.MaxCreationLimit
  462. }
  463. return u.MaxRepoCreation
  464. }
  465. // canCreateRepo returns true if the user can create a repository.
  466. func (u *User) canCreateRepo() bool {
  467. return u.maxNumRepos() <= -1 || u.NumRepos < u.maxNumRepos()
  468. }
  469. // CanCreateOrganization returns true if user can create organizations.
  470. func (u *User) CanCreateOrganization() bool {
  471. return !conf.Admin.DisableRegularOrgCreation || u.IsAdmin
  472. }
  473. // CanEditGitHook returns true if user can edit Git hooks.
  474. func (u *User) CanEditGitHook() bool {
  475. return u.IsAdmin || u.AllowGitHook
  476. }
  477. // CanImportLocal returns true if user can migrate repositories by local path.
  478. func (u *User) CanImportLocal() bool {
  479. return conf.Repository.EnableLocalPathMigration && (u.IsAdmin || u.AllowImportLocal)
  480. }
  481. // DisplayName returns the full name of the user if it's not empty, returns the
  482. // username otherwise.
  483. func (u *User) DisplayName() string {
  484. if len(u.FullName) > 0 {
  485. return u.FullName
  486. }
  487. return u.Name
  488. }
  489. // HomeURLPath returns the URL path to the user or organization home page.
  490. //
  491. // TODO(unknwon): This is also used in templates, which should be fixed by
  492. // having a dedicated type `template.User` and move this to the "userutil"
  493. // package.
  494. func (u *User) HomeURLPath() string {
  495. return conf.Server.Subpath + "/" + u.Name
  496. }
  497. // HTMLURL returns the full URL to the user or organization home page.
  498. //
  499. // TODO(unknwon): This is also used in templates, which should be fixed by
  500. // having a dedicated type `template.User` and move this to the "userutil"
  501. // package.
  502. func (u *User) HTMLURL() string {
  503. return conf.Server.ExternalURL + u.Name
  504. }
  505. // AvatarURLPath returns the URL path to the user or organization avatar. If the
  506. // user enables Gravatar-like service, then an external URL will be returned.
  507. //
  508. // TODO(unknwon): This is also used in templates, which should be fixed by
  509. // having a dedicated type `template.User` and move this to the "userutil"
  510. // package.
  511. func (u *User) AvatarURLPath() string {
  512. defaultURLPath := conf.UserDefaultAvatarURLPath()
  513. if u.ID <= 0 {
  514. return defaultURLPath
  515. }
  516. hasCustomAvatar := osutil.IsFile(userutil.CustomAvatarPath(u.ID))
  517. switch {
  518. case u.UseCustomAvatar:
  519. if !hasCustomAvatar {
  520. return defaultURLPath
  521. }
  522. return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, conf.UsersAvatarPathPrefix, u.ID)
  523. case conf.Picture.DisableGravatar:
  524. if !hasCustomAvatar {
  525. if err := userutil.GenerateRandomAvatar(u.ID, u.Name, u.Email); err != nil {
  526. log.Error("Failed to generate random avatar [user_id: %d]: %v", u.ID, err)
  527. }
  528. }
  529. return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, conf.UsersAvatarPathPrefix, u.ID)
  530. }
  531. return tool.AvatarLink(u.AvatarEmail)
  532. }
  533. // AvatarURL returns the full URL to the user or organization avatar. If the
  534. // user enables Gravatar-like service, then an external URL will be returned.
  535. //
  536. // TODO(unknwon): This is also used in templates, which should be fixed by
  537. // having a dedicated type `template.User` and move this to the "userutil"
  538. // package.
  539. func (u *User) AvatarURL() string {
  540. link := u.AvatarURLPath()
  541. if link[0] == '/' && link[1] != '/' {
  542. return conf.Server.ExternalURL + strings.TrimPrefix(link, conf.Server.Subpath)[1:]
  543. }
  544. return link
  545. }
  546. // IsFollowing returns true if the user is following the given user.
  547. //
  548. // TODO(unknwon): This is also used in templates, which should be fixed by
  549. // having a dedicated type `template.User`.
  550. func (u *User) IsFollowing(followID int64) bool {
  551. return Follows.IsFollowing(context.TODO(), u.ID, followID)
  552. }
  553. // IsUserOrgOwner returns true if the user is in the owner team of the given
  554. // organization.
  555. //
  556. // TODO(unknwon): This is also used in templates, which should be fixed by
  557. // having a dedicated type `template.User`.
  558. func (u *User) IsUserOrgOwner(orgId int64) bool {
  559. return IsOrganizationOwner(orgId, u.ID)
  560. }
  561. // IsPublicMember returns true if the user has public membership of the given
  562. // organization.
  563. //
  564. // TODO(unknwon): This is also used in templates, which should be fixed by
  565. // having a dedicated type `template.User`.
  566. func (u *User) IsPublicMember(orgId int64) bool {
  567. return IsPublicMembership(orgId, u.ID)
  568. }
  569. // GetOrganizationCount returns the count of organization membership that the
  570. // user has.
  571. //
  572. // TODO(unknwon): This is also used in templates, which should be fixed by
  573. // having a dedicated type `template.User`.
  574. func (u *User) GetOrganizationCount() (int64, error) {
  575. return OrgUsers.CountByUser(context.TODO(), u.ID)
  576. }
  577. // ShortName truncates and returns the username at most in given length.
  578. //
  579. // TODO(unknwon): This is also used in templates, which should be fixed by
  580. // having a dedicated type `template.User`.
  581. func (u *User) ShortName(length int) string {
  582. return strutil.Ellipsis(u.Name, length)
  583. }