users.go 48 KB

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