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

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