You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

user.go 35KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package user
  5. import (
  6. "context"
  7. "encoding/hex"
  8. "fmt"
  9. "net/url"
  10. "path/filepath"
  11. "regexp"
  12. "strings"
  13. "time"
  14. "unicode"
  15. _ "image/jpeg" // Needed for jpeg support
  16. "code.gitea.io/gitea/models/auth"
  17. "code.gitea.io/gitea/models/db"
  18. "code.gitea.io/gitea/modules/auth/openid"
  19. "code.gitea.io/gitea/modules/auth/password/hash"
  20. "code.gitea.io/gitea/modules/base"
  21. "code.gitea.io/gitea/modules/container"
  22. "code.gitea.io/gitea/modules/git"
  23. "code.gitea.io/gitea/modules/log"
  24. "code.gitea.io/gitea/modules/optional"
  25. "code.gitea.io/gitea/modules/setting"
  26. "code.gitea.io/gitea/modules/structs"
  27. "code.gitea.io/gitea/modules/timeutil"
  28. "code.gitea.io/gitea/modules/util"
  29. "code.gitea.io/gitea/modules/validation"
  30. "golang.org/x/text/runes"
  31. "golang.org/x/text/transform"
  32. "golang.org/x/text/unicode/norm"
  33. "xorm.io/builder"
  34. )
  35. // UserType defines the user type
  36. type UserType int //revive:disable-line:exported
  37. const (
  38. // UserTypeIndividual defines an individual user
  39. UserTypeIndividual UserType = iota // Historic reason to make it starts at 0.
  40. // UserTypeOrganization defines an organization
  41. UserTypeOrganization
  42. // UserTypeUserReserved reserves a (non-existing) user, i.e. to prevent a spam user from re-registering after being deleted, or to reserve the name until the user is actually created later on
  43. UserTypeUserReserved
  44. // UserTypeOrganizationReserved reserves a (non-existing) organization, to be used in combination with UserTypeUserReserved
  45. UserTypeOrganizationReserved
  46. // UserTypeBot defines a bot user
  47. UserTypeBot
  48. // UserTypeRemoteUser defines a remote user for federated users
  49. UserTypeRemoteUser
  50. )
  51. const (
  52. // EmailNotificationsEnabled indicates that the user would like to receive all email notifications except your own
  53. EmailNotificationsEnabled = "enabled"
  54. // EmailNotificationsOnMention indicates that the user would like to be notified via email when mentioned.
  55. EmailNotificationsOnMention = "onmention"
  56. // EmailNotificationsDisabled indicates that the user would not like to be notified via email.
  57. EmailNotificationsDisabled = "disabled"
  58. // EmailNotificationsAndYourOwn indicates that the user would like to receive all email notifications and your own
  59. EmailNotificationsAndYourOwn = "andyourown"
  60. )
  61. // User represents the object of individual and member of organization.
  62. type User struct {
  63. ID int64 `xorm:"pk autoincr"`
  64. LowerName string `xorm:"UNIQUE NOT NULL"`
  65. Name string `xorm:"UNIQUE NOT NULL"`
  66. FullName string
  67. // Email is the primary email address (to be used for communication)
  68. Email string `xorm:"NOT NULL"`
  69. KeepEmailPrivate bool
  70. EmailNotificationsPreference string `xorm:"VARCHAR(20) NOT NULL DEFAULT 'enabled'"`
  71. Passwd string `xorm:"NOT NULL"`
  72. PasswdHashAlgo string `xorm:"NOT NULL DEFAULT 'argon2'"`
  73. // MustChangePassword is an attribute that determines if a user
  74. // is to change their password after registration.
  75. MustChangePassword bool `xorm:"NOT NULL DEFAULT false"`
  76. LoginType auth.Type
  77. LoginSource int64 `xorm:"NOT NULL DEFAULT 0"`
  78. LoginName string
  79. Type UserType
  80. Location string
  81. Website string
  82. Rands string `xorm:"VARCHAR(32)"`
  83. Salt string `xorm:"VARCHAR(32)"`
  84. Language string `xorm:"VARCHAR(5)"`
  85. Description string
  86. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  87. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  88. LastLoginUnix timeutil.TimeStamp `xorm:"INDEX"`
  89. // Remember visibility choice for convenience, true for private
  90. LastRepoVisibility bool
  91. // Maximum repository creation limit, -1 means use global default
  92. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1"`
  93. // IsActive true: primary email is activated, user can access Web UI and Git SSH.
  94. // false: an inactive user can only log in Web UI for account operations (ex: activate the account by email), no other access.
  95. IsActive bool `xorm:"INDEX"`
  96. // the user is a Gitea admin, who can access all repositories and the admin pages.
  97. IsAdmin bool
  98. // true: the user is only allowed to see organizations/repositories that they has explicit rights to.
  99. // (ex: in private Gitea instances user won't be allowed to see even organizations/repositories that are set as public)
  100. IsRestricted bool `xorm:"NOT NULL DEFAULT false"`
  101. AllowGitHook bool
  102. AllowImportLocal bool // Allow migrate repository by local path
  103. AllowCreateOrganization bool `xorm:"DEFAULT true"`
  104. // true: the user is not allowed to log in Web UI. Git/SSH access could still be allowed (please refer to Git/SSH access related code/documents)
  105. ProhibitLogin bool `xorm:"NOT NULL DEFAULT false"`
  106. // Avatar
  107. Avatar string `xorm:"VARCHAR(2048) NOT NULL"`
  108. AvatarEmail string `xorm:"NOT NULL"`
  109. UseCustomAvatar bool
  110. // Counters
  111. NumFollowers int
  112. NumFollowing int `xorm:"NOT NULL DEFAULT 0"`
  113. NumStars int
  114. NumRepos int
  115. // For organization
  116. NumTeams int
  117. NumMembers int
  118. Visibility structs.VisibleType `xorm:"NOT NULL DEFAULT 0"`
  119. RepoAdminChangeTeamAccess bool `xorm:"NOT NULL DEFAULT false"`
  120. // Preferences
  121. DiffViewStyle string `xorm:"NOT NULL DEFAULT ''"`
  122. Theme string `xorm:"NOT NULL DEFAULT ''"`
  123. KeepActivityPrivate bool `xorm:"NOT NULL DEFAULT false"`
  124. }
  125. func init() {
  126. db.RegisterModel(new(User))
  127. }
  128. // SearchOrganizationsOptions options to filter organizations
  129. type SearchOrganizationsOptions struct {
  130. db.ListOptions
  131. All bool
  132. }
  133. func (u *User) LogString() string {
  134. if u == nil {
  135. return "<User nil>"
  136. }
  137. return fmt.Sprintf("<User %d:%s>", u.ID, u.Name)
  138. }
  139. // BeforeUpdate is invoked from XORM before updating this object.
  140. func (u *User) BeforeUpdate() {
  141. if u.MaxRepoCreation < -1 {
  142. u.MaxRepoCreation = -1
  143. }
  144. // Organization does not need email
  145. u.Email = strings.ToLower(u.Email)
  146. if !u.IsOrganization() {
  147. if len(u.AvatarEmail) == 0 {
  148. u.AvatarEmail = u.Email
  149. }
  150. }
  151. u.LowerName = strings.ToLower(u.Name)
  152. u.Location = base.TruncateString(u.Location, 255)
  153. u.Website = base.TruncateString(u.Website, 255)
  154. u.Description = base.TruncateString(u.Description, 255)
  155. }
  156. // AfterLoad is invoked from XORM after filling all the fields of this object.
  157. func (u *User) AfterLoad() {
  158. if u.Theme == "" {
  159. u.Theme = setting.UI.DefaultTheme
  160. }
  161. }
  162. // SetLastLogin set time to last login
  163. func (u *User) SetLastLogin() {
  164. u.LastLoginUnix = timeutil.TimeStampNow()
  165. }
  166. // GetPlaceholderEmail returns an noreply email
  167. func (u *User) GetPlaceholderEmail() string {
  168. return fmt.Sprintf("%s@%s", u.LowerName, setting.Service.NoReplyAddress)
  169. }
  170. // GetEmail returns an noreply email, if the user has set to keep his
  171. // email address private, otherwise the primary email address.
  172. func (u *User) GetEmail() string {
  173. if u.KeepEmailPrivate {
  174. return u.GetPlaceholderEmail()
  175. }
  176. return u.Email
  177. }
  178. // GetAllUsers returns a slice of all individual users found in DB.
  179. func GetAllUsers(ctx context.Context) ([]*User, error) {
  180. users := make([]*User, 0)
  181. return users, db.GetEngine(ctx).OrderBy("id").Where("type = ?", UserTypeIndividual).Find(&users)
  182. }
  183. // IsLocal returns true if user login type is LoginPlain.
  184. func (u *User) IsLocal() bool {
  185. return u.LoginType <= auth.Plain
  186. }
  187. // IsOAuth2 returns true if user login type is LoginOAuth2.
  188. func (u *User) IsOAuth2() bool {
  189. return u.LoginType == auth.OAuth2
  190. }
  191. // MaxCreationLimit returns the number of repositories a user is allowed to create
  192. func (u *User) MaxCreationLimit() int {
  193. if u.MaxRepoCreation <= -1 {
  194. return setting.Repository.MaxCreationLimit
  195. }
  196. return u.MaxRepoCreation
  197. }
  198. // CanCreateRepo returns if user login can create a repository
  199. // NOTE: functions calling this assume a failure due to repository count limit; if new checks are added, those functions should be revised
  200. func (u *User) CanCreateRepo() bool {
  201. if u.IsAdmin {
  202. return true
  203. }
  204. if u.MaxRepoCreation <= -1 {
  205. if setting.Repository.MaxCreationLimit <= -1 {
  206. return true
  207. }
  208. return u.NumRepos < setting.Repository.MaxCreationLimit
  209. }
  210. return u.NumRepos < u.MaxRepoCreation
  211. }
  212. // CanCreateOrganization returns true if user can create organisation.
  213. func (u *User) CanCreateOrganization() bool {
  214. return u.IsAdmin || (u.AllowCreateOrganization && !setting.Admin.DisableRegularOrgCreation)
  215. }
  216. // CanEditGitHook returns true if user can edit Git hooks.
  217. func (u *User) CanEditGitHook() bool {
  218. return !setting.DisableGitHooks && (u.IsAdmin || u.AllowGitHook)
  219. }
  220. // CanForkRepo returns if user login can fork a repository
  221. // It checks especially that the user can create repos, and potentially more
  222. func (u *User) CanForkRepo() bool {
  223. if setting.Repository.AllowForkWithoutMaximumLimit {
  224. return true
  225. }
  226. return u.CanCreateRepo()
  227. }
  228. // CanImportLocal returns true if user can migrate repository by local path.
  229. func (u *User) CanImportLocal() bool {
  230. if !setting.ImportLocalPaths || u == nil {
  231. return false
  232. }
  233. return u.IsAdmin || u.AllowImportLocal
  234. }
  235. // DashboardLink returns the user dashboard page link.
  236. func (u *User) DashboardLink() string {
  237. if u.IsOrganization() {
  238. return u.OrganisationLink() + "/dashboard"
  239. }
  240. return setting.AppSubURL + "/"
  241. }
  242. // HomeLink returns the user or organization home page link.
  243. func (u *User) HomeLink() string {
  244. return setting.AppSubURL + "/" + url.PathEscape(u.Name)
  245. }
  246. // HTMLURL returns the user or organization's full link.
  247. func (u *User) HTMLURL() string {
  248. return setting.AppURL + url.PathEscape(u.Name)
  249. }
  250. // OrganisationLink returns the organization sub page link.
  251. func (u *User) OrganisationLink() string {
  252. return setting.AppSubURL + "/org/" + url.PathEscape(u.Name)
  253. }
  254. // GenerateEmailActivateCode generates an activate code based on user information and given e-mail.
  255. func (u *User) GenerateEmailActivateCode(email string) string {
  256. code := base.CreateTimeLimitCode(
  257. fmt.Sprintf("%d%s%s%s%s", u.ID, email, u.LowerName, u.Passwd, u.Rands),
  258. setting.Service.ActiveCodeLives, nil)
  259. // Add tail hex username
  260. code += hex.EncodeToString([]byte(u.LowerName))
  261. return code
  262. }
  263. // GetUserFollowers returns range of user's followers.
  264. func GetUserFollowers(ctx context.Context, u, viewer *User, listOptions db.ListOptions) ([]*User, int64, error) {
  265. sess := db.GetEngine(ctx).
  266. Select("`user`.*").
  267. Join("LEFT", "follow", "`user`.id=follow.user_id").
  268. Where("follow.follow_id=?", u.ID).
  269. And("`user`.type=?", UserTypeIndividual).
  270. And(isUserVisibleToViewerCond(viewer))
  271. if listOptions.Page != 0 {
  272. sess = db.SetSessionPagination(sess, &listOptions)
  273. users := make([]*User, 0, listOptions.PageSize)
  274. count, err := sess.FindAndCount(&users)
  275. return users, count, err
  276. }
  277. users := make([]*User, 0, 8)
  278. count, err := sess.FindAndCount(&users)
  279. return users, count, err
  280. }
  281. // GetUserFollowing returns range of user's following.
  282. func GetUserFollowing(ctx context.Context, u, viewer *User, listOptions db.ListOptions) ([]*User, int64, error) {
  283. sess := db.GetEngine(ctx).
  284. Select("`user`.*").
  285. Join("LEFT", "follow", "`user`.id=follow.follow_id").
  286. Where("follow.user_id=?", u.ID).
  287. And("`user`.type IN (?, ?)", UserTypeIndividual, UserTypeOrganization).
  288. And(isUserVisibleToViewerCond(viewer))
  289. if listOptions.Page != 0 {
  290. sess = db.SetSessionPagination(sess, &listOptions)
  291. users := make([]*User, 0, listOptions.PageSize)
  292. count, err := sess.FindAndCount(&users)
  293. return users, count, err
  294. }
  295. users := make([]*User, 0, 8)
  296. count, err := sess.FindAndCount(&users)
  297. return users, count, err
  298. }
  299. // NewGitSig generates and returns the signature of given user.
  300. func (u *User) NewGitSig() *git.Signature {
  301. return &git.Signature{
  302. Name: u.GitName(),
  303. Email: u.GetEmail(),
  304. When: time.Now(),
  305. }
  306. }
  307. // SetPassword hashes a password using the algorithm defined in the config value of PASSWORD_HASH_ALGO
  308. // change passwd, salt and passwd_hash_algo fields
  309. func (u *User) SetPassword(passwd string) (err error) {
  310. if u.Salt, err = GetUserSalt(); err != nil {
  311. return err
  312. }
  313. if u.Passwd, err = hash.Parse(setting.PasswordHashAlgo).Hash(passwd, u.Salt); err != nil {
  314. return err
  315. }
  316. u.PasswdHashAlgo = setting.PasswordHashAlgo
  317. return nil
  318. }
  319. // ValidatePassword checks if the given password matches the one belonging to the user.
  320. func (u *User) ValidatePassword(passwd string) bool {
  321. return hash.Parse(u.PasswdHashAlgo).VerifyPassword(passwd, u.Passwd, u.Salt)
  322. }
  323. // IsPasswordSet checks if the password is set or left empty
  324. func (u *User) IsPasswordSet() bool {
  325. return len(u.Passwd) != 0
  326. }
  327. // IsOrganization returns true if user is actually a organization.
  328. func (u *User) IsOrganization() bool {
  329. return u.Type == UserTypeOrganization
  330. }
  331. // IsIndividual returns true if user is actually a individual user.
  332. func (u *User) IsIndividual() bool {
  333. return u.Type == UserTypeIndividual
  334. }
  335. // IsBot returns whether or not the user is of type bot
  336. func (u *User) IsBot() bool {
  337. return u.Type == UserTypeBot
  338. }
  339. // DisplayName returns full name if it's not empty,
  340. // returns username otherwise.
  341. func (u *User) DisplayName() string {
  342. trimmed := strings.TrimSpace(u.FullName)
  343. if len(trimmed) > 0 {
  344. return trimmed
  345. }
  346. return u.Name
  347. }
  348. // GetDisplayName returns full name if it's not empty and DEFAULT_SHOW_FULL_NAME is set,
  349. // returns username otherwise.
  350. func (u *User) GetDisplayName() string {
  351. if setting.UI.DefaultShowFullName {
  352. trimmed := strings.TrimSpace(u.FullName)
  353. if len(trimmed) > 0 {
  354. return trimmed
  355. }
  356. }
  357. return u.Name
  358. }
  359. // GetCompleteName returns the full name and username in the form of
  360. // "Full Name (username)" if full name is not empty, otherwise it returns
  361. // "username".
  362. func (u *User) GetCompleteName() string {
  363. trimmedFullName := strings.TrimSpace(u.FullName)
  364. if len(trimmedFullName) > 0 {
  365. return fmt.Sprintf("%s (%s)", trimmedFullName, u.Name)
  366. }
  367. return u.Name
  368. }
  369. func gitSafeName(name string) string {
  370. return strings.TrimSpace(strings.NewReplacer("\n", "", "<", "", ">", "").Replace(name))
  371. }
  372. // GitName returns a git safe name
  373. func (u *User) GitName() string {
  374. gitName := gitSafeName(u.FullName)
  375. if len(gitName) > 0 {
  376. return gitName
  377. }
  378. // Although u.Name should be safe if created in our system
  379. // LDAP users may have bad names
  380. gitName = gitSafeName(u.Name)
  381. if len(gitName) > 0 {
  382. return gitName
  383. }
  384. // Totally pathological name so it's got to be:
  385. return fmt.Sprintf("user-%d", u.ID)
  386. }
  387. // ShortName ellipses username to length
  388. func (u *User) ShortName(length int) string {
  389. if setting.UI.DefaultShowFullName && len(u.FullName) > 0 {
  390. return base.EllipsisString(u.FullName, length)
  391. }
  392. return base.EllipsisString(u.Name, length)
  393. }
  394. // IsMailable checks if a user is eligible
  395. // to receive emails.
  396. func (u *User) IsMailable() bool {
  397. return u.IsActive
  398. }
  399. // IsUserExist checks if given user name exist,
  400. // the user name should be noncased unique.
  401. // If uid is presented, then check will rule out that one,
  402. // it is used when update a user name in settings page.
  403. func IsUserExist(ctx context.Context, uid int64, name string) (bool, error) {
  404. if len(name) == 0 {
  405. return false, nil
  406. }
  407. return db.GetEngine(ctx).
  408. Where("id!=?", uid).
  409. Get(&User{LowerName: strings.ToLower(name)})
  410. }
  411. // Note: As of the beginning of 2022, it is recommended to use at least
  412. // 64 bits of salt, but NIST is already recommending to use to 128 bits.
  413. // (16 bytes = 16 * 8 = 128 bits)
  414. const SaltByteLength = 16
  415. // GetUserSalt returns a random user salt token.
  416. func GetUserSalt() (string, error) {
  417. rBytes, err := util.CryptoRandomBytes(SaltByteLength)
  418. if err != nil {
  419. return "", err
  420. }
  421. // Returns a 32 bytes long string.
  422. return hex.EncodeToString(rBytes), nil
  423. }
  424. // Note: The set of characters here can safely expand without a breaking change,
  425. // but characters removed from this set can cause user account linking to break
  426. var (
  427. customCharsReplacement = strings.NewReplacer("Æ", "AE")
  428. removeCharsRE = regexp.MustCompile(`['´\x60]`)
  429. removeDiacriticsTransform = transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC)
  430. replaceCharsHyphenRE = regexp.MustCompile(`[\s~+]`)
  431. )
  432. // normalizeUserName returns a string with single-quotes and diacritics
  433. // removed, and any other non-supported username characters replaced with
  434. // a `-` character
  435. func NormalizeUserName(s string) (string, error) {
  436. strDiacriticsRemoved, n, err := transform.String(removeDiacriticsTransform, customCharsReplacement.Replace(s))
  437. if err != nil {
  438. return "", fmt.Errorf("Failed to normalize character `%v` in provided username `%v`", s[n], s)
  439. }
  440. return replaceCharsHyphenRE.ReplaceAllLiteralString(removeCharsRE.ReplaceAllLiteralString(strDiacriticsRemoved, ""), "-"), nil
  441. }
  442. var (
  443. reservedUsernames = []string{
  444. ".",
  445. "..",
  446. ".well-known",
  447. "admin",
  448. "api",
  449. "assets",
  450. "attachments",
  451. "avatar",
  452. "avatars",
  453. "captcha",
  454. "commits",
  455. "debug",
  456. "error",
  457. "explore",
  458. "favicon.ico",
  459. "ghost",
  460. "issues",
  461. "login",
  462. "manifest.json",
  463. "metrics",
  464. "milestones",
  465. "new",
  466. "notifications",
  467. "org",
  468. "pulls",
  469. "raw",
  470. "repo",
  471. "repo-avatars",
  472. "robots.txt",
  473. "search",
  474. "serviceworker.js",
  475. "ssh_info",
  476. "swagger.v1.json",
  477. "user",
  478. "v2",
  479. "gitea-actions",
  480. }
  481. // DON'T ADD ANY NEW STUFF, WE SOLVE THIS WITH `/user/{obj}` PATHS!
  482. reservedUserPatterns = []string{"*.keys", "*.gpg", "*.rss", "*.atom", "*.png"}
  483. )
  484. // IsUsableUsername returns an error when a username is reserved
  485. func IsUsableUsername(name string) error {
  486. // Validate username make sure it satisfies requirement.
  487. if !validation.IsValidUsername(name) {
  488. // Note: usually this error is normally caught up earlier in the UI
  489. return db.ErrNameCharsNotAllowed{Name: name}
  490. }
  491. return db.IsUsableName(reservedUsernames, reservedUserPatterns, name)
  492. }
  493. // CreateUserOverwriteOptions are an optional options who overwrite system defaults on user creation
  494. type CreateUserOverwriteOptions struct {
  495. KeepEmailPrivate optional.Option[bool]
  496. Visibility *structs.VisibleType
  497. AllowCreateOrganization optional.Option[bool]
  498. EmailNotificationsPreference *string
  499. MaxRepoCreation *int
  500. Theme *string
  501. IsRestricted optional.Option[bool]
  502. IsActive optional.Option[bool]
  503. }
  504. // CreateUser creates record of a new user.
  505. func CreateUser(ctx context.Context, u *User, overwriteDefault ...*CreateUserOverwriteOptions) (err error) {
  506. return createUser(ctx, u, false, overwriteDefault...)
  507. }
  508. // AdminCreateUser is used by admins to manually create users
  509. func AdminCreateUser(ctx context.Context, u *User, overwriteDefault ...*CreateUserOverwriteOptions) (err error) {
  510. return createUser(ctx, u, true, overwriteDefault...)
  511. }
  512. // createUser creates record of a new user.
  513. func createUser(ctx context.Context, u *User, createdByAdmin bool, overwriteDefault ...*CreateUserOverwriteOptions) (err error) {
  514. if err = IsUsableUsername(u.Name); err != nil {
  515. return err
  516. }
  517. // set system defaults
  518. u.KeepEmailPrivate = setting.Service.DefaultKeepEmailPrivate
  519. u.Visibility = setting.Service.DefaultUserVisibilityMode
  520. u.AllowCreateOrganization = setting.Service.DefaultAllowCreateOrganization && !setting.Admin.DisableRegularOrgCreation
  521. u.EmailNotificationsPreference = setting.Admin.DefaultEmailNotification
  522. u.MaxRepoCreation = -1
  523. u.Theme = setting.UI.DefaultTheme
  524. u.IsRestricted = setting.Service.DefaultUserIsRestricted
  525. u.IsActive = !(setting.Service.RegisterEmailConfirm || setting.Service.RegisterManualConfirm)
  526. // Ensure consistency of the dates.
  527. if u.UpdatedUnix < u.CreatedUnix {
  528. u.UpdatedUnix = u.CreatedUnix
  529. }
  530. // overwrite defaults if set
  531. if len(overwriteDefault) != 0 && overwriteDefault[0] != nil {
  532. overwrite := overwriteDefault[0]
  533. if overwrite.KeepEmailPrivate.Has() {
  534. u.KeepEmailPrivate = overwrite.KeepEmailPrivate.Value()
  535. }
  536. if overwrite.Visibility != nil {
  537. u.Visibility = *overwrite.Visibility
  538. }
  539. if overwrite.AllowCreateOrganization.Has() {
  540. u.AllowCreateOrganization = overwrite.AllowCreateOrganization.Value()
  541. }
  542. if overwrite.EmailNotificationsPreference != nil {
  543. u.EmailNotificationsPreference = *overwrite.EmailNotificationsPreference
  544. }
  545. if overwrite.MaxRepoCreation != nil {
  546. u.MaxRepoCreation = *overwrite.MaxRepoCreation
  547. }
  548. if overwrite.Theme != nil {
  549. u.Theme = *overwrite.Theme
  550. }
  551. if overwrite.IsRestricted.Has() {
  552. u.IsRestricted = overwrite.IsRestricted.Value()
  553. }
  554. if overwrite.IsActive.Has() {
  555. u.IsActive = overwrite.IsActive.Value()
  556. }
  557. }
  558. // validate data
  559. if err := ValidateUser(u); err != nil {
  560. return err
  561. }
  562. if createdByAdmin {
  563. if err := ValidateEmailForAdmin(u.Email); err != nil {
  564. return err
  565. }
  566. } else {
  567. if err := ValidateEmail(u.Email); err != nil {
  568. return err
  569. }
  570. }
  571. ctx, committer, err := db.TxContext(ctx)
  572. if err != nil {
  573. return err
  574. }
  575. defer committer.Close()
  576. isExist, err := IsUserExist(ctx, 0, u.Name)
  577. if err != nil {
  578. return err
  579. } else if isExist {
  580. return ErrUserAlreadyExist{u.Name}
  581. }
  582. isExist, err = IsEmailUsed(ctx, u.Email)
  583. if err != nil {
  584. return err
  585. } else if isExist {
  586. return ErrEmailAlreadyUsed{
  587. Email: u.Email,
  588. }
  589. }
  590. // prepare for database
  591. u.LowerName = strings.ToLower(u.Name)
  592. u.AvatarEmail = u.Email
  593. if u.Rands, err = GetUserSalt(); err != nil {
  594. return err
  595. }
  596. if u.Passwd != "" {
  597. if err = u.SetPassword(u.Passwd); err != nil {
  598. return err
  599. }
  600. } else {
  601. u.Salt = ""
  602. u.PasswdHashAlgo = ""
  603. }
  604. // save changes to database
  605. if err = DeleteUserRedirect(ctx, u.Name); err != nil {
  606. return err
  607. }
  608. if u.CreatedUnix == 0 {
  609. // Caller expects auto-time for creation & update timestamps.
  610. err = db.Insert(ctx, u)
  611. } else {
  612. // Caller sets the timestamps themselves. They are responsible for ensuring
  613. // both `CreatedUnix` and `UpdatedUnix` are set appropriately.
  614. _, err = db.GetEngine(ctx).NoAutoTime().Insert(u)
  615. }
  616. if err != nil {
  617. return err
  618. }
  619. // insert email address
  620. if err := db.Insert(ctx, &EmailAddress{
  621. UID: u.ID,
  622. Email: u.Email,
  623. LowerEmail: strings.ToLower(u.Email),
  624. IsActivated: u.IsActive,
  625. IsPrimary: true,
  626. }); err != nil {
  627. return err
  628. }
  629. return committer.Commit()
  630. }
  631. // IsLastAdminUser check whether user is the last admin
  632. func IsLastAdminUser(ctx context.Context, user *User) bool {
  633. if user.IsAdmin && CountUsers(ctx, &CountUserFilter{IsAdmin: optional.Some(true)}) <= 1 {
  634. return true
  635. }
  636. return false
  637. }
  638. // CountUserFilter represent optional filters for CountUsers
  639. type CountUserFilter struct {
  640. LastLoginSince *int64
  641. IsAdmin optional.Option[bool]
  642. }
  643. // CountUsers returns number of users.
  644. func CountUsers(ctx context.Context, opts *CountUserFilter) int64 {
  645. return countUsers(ctx, opts)
  646. }
  647. func countUsers(ctx context.Context, opts *CountUserFilter) int64 {
  648. sess := db.GetEngine(ctx)
  649. cond := builder.NewCond()
  650. cond = cond.And(builder.Eq{"type": UserTypeIndividual})
  651. if opts != nil {
  652. if opts.LastLoginSince != nil {
  653. cond = cond.And(builder.Gte{"last_login_unix": *opts.LastLoginSince})
  654. }
  655. if opts.IsAdmin.Has() {
  656. cond = cond.And(builder.Eq{"is_admin": opts.IsAdmin.Value()})
  657. }
  658. }
  659. count, err := sess.Where(cond).Count(new(User))
  660. if err != nil {
  661. log.Error("user.countUsers: %v", err)
  662. }
  663. return count
  664. }
  665. // GetVerifyUser get user by verify code
  666. func GetVerifyUser(ctx context.Context, code string) (user *User) {
  667. if len(code) <= base.TimeLimitCodeLength {
  668. return nil
  669. }
  670. // use tail hex username query user
  671. hexStr := code[base.TimeLimitCodeLength:]
  672. if b, err := hex.DecodeString(hexStr); err == nil {
  673. if user, err = GetUserByName(ctx, string(b)); user != nil {
  674. return user
  675. }
  676. log.Error("user.getVerifyUser: %v", err)
  677. }
  678. return nil
  679. }
  680. // VerifyUserActiveCode verifies active code when active account
  681. func VerifyUserActiveCode(ctx context.Context, code string) (user *User) {
  682. minutes := setting.Service.ActiveCodeLives
  683. if user = GetVerifyUser(ctx, code); user != nil {
  684. // time limit code
  685. prefix := code[:base.TimeLimitCodeLength]
  686. data := fmt.Sprintf("%d%s%s%s%s", user.ID, user.Email, user.LowerName, user.Passwd, user.Rands)
  687. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  688. return user
  689. }
  690. }
  691. return nil
  692. }
  693. // ValidateUser check if user is valid to insert / update into database
  694. func ValidateUser(u *User, cols ...string) error {
  695. if len(cols) == 0 || util.SliceContainsString(cols, "visibility", true) {
  696. if !setting.Service.AllowedUserVisibilityModesSlice.IsAllowedVisibility(u.Visibility) && !u.IsOrganization() {
  697. return fmt.Errorf("visibility Mode not allowed: %s", u.Visibility.String())
  698. }
  699. }
  700. return nil
  701. }
  702. // UpdateUserCols update user according special columns
  703. func UpdateUserCols(ctx context.Context, u *User, cols ...string) error {
  704. if err := ValidateUser(u, cols...); err != nil {
  705. return err
  706. }
  707. _, err := db.GetEngine(ctx).ID(u.ID).Cols(cols...).Update(u)
  708. return err
  709. }
  710. // GetInactiveUsers gets all inactive users
  711. func GetInactiveUsers(ctx context.Context, olderThan time.Duration) ([]*User, error) {
  712. var cond builder.Cond = builder.Eq{"is_active": false}
  713. if olderThan > 0 {
  714. cond = cond.And(builder.Lt{"created_unix": time.Now().Add(-olderThan).Unix()})
  715. }
  716. users := make([]*User, 0, 10)
  717. return users, db.GetEngine(ctx).
  718. Where(cond).
  719. Find(&users)
  720. }
  721. // UserPath returns the path absolute path of user repositories.
  722. func UserPath(userName string) string { //revive:disable-line:exported
  723. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  724. }
  725. // GetUserByID returns the user object by given ID if exists.
  726. func GetUserByID(ctx context.Context, id int64) (*User, error) {
  727. u := new(User)
  728. has, err := db.GetEngine(ctx).ID(id).Get(u)
  729. if err != nil {
  730. return nil, err
  731. } else if !has {
  732. return nil, ErrUserNotExist{UID: id}
  733. }
  734. return u, nil
  735. }
  736. // GetUserByIDs returns the user objects by given IDs if exists.
  737. func GetUserByIDs(ctx context.Context, ids []int64) ([]*User, error) {
  738. users := make([]*User, 0, len(ids))
  739. err := db.GetEngine(ctx).In("id", ids).
  740. Table("user").
  741. Find(&users)
  742. return users, err
  743. }
  744. // GetPossibleUserByID returns the user if id > 0 or return system usrs if id < 0
  745. func GetPossibleUserByID(ctx context.Context, id int64) (*User, error) {
  746. switch id {
  747. case GhostUserID:
  748. return NewGhostUser(), nil
  749. case ActionsUserID:
  750. return NewActionsUser(), nil
  751. case 0:
  752. return nil, ErrUserNotExist{}
  753. default:
  754. return GetUserByID(ctx, id)
  755. }
  756. }
  757. // GetPossibleUserByIDs returns the users if id > 0 or return system users if id < 0
  758. func GetPossibleUserByIDs(ctx context.Context, ids []int64) ([]*User, error) {
  759. uniqueIDs := container.SetOf(ids...)
  760. users := make([]*User, 0, len(ids))
  761. _ = uniqueIDs.Remove(0)
  762. if uniqueIDs.Remove(GhostUserID) {
  763. users = append(users, NewGhostUser())
  764. }
  765. if uniqueIDs.Remove(ActionsUserID) {
  766. users = append(users, NewActionsUser())
  767. }
  768. res, err := GetUserByIDs(ctx, uniqueIDs.Values())
  769. if err != nil {
  770. return nil, err
  771. }
  772. users = append(users, res...)
  773. return users, nil
  774. }
  775. // GetUserByNameCtx returns user by given name.
  776. func GetUserByName(ctx context.Context, name string) (*User, error) {
  777. if len(name) == 0 {
  778. return nil, ErrUserNotExist{Name: name}
  779. }
  780. u := &User{LowerName: strings.ToLower(name), Type: UserTypeIndividual}
  781. has, err := db.GetEngine(ctx).Get(u)
  782. if err != nil {
  783. return nil, err
  784. } else if !has {
  785. return nil, ErrUserNotExist{Name: name}
  786. }
  787. return u, nil
  788. }
  789. // GetUserEmailsByNames returns a list of e-mails corresponds to names of users
  790. // that have their email notifications set to enabled or onmention.
  791. func GetUserEmailsByNames(ctx context.Context, names []string) []string {
  792. mails := make([]string, 0, len(names))
  793. for _, name := range names {
  794. u, err := GetUserByName(ctx, name)
  795. if err != nil {
  796. continue
  797. }
  798. if u.IsMailable() && u.EmailNotificationsPreference != EmailNotificationsDisabled {
  799. mails = append(mails, u.Email)
  800. }
  801. }
  802. return mails
  803. }
  804. // GetMaileableUsersByIDs gets users from ids, but only if they can receive mails
  805. func GetMaileableUsersByIDs(ctx context.Context, ids []int64, isMention bool) ([]*User, error) {
  806. if len(ids) == 0 {
  807. return nil, nil
  808. }
  809. ous := make([]*User, 0, len(ids))
  810. if isMention {
  811. return ous, db.GetEngine(ctx).
  812. In("id", ids).
  813. Where("`type` = ?", UserTypeIndividual).
  814. And("`prohibit_login` = ?", false).
  815. And("`is_active` = ?", true).
  816. In("`email_notifications_preference`", EmailNotificationsEnabled, EmailNotificationsOnMention, EmailNotificationsAndYourOwn).
  817. Find(&ous)
  818. }
  819. return ous, db.GetEngine(ctx).
  820. In("id", ids).
  821. Where("`type` = ?", UserTypeIndividual).
  822. And("`prohibit_login` = ?", false).
  823. And("`is_active` = ?", true).
  824. In("`email_notifications_preference`", EmailNotificationsEnabled, EmailNotificationsAndYourOwn).
  825. Find(&ous)
  826. }
  827. // GetUserNamesByIDs returns usernames for all resolved users from a list of Ids.
  828. func GetUserNamesByIDs(ctx context.Context, ids []int64) ([]string, error) {
  829. unames := make([]string, 0, len(ids))
  830. err := db.GetEngine(ctx).In("id", ids).
  831. Table("user").
  832. Asc("name").
  833. Cols("name").
  834. Find(&unames)
  835. return unames, err
  836. }
  837. // GetUserNameByID returns username for the id
  838. func GetUserNameByID(ctx context.Context, id int64) (string, error) {
  839. var name string
  840. has, err := db.GetEngine(ctx).Table("user").Where("id = ?", id).Cols("name").Get(&name)
  841. if err != nil {
  842. return "", err
  843. }
  844. if has {
  845. return name, nil
  846. }
  847. return "", nil
  848. }
  849. // GetUserIDsByNames returns a slice of ids corresponds to names.
  850. func GetUserIDsByNames(ctx context.Context, names []string, ignoreNonExistent bool) ([]int64, error) {
  851. ids := make([]int64, 0, len(names))
  852. for _, name := range names {
  853. u, err := GetUserByName(ctx, name)
  854. if err != nil {
  855. if ignoreNonExistent {
  856. continue
  857. } else {
  858. return nil, err
  859. }
  860. }
  861. ids = append(ids, u.ID)
  862. }
  863. return ids, nil
  864. }
  865. // GetUsersBySource returns a list of Users for a login source
  866. func GetUsersBySource(ctx context.Context, s *auth.Source) ([]*User, error) {
  867. var users []*User
  868. err := db.GetEngine(ctx).Where("login_type = ? AND login_source = ?", s.Type, s.ID).Find(&users)
  869. return users, err
  870. }
  871. // UserCommit represents a commit with validation of user.
  872. type UserCommit struct { //revive:disable-line:exported
  873. User *User
  874. *git.Commit
  875. }
  876. // ValidateCommitWithEmail check if author's e-mail of commit is corresponding to a user.
  877. func ValidateCommitWithEmail(ctx context.Context, c *git.Commit) *User {
  878. if c.Author == nil {
  879. return nil
  880. }
  881. u, err := GetUserByEmail(ctx, c.Author.Email)
  882. if err != nil {
  883. return nil
  884. }
  885. return u
  886. }
  887. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  888. func ValidateCommitsWithEmails(ctx context.Context, oldCommits []*git.Commit) []*UserCommit {
  889. var (
  890. emails = make(map[string]*User)
  891. newCommits = make([]*UserCommit, 0, len(oldCommits))
  892. )
  893. for _, c := range oldCommits {
  894. var u *User
  895. if c.Author != nil {
  896. if v, ok := emails[c.Author.Email]; !ok {
  897. u, _ = GetUserByEmail(ctx, c.Author.Email)
  898. emails[c.Author.Email] = u
  899. } else {
  900. u = v
  901. }
  902. }
  903. newCommits = append(newCommits, &UserCommit{
  904. User: u,
  905. Commit: c,
  906. })
  907. }
  908. return newCommits
  909. }
  910. // GetUserByEmail returns the user object by given e-mail if exists.
  911. func GetUserByEmail(ctx context.Context, email string) (*User, error) {
  912. if len(email) == 0 {
  913. return nil, ErrUserNotExist{Name: email}
  914. }
  915. email = strings.ToLower(email)
  916. // Otherwise, check in alternative list for activated email addresses
  917. emailAddress := &EmailAddress{LowerEmail: email, IsActivated: true}
  918. has, err := db.GetEngine(ctx).Get(emailAddress)
  919. if err != nil {
  920. return nil, err
  921. }
  922. if has {
  923. return GetUserByID(ctx, emailAddress.UID)
  924. }
  925. // Finally, if email address is the protected email address:
  926. if strings.HasSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress)) {
  927. username := strings.TrimSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress))
  928. user := &User{}
  929. has, err := db.GetEngine(ctx).Where("lower_name=?", username).Get(user)
  930. if err != nil {
  931. return nil, err
  932. }
  933. if has {
  934. return user, nil
  935. }
  936. }
  937. return nil, ErrUserNotExist{Name: email}
  938. }
  939. // GetUser checks if a user already exists
  940. func GetUser(ctx context.Context, user *User) (bool, error) {
  941. return db.GetEngine(ctx).Get(user)
  942. }
  943. // GetUserByOpenID returns the user object by given OpenID if exists.
  944. func GetUserByOpenID(ctx context.Context, uri string) (*User, error) {
  945. if len(uri) == 0 {
  946. return nil, ErrUserNotExist{Name: uri}
  947. }
  948. uri, err := openid.Normalize(uri)
  949. if err != nil {
  950. return nil, err
  951. }
  952. log.Trace("Normalized OpenID URI: " + uri)
  953. // Otherwise, check in openid table
  954. oid := &UserOpenID{}
  955. has, err := db.GetEngine(ctx).Where("uri=?", uri).Get(oid)
  956. if err != nil {
  957. return nil, err
  958. }
  959. if has {
  960. return GetUserByID(ctx, oid.UID)
  961. }
  962. return nil, ErrUserNotExist{Name: uri}
  963. }
  964. // GetAdminUser returns the first administrator
  965. func GetAdminUser(ctx context.Context) (*User, error) {
  966. var admin User
  967. has, err := db.GetEngine(ctx).
  968. Where("is_admin=?", true).
  969. Asc("id"). // Reliably get the admin with the lowest ID.
  970. Get(&admin)
  971. if err != nil {
  972. return nil, err
  973. } else if !has {
  974. return nil, ErrUserNotExist{}
  975. }
  976. return &admin, nil
  977. }
  978. func isUserVisibleToViewerCond(viewer *User) builder.Cond {
  979. if viewer != nil && viewer.IsAdmin {
  980. return builder.NewCond()
  981. }
  982. if viewer == nil || viewer.IsRestricted {
  983. return builder.Eq{
  984. "`user`.visibility": structs.VisibleTypePublic,
  985. }
  986. }
  987. return builder.Neq{
  988. "`user`.visibility": structs.VisibleTypePrivate,
  989. }.Or(
  990. // viewer self
  991. builder.Eq{"`user`.id": viewer.ID},
  992. // viewer's following
  993. builder.In("`user`.id",
  994. builder.
  995. Select("`follow`.user_id").
  996. From("follow").
  997. Where(builder.Eq{"`follow`.follow_id": viewer.ID})),
  998. // viewer's org user
  999. builder.In("`user`.id",
  1000. builder.
  1001. Select("`team_user`.uid").
  1002. From("team_user").
  1003. Join("INNER", "`team_user` AS t2", "`team_user`.org_id = `t2`.org_id").
  1004. Where(builder.Eq{"`t2`.uid": viewer.ID})),
  1005. // viewer's org
  1006. builder.In("`user`.id",
  1007. builder.
  1008. Select("`team_user`.org_id").
  1009. From("team_user").
  1010. Where(builder.Eq{"`team_user`.uid": viewer.ID})))
  1011. }
  1012. // IsUserVisibleToViewer check if viewer is able to see user profile
  1013. func IsUserVisibleToViewer(ctx context.Context, u, viewer *User) bool {
  1014. if viewer != nil && (viewer.IsAdmin || viewer.ID == u.ID) {
  1015. return true
  1016. }
  1017. switch u.Visibility {
  1018. case structs.VisibleTypePublic:
  1019. return true
  1020. case structs.VisibleTypeLimited:
  1021. if viewer == nil || viewer.IsRestricted {
  1022. return false
  1023. }
  1024. return true
  1025. case structs.VisibleTypePrivate:
  1026. if viewer == nil || viewer.IsRestricted {
  1027. return false
  1028. }
  1029. // If they follow - they see each other
  1030. follower := IsFollowing(ctx, u.ID, viewer.ID)
  1031. if follower {
  1032. return true
  1033. }
  1034. // Now we need to check if they in some organization together
  1035. count, err := db.GetEngine(ctx).Table("team_user").
  1036. Where(
  1037. builder.And(
  1038. builder.Eq{"uid": viewer.ID},
  1039. builder.Or(
  1040. builder.Eq{"org_id": u.ID},
  1041. builder.In("org_id",
  1042. builder.Select("org_id").
  1043. From("team_user", "t2").
  1044. Where(builder.Eq{"uid": u.ID}))))).
  1045. Count()
  1046. if err != nil {
  1047. return false
  1048. }
  1049. if count == 0 {
  1050. // No common organization
  1051. return false
  1052. }
  1053. // they are in an organization together
  1054. return true
  1055. }
  1056. return false
  1057. }
  1058. // CountWrongUserType count OrgUser who have wrong type
  1059. func CountWrongUserType(ctx context.Context) (int64, error) {
  1060. return db.GetEngine(ctx).Where(builder.Eq{"type": 0}.And(builder.Neq{"num_teams": 0})).Count(new(User))
  1061. }
  1062. // FixWrongUserType fix OrgUser who have wrong type
  1063. func FixWrongUserType(ctx context.Context) (int64, error) {
  1064. return db.GetEngine(ctx).Where(builder.Eq{"type": 0}.And(builder.Neq{"num_teams": 0})).Cols("type").NoAutoTime().Update(&User{Type: 1})
  1065. }
  1066. func GetOrderByName() string {
  1067. if setting.UI.DefaultShowFullName {
  1068. return "full_name, name"
  1069. }
  1070. return "name"
  1071. }