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 36KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251
  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("['`´]")
  429. transformDiacritics = transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC)
  430. replaceCharsHyphenRE = regexp.MustCompile(`[\s~+]`)
  431. )
  432. // NormalizeUserName only takes the name part if it is an email address, transforms it diacritics to ASCII characters.
  433. // It returns a string with the single-quotes removed, and any other non-supported username characters are replaced with a `-` character
  434. func NormalizeUserName(s string) (string, error) {
  435. s, _, _ = strings.Cut(s, "@")
  436. strDiacriticsRemoved, n, err := transform.String(transformDiacritics, customCharsReplacement.Replace(s))
  437. if err != nil {
  438. return "", fmt.Errorf("failed to normalize the string of provided username %q at position %d", s, n)
  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. }
  858. return nil, err
  859. }
  860. ids = append(ids, u.ID)
  861. }
  862. return ids, nil
  863. }
  864. // GetUsersBySource returns a list of Users for a login source
  865. func GetUsersBySource(ctx context.Context, s *auth.Source) ([]*User, error) {
  866. var users []*User
  867. err := db.GetEngine(ctx).Where("login_type = ? AND login_source = ?", s.Type, s.ID).Find(&users)
  868. return users, err
  869. }
  870. // UserCommit represents a commit with validation of user.
  871. type UserCommit struct { //revive:disable-line:exported
  872. User *User
  873. *git.Commit
  874. }
  875. // ValidateCommitWithEmail check if author's e-mail of commit is corresponding to a user.
  876. func ValidateCommitWithEmail(ctx context.Context, c *git.Commit) *User {
  877. if c.Author == nil {
  878. return nil
  879. }
  880. u, err := GetUserByEmail(ctx, c.Author.Email)
  881. if err != nil {
  882. return nil
  883. }
  884. return u
  885. }
  886. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  887. func ValidateCommitsWithEmails(ctx context.Context, oldCommits []*git.Commit) []*UserCommit {
  888. var (
  889. emails = make(map[string]*User)
  890. newCommits = make([]*UserCommit, 0, len(oldCommits))
  891. )
  892. for _, c := range oldCommits {
  893. var u *User
  894. if c.Author != nil {
  895. if v, ok := emails[c.Author.Email]; !ok {
  896. u, _ = GetUserByEmail(ctx, c.Author.Email)
  897. emails[c.Author.Email] = u
  898. } else {
  899. u = v
  900. }
  901. }
  902. newCommits = append(newCommits, &UserCommit{
  903. User: u,
  904. Commit: c,
  905. })
  906. }
  907. return newCommits
  908. }
  909. // GetUserByEmail returns the user object by given e-mail if exists.
  910. func GetUserByEmail(ctx context.Context, email string) (*User, error) {
  911. if len(email) == 0 {
  912. return nil, ErrUserNotExist{Name: email}
  913. }
  914. email = strings.ToLower(email)
  915. // Otherwise, check in alternative list for activated email addresses
  916. emailAddress := &EmailAddress{LowerEmail: email, IsActivated: true}
  917. has, err := db.GetEngine(ctx).Get(emailAddress)
  918. if err != nil {
  919. return nil, err
  920. }
  921. if has {
  922. return GetUserByID(ctx, emailAddress.UID)
  923. }
  924. // Finally, if email address is the protected email address:
  925. if strings.HasSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress)) {
  926. username := strings.TrimSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress))
  927. user := &User{}
  928. has, err := db.GetEngine(ctx).Where("lower_name=?", username).Get(user)
  929. if err != nil {
  930. return nil, err
  931. }
  932. if has {
  933. return user, nil
  934. }
  935. }
  936. return nil, ErrUserNotExist{Name: email}
  937. }
  938. // GetUser checks if a user already exists
  939. func GetUser(ctx context.Context, user *User) (bool, error) {
  940. return db.GetEngine(ctx).Get(user)
  941. }
  942. // GetUserByOpenID returns the user object by given OpenID if exists.
  943. func GetUserByOpenID(ctx context.Context, uri string) (*User, error) {
  944. if len(uri) == 0 {
  945. return nil, ErrUserNotExist{Name: uri}
  946. }
  947. uri, err := openid.Normalize(uri)
  948. if err != nil {
  949. return nil, err
  950. }
  951. log.Trace("Normalized OpenID URI: " + uri)
  952. // Otherwise, check in openid table
  953. oid := &UserOpenID{}
  954. has, err := db.GetEngine(ctx).Where("uri=?", uri).Get(oid)
  955. if err != nil {
  956. return nil, err
  957. }
  958. if has {
  959. return GetUserByID(ctx, oid.UID)
  960. }
  961. return nil, ErrUserNotExist{Name: uri}
  962. }
  963. // GetAdminUser returns the first administrator
  964. func GetAdminUser(ctx context.Context) (*User, error) {
  965. var admin User
  966. has, err := db.GetEngine(ctx).
  967. Where("is_admin=?", true).
  968. Asc("id"). // Reliably get the admin with the lowest ID.
  969. Get(&admin)
  970. if err != nil {
  971. return nil, err
  972. } else if !has {
  973. return nil, ErrUserNotExist{}
  974. }
  975. return &admin, nil
  976. }
  977. func isUserVisibleToViewerCond(viewer *User) builder.Cond {
  978. if viewer != nil && viewer.IsAdmin {
  979. return builder.NewCond()
  980. }
  981. if viewer == nil || viewer.IsRestricted {
  982. return builder.Eq{
  983. "`user`.visibility": structs.VisibleTypePublic,
  984. }
  985. }
  986. return builder.Neq{
  987. "`user`.visibility": structs.VisibleTypePrivate,
  988. }.Or(
  989. // viewer self
  990. builder.Eq{"`user`.id": viewer.ID},
  991. // viewer's following
  992. builder.In("`user`.id",
  993. builder.
  994. Select("`follow`.user_id").
  995. From("follow").
  996. Where(builder.Eq{"`follow`.follow_id": viewer.ID})),
  997. // viewer's org user
  998. builder.In("`user`.id",
  999. builder.
  1000. Select("`team_user`.uid").
  1001. From("team_user").
  1002. Join("INNER", "`team_user` AS t2", "`team_user`.org_id = `t2`.org_id").
  1003. Where(builder.Eq{"`t2`.uid": viewer.ID})),
  1004. // viewer's org
  1005. builder.In("`user`.id",
  1006. builder.
  1007. Select("`team_user`.org_id").
  1008. From("team_user").
  1009. Where(builder.Eq{"`team_user`.uid": viewer.ID})))
  1010. }
  1011. // IsUserVisibleToViewer check if viewer is able to see user profile
  1012. func IsUserVisibleToViewer(ctx context.Context, u, viewer *User) bool {
  1013. if viewer != nil && (viewer.IsAdmin || viewer.ID == u.ID) {
  1014. return true
  1015. }
  1016. switch u.Visibility {
  1017. case structs.VisibleTypePublic:
  1018. return true
  1019. case structs.VisibleTypeLimited:
  1020. if viewer == nil || viewer.IsRestricted {
  1021. return false
  1022. }
  1023. return true
  1024. case structs.VisibleTypePrivate:
  1025. if viewer == nil || viewer.IsRestricted {
  1026. return false
  1027. }
  1028. // If they follow - they see each other
  1029. follower := IsFollowing(ctx, u.ID, viewer.ID)
  1030. if follower {
  1031. return true
  1032. }
  1033. // Now we need to check if they in some organization together
  1034. count, err := db.GetEngine(ctx).Table("team_user").
  1035. Where(
  1036. builder.And(
  1037. builder.Eq{"uid": viewer.ID},
  1038. builder.Or(
  1039. builder.Eq{"org_id": u.ID},
  1040. builder.In("org_id",
  1041. builder.Select("org_id").
  1042. From("team_user", "t2").
  1043. Where(builder.Eq{"uid": u.ID}))))).
  1044. Count()
  1045. if err != nil {
  1046. return false
  1047. }
  1048. if count == 0 {
  1049. // No common organization
  1050. return false
  1051. }
  1052. // they are in an organization together
  1053. return true
  1054. }
  1055. return false
  1056. }
  1057. // CountWrongUserType count OrgUser who have wrong type
  1058. func CountWrongUserType(ctx context.Context) (int64, error) {
  1059. return db.GetEngine(ctx).Where(builder.Eq{"type": 0}.And(builder.Neq{"num_teams": 0})).Count(new(User))
  1060. }
  1061. // FixWrongUserType fix OrgUser who have wrong type
  1062. func FixWrongUserType(ctx context.Context) (int64, error) {
  1063. return db.GetEngine(ctx).Where(builder.Eq{"type": 0}.And(builder.Neq{"num_teams": 0})).Cols("type").NoAutoTime().Update(&User{Type: 1})
  1064. }
  1065. func GetOrderByName() string {
  1066. if setting.UI.DefaultShowFullName {
  1067. return "full_name, name"
  1068. }
  1069. return "name"
  1070. }
  1071. // IsFeatureDisabledWithLoginType checks if a user feature is disabled, taking into account the login type of the
  1072. // user if applicable
  1073. func IsFeatureDisabledWithLoginType(user *User, feature string) bool {
  1074. // NOTE: in the long run it may be better to check the ExternalLoginUser table rather than user.LoginType
  1075. return (user != nil && user.LoginType > auth.Plain && setting.Admin.ExternalUserDisableFeatures.Contains(feature)) ||
  1076. setting.Admin.UserDisabledFeatures.Contains(feature)
  1077. }
  1078. // DisabledFeaturesWithLoginType returns the set of user features disabled, taking into account the login type
  1079. // of the user if applicable
  1080. func DisabledFeaturesWithLoginType(user *User) *container.Set[string] {
  1081. // NOTE: in the long run it may be better to check the ExternalLoginUser table rather than user.LoginType
  1082. if user != nil && user.LoginType > auth.Plain {
  1083. return &setting.Admin.ExternalUserDisableFeatures
  1084. }
  1085. return &setting.Admin.UserDisabledFeatures
  1086. }