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

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