users.go 24 KB

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