users.go 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430
  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. "database/sql"
  8. "fmt"
  9. "os"
  10. "strings"
  11. "time"
  12. "unicode/utf8"
  13. "github.com/go-macaron/binding"
  14. api "github.com/gogs/go-gogs-client"
  15. "github.com/pkg/errors"
  16. "gorm.io/gorm"
  17. log "unknwon.dev/clog/v2"
  18. "gogs.io/gogs/internal/auth"
  19. "gogs.io/gogs/internal/conf"
  20. "gogs.io/gogs/internal/cryptoutil"
  21. "gogs.io/gogs/internal/dbutil"
  22. "gogs.io/gogs/internal/errutil"
  23. "gogs.io/gogs/internal/markup"
  24. "gogs.io/gogs/internal/osutil"
  25. "gogs.io/gogs/internal/repoutil"
  26. "gogs.io/gogs/internal/strutil"
  27. "gogs.io/gogs/internal/tool"
  28. "gogs.io/gogs/internal/userutil"
  29. )
  30. // UsersStore is the persistent interface for users.
  31. type UsersStore interface {
  32. // Authenticate validates username and password via given login source ID. It
  33. // returns ErrUserNotExist when the user was not found.
  34. //
  35. // When the "loginSourceID" is negative, it aborts the process and returns
  36. // ErrUserNotExist if the user was not found in the database.
  37. //
  38. // When the "loginSourceID" is non-negative, it returns ErrLoginSourceMismatch
  39. // if the user has different login source ID than the "loginSourceID".
  40. //
  41. // When the "loginSourceID" is positive, it tries to authenticate via given
  42. // login source and creates a new user when not yet exists in the database.
  43. Authenticate(ctx context.Context, username, password string, loginSourceID int64) (*User, error)
  44. // Create creates a new user and persists to database. It returns
  45. // ErrNameNotAllowed if the given name or pattern of the name is not allowed as
  46. // a username, or ErrUserAlreadyExist when a user with same name already exists,
  47. // or ErrEmailAlreadyUsed if the email has been used by another user.
  48. Create(ctx context.Context, username, email string, opts CreateUserOptions) (*User, 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. // GetByKeyID returns the owner of given public key ID. It returns
  59. // ErrUserNotExist when not found.
  60. GetByKeyID(ctx context.Context, keyID int64) (*User, error)
  61. // GetMailableEmailsByUsernames returns a list of verified primary email
  62. // addresses (where email notifications are sent to) of users with given list of
  63. // usernames. Non-existing usernames are ignored.
  64. GetMailableEmailsByUsernames(ctx context.Context, usernames []string) ([]string, error)
  65. // SearchByName returns a list of users whose username or full name matches the
  66. // given keyword case-insensitively. Results are paginated by given page and
  67. // page size, and sorted by the given order (e.g. "id DESC"). A total count of
  68. // all results is also returned. If the order is not given, it's up to the
  69. // database to decide.
  70. SearchByName(ctx context.Context, keyword string, page, pageSize int, orderBy string) ([]*User, int64, error)
  71. // IsUsernameUsed returns true if the given username has been used other than
  72. // the excluded user (a non-positive ID effectively meaning check against all
  73. // users).
  74. IsUsernameUsed(ctx context.Context, username string, excludeUserId int64) bool
  75. // ChangeUsername changes the username of the given user and updates all
  76. // references to the old username. It returns ErrNameNotAllowed if the given
  77. // name or pattern of the name is not allowed as a username, or
  78. // ErrUserAlreadyExist when another user with same name already exists.
  79. ChangeUsername(ctx context.Context, userID int64, newUsername string) error
  80. // Update updates fields for the given user.
  81. Update(ctx context.Context, userID int64, opts UpdateUserOptions) error
  82. // UseCustomAvatar uses the given avatar as the user custom avatar.
  83. UseCustomAvatar(ctx context.Context, userID int64, avatar []byte) error
  84. // DeleteCustomAvatar deletes the current user custom avatar and falls back to
  85. // use look up avatar by email.
  86. DeleteCustomAvatar(ctx context.Context, userID int64) error
  87. // DeleteByID deletes the given user and all their resources. It returns
  88. // ErrUserOwnRepos when the user still has repository ownership, or returns
  89. // ErrUserHasOrgs when the user still has organization membership. It is more
  90. // performant to skip rewriting the "authorized_keys" file for individual
  91. // deletion in a batch operation.
  92. DeleteByID(ctx context.Context, userID int64, skipRewriteAuthorizedKeys bool) error
  93. // DeleteInactivated deletes all inactivated users.
  94. DeleteInactivated() error
  95. // Follow marks the user to follow the other user.
  96. Follow(ctx context.Context, userID, followID int64) error
  97. // Unfollow removes the mark the user to follow the other user.
  98. Unfollow(ctx context.Context, userID, followID int64) error
  99. // IsFollowing returns true if the user is following the other user.
  100. IsFollowing(ctx context.Context, userID, followID int64) bool
  101. // ListFollowers returns a list of users that are following the given user.
  102. // Results are paginated by given page and page size, and sorted by the time of
  103. // follow in descending order.
  104. ListFollowers(ctx context.Context, userID int64, page, pageSize int) ([]*User, error)
  105. // ListFollowings returns a list of users that are followed by the given user.
  106. // Results are paginated by given page and page size, and sorted by the time of
  107. // follow in descending order.
  108. ListFollowings(ctx context.Context, userID int64, page, pageSize int) ([]*User, error)
  109. // List returns a list of users. Results are paginated by given page and page
  110. // size, and sorted by primary key (id) in ascending order.
  111. List(ctx context.Context, page, pageSize int) ([]*User, error)
  112. // Count returns the total number of users.
  113. Count(ctx context.Context) int64
  114. }
  115. var Users UsersStore
  116. var _ UsersStore = (*users)(nil)
  117. type users struct {
  118. *gorm.DB
  119. }
  120. // NewUsersStore returns a persistent interface for users with given database
  121. // connection.
  122. func NewUsersStore(db *gorm.DB) UsersStore {
  123. return &users{DB: db}
  124. }
  125. type ErrLoginSourceMismatch struct {
  126. args errutil.Args
  127. }
  128. // IsErrLoginSourceMismatch returns true if the underlying error has the type
  129. // ErrLoginSourceMismatch.
  130. func IsErrLoginSourceMismatch(err error) bool {
  131. _, ok := errors.Cause(err).(ErrLoginSourceMismatch)
  132. return ok
  133. }
  134. func (err ErrLoginSourceMismatch) Error() string {
  135. return fmt.Sprintf("login source mismatch: %v", err.args)
  136. }
  137. func (db *users) Authenticate(ctx context.Context, login, password string, loginSourceID int64) (*User, error) {
  138. login = strings.ToLower(login)
  139. query := db.WithContext(ctx)
  140. if strings.Contains(login, "@") {
  141. query = query.Where("email = ?", login)
  142. } else {
  143. query = query.Where("lower_name = ?", login)
  144. }
  145. user := new(User)
  146. err := query.First(user).Error
  147. if err != nil && err != gorm.ErrRecordNotFound {
  148. return nil, errors.Wrap(err, "get user")
  149. }
  150. var authSourceID int64 // The login source ID will be used to authenticate the user
  151. createNewUser := false // Whether to create a new user after successful authentication
  152. // User found in the database
  153. if err == nil {
  154. // Note: This check is unnecessary but to reduce user confusion at login page
  155. // and make it more consistent from user's perspective.
  156. if loginSourceID >= 0 && user.LoginSource != loginSourceID {
  157. return nil, ErrLoginSourceMismatch{args: errutil.Args{"expect": loginSourceID, "actual": user.LoginSource}}
  158. }
  159. // Validate password hash fetched from database for local accounts.
  160. if user.IsLocal() {
  161. if userutil.ValidatePassword(user.Password, user.Salt, password) {
  162. return user, nil
  163. }
  164. return nil, auth.ErrBadCredentials{Args: map[string]any{"login": login, "userID": user.ID}}
  165. }
  166. authSourceID = user.LoginSource
  167. } else {
  168. // Non-local login source is always greater than 0.
  169. if loginSourceID <= 0 {
  170. return nil, auth.ErrBadCredentials{Args: map[string]any{"login": login}}
  171. }
  172. authSourceID = loginSourceID
  173. createNewUser = true
  174. }
  175. source, err := LoginSources.GetByID(ctx, authSourceID)
  176. if err != nil {
  177. return nil, errors.Wrap(err, "get login source")
  178. }
  179. if !source.IsActived {
  180. return nil, errors.Errorf("login source %d is not activated", source.ID)
  181. }
  182. extAccount, err := source.Provider.Authenticate(login, password)
  183. if err != nil {
  184. return nil, err
  185. }
  186. if !createNewUser {
  187. return user, nil
  188. }
  189. // Validate username make sure it satisfies requirement.
  190. if binding.AlphaDashDotPattern.MatchString(extAccount.Name) {
  191. return nil, fmt.Errorf("invalid pattern for attribute 'username' [%s]: must be valid alpha or numeric or dash(-_) or dot characters", extAccount.Name)
  192. }
  193. return db.Create(ctx, extAccount.Name, extAccount.Email,
  194. CreateUserOptions{
  195. FullName: extAccount.FullName,
  196. LoginSource: authSourceID,
  197. LoginName: extAccount.Login,
  198. Location: extAccount.Location,
  199. Website: extAccount.Website,
  200. Activated: true,
  201. Admin: extAccount.Admin,
  202. },
  203. )
  204. }
  205. func (db *users) ChangeUsername(ctx context.Context, userID int64, newUsername string) error {
  206. err := isUsernameAllowed(newUsername)
  207. if err != nil {
  208. return err
  209. }
  210. if db.IsUsernameUsed(ctx, newUsername, userID) {
  211. return ErrUserAlreadyExist{
  212. args: errutil.Args{
  213. "name": newUsername,
  214. },
  215. }
  216. }
  217. user, err := db.GetByID(ctx, userID)
  218. if err != nil {
  219. return errors.Wrap(err, "get user")
  220. }
  221. return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  222. err := tx.Model(&User{}).
  223. Where("id = ?", user.ID).
  224. Updates(map[string]any{
  225. "lower_name": strings.ToLower(newUsername),
  226. "name": newUsername,
  227. "updated_unix": tx.NowFunc().Unix(),
  228. }).Error
  229. if err != nil {
  230. return errors.Wrap(err, "update user name")
  231. }
  232. // Stop here if it's just a case-change of the username
  233. if strings.EqualFold(user.Name, newUsername) {
  234. return nil
  235. }
  236. // Update all references to the user name in pull requests
  237. err = tx.Model(&PullRequest{}).
  238. Where("head_user_name = ?", user.LowerName).
  239. Update("head_user_name", strings.ToLower(newUsername)).
  240. Error
  241. if err != nil {
  242. return errors.Wrap(err, `update "pull_request.head_user_name"`)
  243. }
  244. // Delete local copies of repositories and their wikis that are owned by the user
  245. rows, err := tx.Model(&Repository{}).Where("owner_id = ?", user.ID).Rows()
  246. if err != nil {
  247. return errors.Wrap(err, "iterate repositories")
  248. }
  249. defer func() { _ = rows.Close() }()
  250. for rows.Next() {
  251. var repo struct {
  252. ID int64
  253. }
  254. err = tx.ScanRows(rows, &repo)
  255. if err != nil {
  256. return errors.Wrap(err, "scan rows")
  257. }
  258. deleteRepoLocalCopy(repo.ID)
  259. RemoveAllWithNotice(fmt.Sprintf("Delete repository %d wiki local copy", repo.ID), repoutil.RepositoryLocalWikiPath(repo.ID))
  260. }
  261. if err = rows.Err(); err != nil {
  262. return errors.Wrap(err, "check rows.Err")
  263. }
  264. // Rename user directory if exists
  265. userPath := repoutil.UserPath(user.Name)
  266. if osutil.IsExist(userPath) {
  267. newUserPath := repoutil.UserPath(newUsername)
  268. err = os.Rename(userPath, newUserPath)
  269. if err != nil {
  270. return errors.Wrap(err, "rename user directory")
  271. }
  272. }
  273. return nil
  274. })
  275. }
  276. func (db *users) Count(ctx context.Context) int64 {
  277. var count int64
  278. db.WithContext(ctx).Model(&User{}).Where("type = ?", UserTypeIndividual).Count(&count)
  279. return count
  280. }
  281. type CreateUserOptions struct {
  282. FullName string
  283. Password string
  284. LoginSource int64
  285. LoginName string
  286. Location string
  287. Website string
  288. Activated bool
  289. Admin bool
  290. }
  291. type ErrUserAlreadyExist struct {
  292. args errutil.Args
  293. }
  294. // IsErrUserAlreadyExist returns true if the underlying error has the type
  295. // ErrUserAlreadyExist.
  296. func IsErrUserAlreadyExist(err error) bool {
  297. _, ok := errors.Cause(err).(ErrUserAlreadyExist)
  298. return ok
  299. }
  300. func (err ErrUserAlreadyExist) Error() string {
  301. return fmt.Sprintf("user already exists: %v", err.args)
  302. }
  303. type ErrEmailAlreadyUsed struct {
  304. args errutil.Args
  305. }
  306. // IsErrEmailAlreadyUsed returns true if the underlying error has the type
  307. // ErrEmailAlreadyUsed.
  308. func IsErrEmailAlreadyUsed(err error) bool {
  309. _, ok := errors.Cause(err).(ErrEmailAlreadyUsed)
  310. return ok
  311. }
  312. func (err ErrEmailAlreadyUsed) Email() string {
  313. email, ok := err.args["email"].(string)
  314. if ok {
  315. return email
  316. }
  317. return "<email not found>"
  318. }
  319. func (err ErrEmailAlreadyUsed) Error() string {
  320. return fmt.Sprintf("email has been used: %v", err.args)
  321. }
  322. func (db *users) Create(ctx context.Context, username, email string, opts CreateUserOptions) (*User, error) {
  323. err := isUsernameAllowed(username)
  324. if err != nil {
  325. return nil, err
  326. }
  327. if db.IsUsernameUsed(ctx, username, 0) {
  328. return nil, ErrUserAlreadyExist{
  329. args: errutil.Args{
  330. "name": username,
  331. },
  332. }
  333. }
  334. email = strings.ToLower(email)
  335. _, err = db.GetByEmail(ctx, email)
  336. if err == nil {
  337. return nil, ErrEmailAlreadyUsed{
  338. args: errutil.Args{
  339. "email": email,
  340. },
  341. }
  342. } else if !IsErrUserNotExist(err) {
  343. return nil, err
  344. }
  345. user := &User{
  346. LowerName: strings.ToLower(username),
  347. Name: username,
  348. FullName: opts.FullName,
  349. Email: email,
  350. Password: opts.Password,
  351. LoginSource: opts.LoginSource,
  352. LoginName: opts.LoginName,
  353. Location: opts.Location,
  354. Website: opts.Website,
  355. MaxRepoCreation: -1,
  356. IsActive: opts.Activated,
  357. IsAdmin: opts.Admin,
  358. Avatar: cryptoutil.MD5(email), // Gravatar URL uses the MD5 hash of the email, see https://en.gravatar.com/site/implement/hash/
  359. AvatarEmail: email,
  360. }
  361. user.Rands, err = userutil.RandomSalt()
  362. if err != nil {
  363. return nil, err
  364. }
  365. user.Salt, err = userutil.RandomSalt()
  366. if err != nil {
  367. return nil, err
  368. }
  369. user.Password = userutil.EncodePassword(user.Password, user.Salt)
  370. return user, db.WithContext(ctx).Create(user).Error
  371. }
  372. func (db *users) DeleteCustomAvatar(ctx context.Context, userID int64) error {
  373. _ = os.Remove(userutil.CustomAvatarPath(userID))
  374. return db.WithContext(ctx).
  375. Model(&User{}).
  376. Where("id = ?", userID).
  377. Updates(map[string]any{
  378. "use_custom_avatar": false,
  379. "updated_unix": db.NowFunc().Unix(),
  380. }).
  381. Error
  382. }
  383. type ErrUserOwnRepos struct {
  384. args errutil.Args
  385. }
  386. // IsErrUserOwnRepos returns true if the underlying error has the type
  387. // ErrUserOwnRepos.
  388. func IsErrUserOwnRepos(err error) bool {
  389. _, ok := errors.Cause(err).(ErrUserOwnRepos)
  390. return ok
  391. }
  392. func (err ErrUserOwnRepos) Error() string {
  393. return fmt.Sprintf("user still has repository ownership: %v", err.args)
  394. }
  395. type ErrUserHasOrgs struct {
  396. args errutil.Args
  397. }
  398. // IsErrUserHasOrgs returns true if the underlying error has the type
  399. // ErrUserHasOrgs.
  400. func IsErrUserHasOrgs(err error) bool {
  401. _, ok := errors.Cause(err).(ErrUserHasOrgs)
  402. return ok
  403. }
  404. func (err ErrUserHasOrgs) Error() string {
  405. return fmt.Sprintf("user still has organization membership: %v", err.args)
  406. }
  407. func (db *users) DeleteByID(ctx context.Context, userID int64, skipRewriteAuthorizedKeys bool) error {
  408. user, err := db.GetByID(ctx, userID)
  409. if err != nil {
  410. if IsErrUserNotExist(err) {
  411. return nil
  412. }
  413. return errors.Wrap(err, "get user")
  414. }
  415. // Double check the user is not a direct owner of any repository and not a
  416. // member of any organization.
  417. var count int64
  418. err = db.WithContext(ctx).Model(&Repository{}).Where("owner_id = ?", userID).Count(&count).Error
  419. if err != nil {
  420. return errors.Wrap(err, "count repositories")
  421. } else if count > 0 {
  422. return ErrUserOwnRepos{args: errutil.Args{"userID": userID}}
  423. }
  424. err = db.WithContext(ctx).Model(&OrgUser{}).Where("uid = ?", userID).Count(&count).Error
  425. if err != nil {
  426. return errors.Wrap(err, "count organization membership")
  427. } else if count > 0 {
  428. return ErrUserHasOrgs{args: errutil.Args{"userID": userID}}
  429. }
  430. needsRewriteAuthorizedKeys := false
  431. err = db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  432. /*
  433. Equivalent SQL for PostgreSQL:
  434. UPDATE repository
  435. SET num_watches = num_watches - 1
  436. WHERE id IN (
  437. SELECT repo_id FROM watch WHERE user_id = @userID
  438. )
  439. */
  440. err = tx.Table("repository").
  441. Where("id IN (?)", tx.
  442. Select("repo_id").
  443. Table("watch").
  444. Where("user_id = ?", userID),
  445. ).
  446. UpdateColumn("num_watches", gorm.Expr("num_watches - 1")).
  447. Error
  448. if err != nil {
  449. return errors.Wrap(err, `decrease "repository.num_watches"`)
  450. }
  451. /*
  452. Equivalent SQL for PostgreSQL:
  453. UPDATE repository
  454. SET num_stars = num_stars - 1
  455. WHERE id IN (
  456. SELECT repo_id FROM star WHERE uid = @userID
  457. )
  458. */
  459. err = tx.Table("repository").
  460. Where("id IN (?)", tx.
  461. Select("repo_id").
  462. Table("star").
  463. Where("uid = ?", userID),
  464. ).
  465. UpdateColumn("num_stars", gorm.Expr("num_stars - 1")).
  466. Error
  467. if err != nil {
  468. return errors.Wrap(err, `decrease "repository.num_stars"`)
  469. }
  470. /*
  471. Equivalent SQL for PostgreSQL:
  472. UPDATE user
  473. SET num_followers = num_followers - 1
  474. WHERE id IN (
  475. SELECT follow_id FROM follow WHERE user_id = @userID
  476. )
  477. */
  478. err = tx.Table("user").
  479. Where("id IN (?)", tx.
  480. Select("follow_id").
  481. Table("follow").
  482. Where("user_id = ?", userID),
  483. ).
  484. UpdateColumn("num_followers", gorm.Expr("num_followers - 1")).
  485. Error
  486. if err != nil {
  487. return errors.Wrap(err, `decrease "user.num_followers"`)
  488. }
  489. /*
  490. Equivalent SQL for PostgreSQL:
  491. UPDATE user
  492. SET num_following = num_following - 1
  493. WHERE id IN (
  494. SELECT user_id FROM follow WHERE follow_id = @userID
  495. )
  496. */
  497. err = tx.Table("user").
  498. Where("id IN (?)", tx.
  499. Select("user_id").
  500. Table("follow").
  501. Where("follow_id = ?", userID),
  502. ).
  503. UpdateColumn("num_following", gorm.Expr("num_following - 1")).
  504. Error
  505. if err != nil {
  506. return errors.Wrap(err, `decrease "user.num_following"`)
  507. }
  508. if !skipRewriteAuthorizedKeys {
  509. // We need to rewrite "authorized_keys" file if the user owns any public keys.
  510. needsRewriteAuthorizedKeys = tx.Where("owner_id = ?", userID).First(&PublicKey{}).Error != gorm.ErrRecordNotFound
  511. }
  512. err = tx.Model(&Issue{}).Where("assignee_id = ?", userID).Update("assignee_id", 0).Error
  513. if err != nil {
  514. return errors.Wrap(err, "clear assignees")
  515. }
  516. for _, t := range []struct {
  517. table any
  518. where string
  519. }{
  520. {&Watch{}, "user_id = @userID"},
  521. {&Star{}, "uid = @userID"},
  522. {&Follow{}, "user_id = @userID OR follow_id = @userID"},
  523. {&PublicKey{}, "owner_id = @userID"},
  524. {&AccessToken{}, "uid = @userID"},
  525. {&Collaboration{}, "user_id = @userID"},
  526. {&Access{}, "user_id = @userID"},
  527. {&Action{}, "user_id = @userID"},
  528. {&IssueUser{}, "uid = @userID"},
  529. {&EmailAddress{}, "uid = @userID"},
  530. {&User{}, "id = @userID"},
  531. } {
  532. err = tx.Where(t.where, sql.Named("userID", userID)).Delete(t.table).Error
  533. if err != nil {
  534. return errors.Wrapf(err, "clean up table %T", t.table)
  535. }
  536. }
  537. return nil
  538. })
  539. if err != nil {
  540. return err
  541. }
  542. _ = os.RemoveAll(repoutil.UserPath(user.Name))
  543. _ = os.Remove(userutil.CustomAvatarPath(userID))
  544. if needsRewriteAuthorizedKeys {
  545. err = NewPublicKeysStore(db.DB).RewriteAuthorizedKeys()
  546. if err != nil {
  547. return errors.Wrap(err, `rewrite "authorized_keys" file`)
  548. }
  549. }
  550. return nil
  551. }
  552. // NOTE: We do not take context.Context here because this operation in practice
  553. // could much longer than the general request timeout (e.g. one minute).
  554. func (db *users) DeleteInactivated() error {
  555. var userIDs []int64
  556. err := db.Model(&User{}).Where("is_active = ?", false).Pluck("id", &userIDs).Error
  557. if err != nil {
  558. return errors.Wrap(err, "get inactivated user IDs")
  559. }
  560. for _, userID := range userIDs {
  561. err = db.DeleteByID(context.Background(), userID, true)
  562. if err != nil {
  563. // Skip users that may had set to inactivated by admins.
  564. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  565. continue
  566. }
  567. return errors.Wrapf(err, "delete user with ID %d", userID)
  568. }
  569. }
  570. err = NewPublicKeysStore(db.DB).RewriteAuthorizedKeys()
  571. if err != nil {
  572. return errors.Wrap(err, `rewrite "authorized_keys" file`)
  573. }
  574. return nil
  575. }
  576. func (*users) recountFollows(tx *gorm.DB, userID, followID int64) error {
  577. /*
  578. Equivalent SQL for PostgreSQL:
  579. UPDATE "user"
  580. SET num_followers = (
  581. SELECT COUNT(*) FROM follow WHERE follow_id = @followID
  582. )
  583. WHERE id = @followID
  584. */
  585. err := tx.Model(&User{}).
  586. Where("id = ?", followID).
  587. Update(
  588. "num_followers",
  589. tx.Model(&Follow{}).Select("COUNT(*)").Where("follow_id = ?", followID),
  590. ).
  591. Error
  592. if err != nil {
  593. return errors.Wrap(err, `update "user.num_followers"`)
  594. }
  595. /*
  596. Equivalent SQL for PostgreSQL:
  597. UPDATE "user"
  598. SET num_following = (
  599. SELECT COUNT(*) FROM follow WHERE user_id = @userID
  600. )
  601. WHERE id = @userID
  602. */
  603. err = tx.Model(&User{}).
  604. Where("id = ?", userID).
  605. Update(
  606. "num_following",
  607. tx.Model(&Follow{}).Select("COUNT(*)").Where("user_id = ?", userID),
  608. ).
  609. Error
  610. if err != nil {
  611. return errors.Wrap(err, `update "user.num_following"`)
  612. }
  613. return nil
  614. }
  615. func (db *users) Follow(ctx context.Context, userID, followID int64) error {
  616. if userID == followID {
  617. return nil
  618. }
  619. return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  620. f := &Follow{
  621. UserID: userID,
  622. FollowID: followID,
  623. }
  624. result := tx.FirstOrCreate(f, f)
  625. if result.Error != nil {
  626. return errors.Wrap(result.Error, "upsert")
  627. } else if result.RowsAffected <= 0 {
  628. return nil // Relation already exists
  629. }
  630. return db.recountFollows(tx, userID, followID)
  631. })
  632. }
  633. func (db *users) Unfollow(ctx context.Context, userID, followID int64) error {
  634. if userID == followID {
  635. return nil
  636. }
  637. return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  638. err := tx.Where("user_id = ? AND follow_id = ?", userID, followID).Delete(&Follow{}).Error
  639. if err != nil {
  640. return errors.Wrap(err, "delete")
  641. }
  642. return db.recountFollows(tx, userID, followID)
  643. })
  644. }
  645. func (db *users) IsFollowing(ctx context.Context, userID, followID int64) bool {
  646. return db.WithContext(ctx).Where("user_id = ? AND follow_id = ?", userID, followID).First(&Follow{}).Error == nil
  647. }
  648. var _ errutil.NotFound = (*ErrUserNotExist)(nil)
  649. type ErrUserNotExist struct {
  650. args errutil.Args
  651. }
  652. // IsErrUserNotExist returns true if the underlying error has the type
  653. // ErrUserNotExist.
  654. func IsErrUserNotExist(err error) bool {
  655. _, ok := errors.Cause(err).(ErrUserNotExist)
  656. return ok
  657. }
  658. func (err ErrUserNotExist) Error() string {
  659. return fmt.Sprintf("user does not exist: %v", err.args)
  660. }
  661. func (ErrUserNotExist) NotFound() bool {
  662. return true
  663. }
  664. func (db *users) GetByEmail(ctx context.Context, email string) (*User, error) {
  665. if email == "" {
  666. return nil, ErrUserNotExist{args: errutil.Args{"email": email}}
  667. }
  668. email = strings.ToLower(email)
  669. /*
  670. Equivalent SQL for PostgreSQL:
  671. SELECT * FROM "user"
  672. LEFT JOIN email_address ON email_address.uid = "user".id
  673. WHERE
  674. "user".type = @userType
  675. AND (
  676. "user".email = @email AND "user".is_active = TRUE
  677. OR email_address.email = @email AND email_address.is_activated = TRUE
  678. )
  679. */
  680. user := new(User)
  681. err := db.WithContext(ctx).
  682. Joins(dbutil.Quote("LEFT JOIN email_address ON email_address.uid = %s.id", "user"), true).
  683. Where(dbutil.Quote("%s.type = ?", "user"), UserTypeIndividual).
  684. Where(db.
  685. Where(dbutil.Quote("%[1]s.email = ? AND %[1]s.is_active = ?", "user"), email, true).
  686. Or("email_address.email = ? AND email_address.is_activated = ?", email, true),
  687. ).
  688. First(&user).
  689. Error
  690. if err != nil {
  691. if err == gorm.ErrRecordNotFound {
  692. return nil, ErrUserNotExist{args: errutil.Args{"email": email}}
  693. }
  694. return nil, err
  695. }
  696. return user, nil
  697. }
  698. func (db *users) GetByID(ctx context.Context, id int64) (*User, error) {
  699. user := new(User)
  700. err := db.WithContext(ctx).Where("id = ?", id).First(user).Error
  701. if err != nil {
  702. if err == gorm.ErrRecordNotFound {
  703. return nil, ErrUserNotExist{args: errutil.Args{"userID": id}}
  704. }
  705. return nil, err
  706. }
  707. return user, nil
  708. }
  709. func (db *users) GetByUsername(ctx context.Context, username string) (*User, error) {
  710. user := new(User)
  711. err := db.WithContext(ctx).Where("lower_name = ?", strings.ToLower(username)).First(user).Error
  712. if err != nil {
  713. if err == gorm.ErrRecordNotFound {
  714. return nil, ErrUserNotExist{args: errutil.Args{"name": username}}
  715. }
  716. return nil, err
  717. }
  718. return user, nil
  719. }
  720. func (db *users) GetByKeyID(ctx context.Context, keyID int64) (*User, error) {
  721. user := new(User)
  722. err := db.WithContext(ctx).
  723. Joins(dbutil.Quote("JOIN public_key ON public_key.owner_id = %s.id", "user")).
  724. Where("public_key.id = ?", keyID).
  725. First(user).
  726. Error
  727. if err != nil {
  728. if err == gorm.ErrRecordNotFound {
  729. return nil, ErrUserNotExist{args: errutil.Args{"keyID": keyID}}
  730. }
  731. return nil, err
  732. }
  733. return user, nil
  734. }
  735. func (db *users) GetMailableEmailsByUsernames(ctx context.Context, usernames []string) ([]string, error) {
  736. emails := make([]string, 0, len(usernames))
  737. return emails, db.WithContext(ctx).
  738. Model(&User{}).
  739. Select("email").
  740. Where("lower_name IN (?) AND is_active = ?", usernames, true).
  741. Find(&emails).Error
  742. }
  743. func (db *users) IsUsernameUsed(ctx context.Context, username string, excludeUserId int64) bool {
  744. if username == "" {
  745. return false
  746. }
  747. return db.WithContext(ctx).
  748. Select("id").
  749. Where("lower_name = ? AND id != ?", strings.ToLower(username), excludeUserId).
  750. First(&User{}).
  751. Error != gorm.ErrRecordNotFound
  752. }
  753. func (db *users) List(ctx context.Context, page, pageSize int) ([]*User, error) {
  754. users := make([]*User, 0, pageSize)
  755. return users, db.WithContext(ctx).
  756. Where("type = ?", UserTypeIndividual).
  757. Limit(pageSize).Offset((page - 1) * pageSize).
  758. Order("id ASC").
  759. Find(&users).
  760. Error
  761. }
  762. func (db *users) ListFollowers(ctx context.Context, userID int64, page, pageSize int) ([]*User, error) {
  763. /*
  764. Equivalent SQL for PostgreSQL:
  765. SELECT * FROM "user"
  766. LEFT JOIN follow ON follow.user_id = "user".id
  767. WHERE follow.follow_id = @userID
  768. ORDER BY follow.id DESC
  769. LIMIT @limit OFFSET @offset
  770. */
  771. users := make([]*User, 0, pageSize)
  772. return users, db.WithContext(ctx).
  773. Joins(dbutil.Quote("LEFT JOIN follow ON follow.user_id = %s.id", "user")).
  774. Where("follow.follow_id = ?", userID).
  775. Limit(pageSize).Offset((page - 1) * pageSize).
  776. Order("follow.id DESC").
  777. Find(&users).
  778. Error
  779. }
  780. func (db *users) ListFollowings(ctx context.Context, userID int64, page, pageSize int) ([]*User, error) {
  781. /*
  782. Equivalent SQL for PostgreSQL:
  783. SELECT * FROM "user"
  784. LEFT JOIN follow ON follow.user_id = "user".id
  785. WHERE follow.user_id = @userID
  786. ORDER BY follow.id DESC
  787. LIMIT @limit OFFSET @offset
  788. */
  789. users := make([]*User, 0, pageSize)
  790. return users, db.WithContext(ctx).
  791. Joins(dbutil.Quote("LEFT JOIN follow ON follow.follow_id = %s.id", "user")).
  792. Where("follow.user_id = ?", userID).
  793. Limit(pageSize).Offset((page - 1) * pageSize).
  794. Order("follow.id DESC").
  795. Find(&users).
  796. Error
  797. }
  798. func searchUserByName(ctx context.Context, db *gorm.DB, userType UserType, keyword string, page, pageSize int, orderBy string) ([]*User, int64, error) {
  799. if keyword == "" {
  800. return []*User{}, 0, nil
  801. }
  802. keyword = "%" + strings.ToLower(keyword) + "%"
  803. tx := db.WithContext(ctx).
  804. Where("type = ? AND (lower_name LIKE ? OR LOWER(full_name) LIKE ?)", userType, keyword, keyword)
  805. var count int64
  806. err := tx.Model(&User{}).Count(&count).Error
  807. if err != nil {
  808. return nil, 0, errors.Wrap(err, "count")
  809. }
  810. users := make([]*User, 0, pageSize)
  811. return users, count, tx.Order(orderBy).Limit(pageSize).Offset((page - 1) * pageSize).Find(&users).Error
  812. }
  813. func (db *users) SearchByName(ctx context.Context, keyword string, page, pageSize int, orderBy string) ([]*User, int64, error) {
  814. return searchUserByName(ctx, db.DB, UserTypeIndividual, keyword, page, pageSize, orderBy)
  815. }
  816. type UpdateUserOptions struct {
  817. LoginSource *int64
  818. LoginName *string
  819. Password *string
  820. // GenerateNewRands indicates whether to force generate new rands for the user.
  821. GenerateNewRands bool
  822. FullName *string
  823. Email *string
  824. Website *string
  825. Location *string
  826. Description *string
  827. MaxRepoCreation *int
  828. LastRepoVisibility *bool
  829. IsActivated *bool
  830. IsAdmin *bool
  831. AllowGitHook *bool
  832. AllowImportLocal *bool
  833. ProhibitLogin *bool
  834. Avatar *string
  835. AvatarEmail *string
  836. }
  837. func (db *users) Update(ctx context.Context, userID int64, opts UpdateUserOptions) error {
  838. updates := map[string]any{
  839. "updated_unix": db.NowFunc().Unix(),
  840. }
  841. if opts.LoginSource != nil {
  842. updates["login_source"] = *opts.LoginSource
  843. }
  844. if opts.LoginName != nil {
  845. updates["login_name"] = *opts.LoginName
  846. }
  847. if opts.Password != nil {
  848. salt, err := userutil.RandomSalt()
  849. if err != nil {
  850. return errors.Wrap(err, "generate salt")
  851. }
  852. updates["salt"] = salt
  853. updates["passwd"] = userutil.EncodePassword(*opts.Password, salt)
  854. opts.GenerateNewRands = true
  855. }
  856. if opts.GenerateNewRands {
  857. rands, err := userutil.RandomSalt()
  858. if err != nil {
  859. return errors.Wrap(err, "generate rands")
  860. }
  861. updates["rands"] = rands
  862. }
  863. if opts.FullName != nil {
  864. updates["full_name"] = strutil.Truncate(*opts.FullName, 255)
  865. }
  866. if opts.Email != nil {
  867. _, err := db.GetByEmail(ctx, *opts.Email)
  868. if err == nil {
  869. return ErrEmailAlreadyUsed{args: errutil.Args{"email": *opts.Email}}
  870. } else if !IsErrUserNotExist(err) {
  871. return errors.Wrap(err, "check email")
  872. }
  873. updates["email"] = *opts.Email
  874. }
  875. if opts.Website != nil {
  876. updates["website"] = strutil.Truncate(*opts.Website, 255)
  877. }
  878. if opts.Location != nil {
  879. updates["location"] = strutil.Truncate(*opts.Location, 255)
  880. }
  881. if opts.Description != nil {
  882. updates["description"] = strutil.Truncate(*opts.Description, 255)
  883. }
  884. if opts.MaxRepoCreation != nil {
  885. if *opts.MaxRepoCreation < -1 {
  886. *opts.MaxRepoCreation = -1
  887. }
  888. updates["max_repo_creation"] = *opts.MaxRepoCreation
  889. }
  890. if opts.LastRepoVisibility != nil {
  891. updates["last_repo_visibility"] = *opts.LastRepoVisibility
  892. }
  893. if opts.IsActivated != nil {
  894. updates["is_active"] = *opts.IsActivated
  895. }
  896. if opts.IsAdmin != nil {
  897. updates["is_admin"] = *opts.IsAdmin
  898. }
  899. if opts.AllowGitHook != nil {
  900. updates["allow_git_hook"] = *opts.AllowGitHook
  901. }
  902. if opts.AllowImportLocal != nil {
  903. updates["allow_import_local"] = *opts.AllowImportLocal
  904. }
  905. if opts.ProhibitLogin != nil {
  906. updates["prohibit_login"] = *opts.ProhibitLogin
  907. }
  908. if opts.Avatar != nil {
  909. updates["avatar"] = strutil.Truncate(*opts.Avatar, 2048)
  910. }
  911. if opts.AvatarEmail != nil {
  912. updates["avatar_email"] = strutil.Truncate(*opts.AvatarEmail, 255)
  913. }
  914. return db.WithContext(ctx).Model(&User{}).Where("id = ?", userID).Updates(updates).Error
  915. }
  916. func (db *users) UseCustomAvatar(ctx context.Context, userID int64, avatar []byte) error {
  917. err := userutil.SaveAvatar(userID, avatar)
  918. if err != nil {
  919. return errors.Wrap(err, "save avatar")
  920. }
  921. return db.WithContext(ctx).
  922. Model(&User{}).
  923. Where("id = ?", userID).
  924. Updates(map[string]any{
  925. "use_custom_avatar": true,
  926. "updated_unix": db.NowFunc().Unix(),
  927. }).
  928. Error
  929. }
  930. // UserType indicates the type of the user account.
  931. type UserType int
  932. const (
  933. UserTypeIndividual UserType = iota // NOTE: Historic reason to make it starts at 0.
  934. UserTypeOrganization
  935. )
  936. // User represents the object of an individual or an organization.
  937. type User struct {
  938. ID int64 `gorm:"primaryKey"`
  939. LowerName string `xorm:"UNIQUE NOT NULL" gorm:"unique;not null"`
  940. Name string `xorm:"UNIQUE NOT NULL" gorm:"not null"`
  941. FullName string
  942. // Email is the primary email address (to be used for communication)
  943. Email string `xorm:"NOT NULL" gorm:"not null"`
  944. Password string `xorm:"passwd NOT NULL" gorm:"column:passwd;not null"`
  945. LoginSource int64 `xorm:"NOT NULL DEFAULT 0" gorm:"not null;default:0"`
  946. LoginName string
  947. Type UserType
  948. Location string
  949. Website string
  950. Rands string `xorm:"VARCHAR(10)" gorm:"type:VARCHAR(10)"`
  951. Salt string `xorm:"VARCHAR(10)" gorm:"type:VARCHAR(10)"`
  952. Created time.Time `xorm:"-" gorm:"-" json:"-"`
  953. CreatedUnix int64
  954. Updated time.Time `xorm:"-" gorm:"-" json:"-"`
  955. UpdatedUnix int64
  956. // Remember visibility choice for convenience, true for private
  957. LastRepoVisibility bool
  958. // Maximum repository creation limit, -1 means use global default
  959. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1" gorm:"not null;default:-1"`
  960. // Permissions
  961. IsActive bool // Activate primary email
  962. IsAdmin bool
  963. AllowGitHook bool
  964. AllowImportLocal bool // Allow migrate repository by local path
  965. ProhibitLogin bool
  966. // Avatar
  967. Avatar string `xorm:"VARCHAR(2048) NOT NULL" gorm:"type:VARCHAR(2048);not null"`
  968. AvatarEmail string `xorm:"NOT NULL" gorm:"not null"`
  969. UseCustomAvatar bool
  970. // Counters
  971. NumFollowers int
  972. NumFollowing int `xorm:"NOT NULL DEFAULT 0" gorm:"not null;default:0"`
  973. NumStars int
  974. NumRepos int
  975. // For organization
  976. Description string
  977. NumTeams int
  978. NumMembers int
  979. Teams []*Team `xorm:"-" gorm:"-" json:"-"`
  980. Members []*User `xorm:"-" gorm:"-" json:"-"`
  981. }
  982. // BeforeCreate implements the GORM create hook.
  983. func (u *User) BeforeCreate(tx *gorm.DB) error {
  984. if u.CreatedUnix == 0 {
  985. u.CreatedUnix = tx.NowFunc().Unix()
  986. u.UpdatedUnix = u.CreatedUnix
  987. }
  988. return nil
  989. }
  990. // AfterFind implements the GORM query hook.
  991. func (u *User) AfterFind(_ *gorm.DB) error {
  992. u.FullName = markup.Sanitize(u.FullName)
  993. u.Created = time.Unix(u.CreatedUnix, 0).Local()
  994. u.Updated = time.Unix(u.UpdatedUnix, 0).Local()
  995. return nil
  996. }
  997. // IsLocal returns true if the user is created as local account.
  998. func (u *User) IsLocal() bool {
  999. return u.LoginSource <= 0
  1000. }
  1001. // IsOrganization returns true if the user is an organization.
  1002. func (u *User) IsOrganization() bool {
  1003. return u.Type == UserTypeOrganization
  1004. }
  1005. // APIFormat returns the API format of a user.
  1006. func (u *User) APIFormat() *api.User {
  1007. return &api.User{
  1008. ID: u.ID,
  1009. UserName: u.Name,
  1010. Login: u.Name,
  1011. FullName: u.FullName,
  1012. Email: u.Email,
  1013. AvatarUrl: u.AvatarURL(),
  1014. }
  1015. }
  1016. // maxNumRepos returns the maximum number of repositories that the user can have
  1017. // direct ownership.
  1018. func (u *User) maxNumRepos() int {
  1019. if u.MaxRepoCreation <= -1 {
  1020. return conf.Repository.MaxCreationLimit
  1021. }
  1022. return u.MaxRepoCreation
  1023. }
  1024. // canCreateRepo returns true if the user can create a repository.
  1025. func (u *User) canCreateRepo() bool {
  1026. return u.maxNumRepos() <= -1 || u.NumRepos < u.maxNumRepos()
  1027. }
  1028. // CanCreateOrganization returns true if user can create organizations.
  1029. func (u *User) CanCreateOrganization() bool {
  1030. return !conf.Admin.DisableRegularOrgCreation || u.IsAdmin
  1031. }
  1032. // CanEditGitHook returns true if user can edit Git hooks.
  1033. func (u *User) CanEditGitHook() bool {
  1034. return u.IsAdmin || u.AllowGitHook
  1035. }
  1036. // CanImportLocal returns true if user can migrate repositories by local path.
  1037. func (u *User) CanImportLocal() bool {
  1038. return conf.Repository.EnableLocalPathMigration && (u.IsAdmin || u.AllowImportLocal)
  1039. }
  1040. // DisplayName returns the full name of the user if it's not empty, returns the
  1041. // username otherwise.
  1042. func (u *User) DisplayName() string {
  1043. if len(u.FullName) > 0 {
  1044. return u.FullName
  1045. }
  1046. return u.Name
  1047. }
  1048. // HomeURLPath returns the URL path to the user or organization home page.
  1049. //
  1050. // TODO(unknwon): This is also used in templates, which should be fixed by
  1051. // having a dedicated type `template.User` and move this to the "userutil"
  1052. // package.
  1053. func (u *User) HomeURLPath() string {
  1054. return conf.Server.Subpath + "/" + u.Name
  1055. }
  1056. // HTMLURL returns the full URL to the user or organization home page.
  1057. //
  1058. // TODO(unknwon): This is also used in templates, which should be fixed by
  1059. // having a dedicated type `template.User` and move this to the "userutil"
  1060. // package.
  1061. func (u *User) HTMLURL() string {
  1062. return conf.Server.ExternalURL + u.Name
  1063. }
  1064. // AvatarURLPath returns the URL path to the user or organization avatar. If the
  1065. // user enables Gravatar-like service, then an external URL will be returned.
  1066. //
  1067. // TODO(unknwon): This is also used in templates, which should be fixed by
  1068. // having a dedicated type `template.User` and move this to the "userutil"
  1069. // package.
  1070. func (u *User) AvatarURLPath() string {
  1071. defaultURLPath := conf.UserDefaultAvatarURLPath()
  1072. if u.ID <= 0 {
  1073. return defaultURLPath
  1074. }
  1075. hasCustomAvatar := osutil.IsFile(userutil.CustomAvatarPath(u.ID))
  1076. switch {
  1077. case u.UseCustomAvatar:
  1078. if !hasCustomAvatar {
  1079. return defaultURLPath
  1080. }
  1081. return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, conf.UsersAvatarPathPrefix, u.ID)
  1082. case conf.Picture.DisableGravatar:
  1083. if !hasCustomAvatar {
  1084. if err := userutil.GenerateRandomAvatar(u.ID, u.Name, u.Email); err != nil {
  1085. log.Error("Failed to generate random avatar [user_id: %d]: %v", u.ID, err)
  1086. }
  1087. }
  1088. return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, conf.UsersAvatarPathPrefix, u.ID)
  1089. }
  1090. return tool.AvatarLink(u.AvatarEmail)
  1091. }
  1092. // AvatarURL returns the full URL to the user or organization avatar. If the
  1093. // user enables Gravatar-like service, then an external URL will be returned.
  1094. //
  1095. // TODO(unknwon): This is also used in templates, which should be fixed by
  1096. // having a dedicated type `template.User` and move this to the "userutil"
  1097. // package.
  1098. func (u *User) AvatarURL() string {
  1099. link := u.AvatarURLPath()
  1100. if link[0] == '/' && link[1] != '/' {
  1101. return conf.Server.ExternalURL + strings.TrimPrefix(link, conf.Server.Subpath)[1:]
  1102. }
  1103. return link
  1104. }
  1105. // IsFollowing returns true if the user is following the given user.
  1106. //
  1107. // TODO(unknwon): This is also used in templates, which should be fixed by
  1108. // having a dedicated type `template.User`.
  1109. func (u *User) IsFollowing(followID int64) bool {
  1110. return Users.IsFollowing(context.TODO(), u.ID, followID)
  1111. }
  1112. // IsUserOrgOwner returns true if the user is in the owner team of the given
  1113. // organization.
  1114. //
  1115. // TODO(unknwon): This is also used in templates, which should be fixed by
  1116. // having a dedicated type `template.User`.
  1117. func (u *User) IsUserOrgOwner(orgId int64) bool {
  1118. return IsOrganizationOwner(orgId, u.ID)
  1119. }
  1120. // IsPublicMember returns true if the user has public membership of the given
  1121. // organization.
  1122. //
  1123. // TODO(unknwon): This is also used in templates, which should be fixed by
  1124. // having a dedicated type `template.User`.
  1125. func (u *User) IsPublicMember(orgId int64) bool {
  1126. return IsPublicMembership(orgId, u.ID)
  1127. }
  1128. // GetOrganizationCount returns the count of organization membership that the
  1129. // user has.
  1130. //
  1131. // TODO(unknwon): This is also used in templates, which should be fixed by
  1132. // having a dedicated type `template.User`.
  1133. func (u *User) GetOrganizationCount() (int64, error) {
  1134. return Orgs.CountByUser(context.TODO(), u.ID)
  1135. }
  1136. // ShortName truncates and returns the username at most in given length.
  1137. //
  1138. // TODO(unknwon): This is also used in templates, which should be fixed by
  1139. // having a dedicated type `template.User`.
  1140. func (u *User) ShortName(length int) string {
  1141. return strutil.Ellipsis(u.Name, length)
  1142. }
  1143. // NewGhostUser creates and returns a fake user for people who has deleted their
  1144. // accounts.
  1145. //
  1146. // TODO: Once migrated to unknwon.dev/i18n, pass in the `i18n.Locale` to
  1147. // translate the text to local language.
  1148. func NewGhostUser() *User {
  1149. return &User{
  1150. ID: -1,
  1151. Name: "Ghost",
  1152. LowerName: "ghost",
  1153. }
  1154. }
  1155. var (
  1156. reservedUsernames = map[string]struct{}{
  1157. "-": {},
  1158. "explore": {},
  1159. "create": {},
  1160. "assets": {},
  1161. "css": {},
  1162. "img": {},
  1163. "js": {},
  1164. "less": {},
  1165. "plugins": {},
  1166. "debug": {},
  1167. "raw": {},
  1168. "install": {},
  1169. "api": {},
  1170. "avatar": {},
  1171. "user": {},
  1172. "org": {},
  1173. "help": {},
  1174. "stars": {},
  1175. "issues": {},
  1176. "pulls": {},
  1177. "commits": {},
  1178. "repo": {},
  1179. "template": {},
  1180. "admin": {},
  1181. "new": {},
  1182. ".": {},
  1183. "..": {},
  1184. }
  1185. reservedUsernamePatterns = []string{"*.keys"}
  1186. )
  1187. type ErrNameNotAllowed struct {
  1188. args errutil.Args
  1189. }
  1190. // IsErrNameNotAllowed returns true if the underlying error has the type
  1191. // ErrNameNotAllowed.
  1192. func IsErrNameNotAllowed(err error) bool {
  1193. _, ok := errors.Cause(err).(ErrNameNotAllowed)
  1194. return ok
  1195. }
  1196. func (err ErrNameNotAllowed) Value() string {
  1197. val, ok := err.args["name"].(string)
  1198. if ok {
  1199. return val
  1200. }
  1201. val, ok = err.args["pattern"].(string)
  1202. if ok {
  1203. return val
  1204. }
  1205. return "<value not found>"
  1206. }
  1207. func (err ErrNameNotAllowed) Error() string {
  1208. return fmt.Sprintf("name is not allowed: %v", err.args)
  1209. }
  1210. // isNameAllowed checks if the name is reserved or pattern of the name is not
  1211. // allowed based on given reserved names and patterns. Names are exact match,
  1212. // patterns can be prefix or suffix match with the wildcard ("*").
  1213. func isNameAllowed(names map[string]struct{}, patterns []string, name string) error {
  1214. name = strings.TrimSpace(strings.ToLower(name))
  1215. if utf8.RuneCountInString(name) == 0 {
  1216. return ErrNameNotAllowed{
  1217. args: errutil.Args{
  1218. "reason": "empty name",
  1219. },
  1220. }
  1221. }
  1222. if _, ok := names[name]; ok {
  1223. return ErrNameNotAllowed{
  1224. args: errutil.Args{
  1225. "reason": "reserved",
  1226. "name": name,
  1227. },
  1228. }
  1229. }
  1230. for _, pattern := range patterns {
  1231. if pattern[0] == '*' && strings.HasSuffix(name, pattern[1:]) ||
  1232. (pattern[len(pattern)-1] == '*' && strings.HasPrefix(name, pattern[:len(pattern)-1])) {
  1233. return ErrNameNotAllowed{
  1234. args: errutil.Args{
  1235. "reason": "reserved",
  1236. "pattern": pattern,
  1237. },
  1238. }
  1239. }
  1240. }
  1241. return nil
  1242. }
  1243. // isUsernameAllowed returns ErrNameNotAllowed if the given name or pattern of
  1244. // the name is not allowed as a username.
  1245. func isUsernameAllowed(name string) error {
  1246. return isNameAllowed(reservedUsernames, reservedUsernamePatterns, name)
  1247. }
  1248. // Follow represents relations of users and their followers.
  1249. type Follow struct {
  1250. ID int64 `gorm:"primaryKey"`
  1251. UserID int64 `xorm:"UNIQUE(follow)" gorm:"uniqueIndex:follow_user_follow_unique;not null"`
  1252. FollowID int64 `xorm:"UNIQUE(follow)" gorm:"uniqueIndex:follow_user_follow_unique;not null"`
  1253. }