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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349
  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. // NewGhostUser creates and returns a fake user for someone has deleted their account.
  482. func NewGhostUser() *User {
  483. return &User{
  484. ID: -1,
  485. Name: "Ghost",
  486. LowerName: "ghost",
  487. }
  488. }
  489. // NewReplaceUser creates and returns a fake user for external user
  490. func NewReplaceUser(name string) *User {
  491. return &User{
  492. ID: -1,
  493. Name: name,
  494. LowerName: strings.ToLower(name),
  495. }
  496. }
  497. // IsGhost check if user is fake user for a deleted account
  498. func (u *User) IsGhost() bool {
  499. if u == nil {
  500. return false
  501. }
  502. return u.ID == -1 && u.Name == "Ghost"
  503. }
  504. var (
  505. reservedUsernames = []string{
  506. ".",
  507. "..",
  508. ".well-known",
  509. "admin",
  510. "api",
  511. "assets",
  512. "attachments",
  513. "avatar",
  514. "avatars",
  515. "captcha",
  516. "commits",
  517. "debug",
  518. "error",
  519. "explore",
  520. "favicon.ico",
  521. "ghost",
  522. "issues",
  523. "login",
  524. "manifest.json",
  525. "metrics",
  526. "milestones",
  527. "new",
  528. "notifications",
  529. "org",
  530. "pulls",
  531. "raw",
  532. "repo",
  533. "repo-avatars",
  534. "robots.txt",
  535. "search",
  536. "serviceworker.js",
  537. "ssh_info",
  538. "swagger.v1.json",
  539. "user",
  540. "v2",
  541. }
  542. reservedUserPatterns = []string{"*.keys", "*.gpg", "*.rss", "*.atom"}
  543. )
  544. // IsUsableUsername returns an error when a username is reserved
  545. func IsUsableUsername(name string) error {
  546. // Validate username make sure it satisfies requirement.
  547. if !validation.IsValidUsername(name) {
  548. // Note: usually this error is normally caught up earlier in the UI
  549. return db.ErrNameCharsNotAllowed{Name: name}
  550. }
  551. return db.IsUsableName(reservedUsernames, reservedUserPatterns, name)
  552. }
  553. // CreateUserOverwriteOptions are an optional options who overwrite system defaults on user creation
  554. type CreateUserOverwriteOptions struct {
  555. KeepEmailPrivate util.OptionalBool
  556. Visibility *structs.VisibleType
  557. AllowCreateOrganization util.OptionalBool
  558. EmailNotificationsPreference *string
  559. MaxRepoCreation *int
  560. Theme *string
  561. IsRestricted util.OptionalBool
  562. IsActive util.OptionalBool
  563. }
  564. // CreateUser creates record of a new user.
  565. func CreateUser(u *User, overwriteDefault ...*CreateUserOverwriteOptions) (err error) {
  566. if err = IsUsableUsername(u.Name); err != nil {
  567. return err
  568. }
  569. // set system defaults
  570. u.KeepEmailPrivate = setting.Service.DefaultKeepEmailPrivate
  571. u.Visibility = setting.Service.DefaultUserVisibilityMode
  572. u.AllowCreateOrganization = setting.Service.DefaultAllowCreateOrganization && !setting.Admin.DisableRegularOrgCreation
  573. u.EmailNotificationsPreference = setting.Admin.DefaultEmailNotification
  574. u.MaxRepoCreation = -1
  575. u.Theme = setting.UI.DefaultTheme
  576. u.IsRestricted = setting.Service.DefaultUserIsRestricted
  577. u.IsActive = !(setting.Service.RegisterEmailConfirm || setting.Service.RegisterManualConfirm)
  578. // overwrite defaults if set
  579. if len(overwriteDefault) != 0 && overwriteDefault[0] != nil {
  580. overwrite := overwriteDefault[0]
  581. if !overwrite.KeepEmailPrivate.IsNone() {
  582. u.KeepEmailPrivate = overwrite.KeepEmailPrivate.IsTrue()
  583. }
  584. if overwrite.Visibility != nil {
  585. u.Visibility = *overwrite.Visibility
  586. }
  587. if !overwrite.AllowCreateOrganization.IsNone() {
  588. u.AllowCreateOrganization = overwrite.AllowCreateOrganization.IsTrue()
  589. }
  590. if overwrite.EmailNotificationsPreference != nil {
  591. u.EmailNotificationsPreference = *overwrite.EmailNotificationsPreference
  592. }
  593. if overwrite.MaxRepoCreation != nil {
  594. u.MaxRepoCreation = *overwrite.MaxRepoCreation
  595. }
  596. if overwrite.Theme != nil {
  597. u.Theme = *overwrite.Theme
  598. }
  599. if !overwrite.IsRestricted.IsNone() {
  600. u.IsRestricted = overwrite.IsRestricted.IsTrue()
  601. }
  602. if !overwrite.IsActive.IsNone() {
  603. u.IsActive = overwrite.IsActive.IsTrue()
  604. }
  605. }
  606. // validate data
  607. if err := validateUser(u); err != nil {
  608. return err
  609. }
  610. if err := ValidateEmail(u.Email); err != nil {
  611. return err
  612. }
  613. ctx, committer, err := db.TxContext(db.DefaultContext)
  614. if err != nil {
  615. return err
  616. }
  617. defer committer.Close()
  618. isExist, err := IsUserExist(ctx, 0, u.Name)
  619. if err != nil {
  620. return err
  621. } else if isExist {
  622. return ErrUserAlreadyExist{u.Name}
  623. }
  624. isExist, err = IsEmailUsed(ctx, u.Email)
  625. if err != nil {
  626. return err
  627. } else if isExist {
  628. return ErrEmailAlreadyUsed{
  629. Email: u.Email,
  630. }
  631. }
  632. // prepare for database
  633. u.LowerName = strings.ToLower(u.Name)
  634. u.AvatarEmail = u.Email
  635. if u.Rands, err = GetUserSalt(); err != nil {
  636. return err
  637. }
  638. if err = u.SetPassword(u.Passwd); err != nil {
  639. return err
  640. }
  641. // save changes to database
  642. if err = DeleteUserRedirect(ctx, u.Name); err != nil {
  643. return err
  644. }
  645. if err = db.Insert(ctx, u); err != nil {
  646. return err
  647. }
  648. // insert email address
  649. if err := db.Insert(ctx, &EmailAddress{
  650. UID: u.ID,
  651. Email: u.Email,
  652. LowerEmail: strings.ToLower(u.Email),
  653. IsActivated: u.IsActive,
  654. IsPrimary: true,
  655. }); err != nil {
  656. return err
  657. }
  658. return committer.Commit()
  659. }
  660. // CountUserFilter represent optional filters for CountUsers
  661. type CountUserFilter struct {
  662. LastLoginSince *int64
  663. }
  664. // CountUsers returns number of users.
  665. func CountUsers(opts *CountUserFilter) int64 {
  666. return countUsers(db.DefaultContext, opts)
  667. }
  668. func countUsers(ctx context.Context, opts *CountUserFilter) int64 {
  669. sess := db.GetEngine(ctx).Where(builder.Eq{"type": "0"})
  670. if opts != nil && opts.LastLoginSince != nil {
  671. sess = sess.Where(builder.Gte{"last_login_unix": *opts.LastLoginSince})
  672. }
  673. count, _ := sess.Count(new(User))
  674. return count
  675. }
  676. // GetVerifyUser get user by verify code
  677. func GetVerifyUser(code string) (user *User) {
  678. if len(code) <= base.TimeLimitCodeLength {
  679. return nil
  680. }
  681. // use tail hex username query user
  682. hexStr := code[base.TimeLimitCodeLength:]
  683. if b, err := hex.DecodeString(hexStr); err == nil {
  684. if user, err = GetUserByName(db.DefaultContext, string(b)); user != nil {
  685. return user
  686. }
  687. log.Error("user.getVerifyUser: %v", err)
  688. }
  689. return nil
  690. }
  691. // VerifyUserActiveCode verifies active code when active account
  692. func VerifyUserActiveCode(code string) (user *User) {
  693. minutes := setting.Service.ActiveCodeLives
  694. if user = GetVerifyUser(code); user != nil {
  695. // time limit code
  696. prefix := code[:base.TimeLimitCodeLength]
  697. data := fmt.Sprintf("%d%s%s%s%s", user.ID, user.Email, user.LowerName, user.Passwd, user.Rands)
  698. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  699. return user
  700. }
  701. }
  702. return nil
  703. }
  704. // ChangeUserName changes all corresponding setting from old user name to new one.
  705. func ChangeUserName(u *User, newUserName string) (err error) {
  706. oldUserName := u.Name
  707. if err = IsUsableUsername(newUserName); err != nil {
  708. return err
  709. }
  710. ctx, committer, err := db.TxContext(db.DefaultContext)
  711. if err != nil {
  712. return err
  713. }
  714. defer committer.Close()
  715. isExist, err := IsUserExist(ctx, 0, newUserName)
  716. if err != nil {
  717. return err
  718. } else if isExist {
  719. return ErrUserAlreadyExist{newUserName}
  720. }
  721. if _, err = db.GetEngine(ctx).Exec("UPDATE `repository` SET owner_name=? WHERE owner_name=?", newUserName, oldUserName); err != nil {
  722. return fmt.Errorf("Change repo owner name: %w", err)
  723. }
  724. // Do not fail if directory does not exist
  725. if err = util.Rename(UserPath(oldUserName), UserPath(newUserName)); err != nil && !os.IsNotExist(err) {
  726. return fmt.Errorf("Rename user directory: %w", err)
  727. }
  728. if err = NewUserRedirect(ctx, u.ID, oldUserName, newUserName); err != nil {
  729. return err
  730. }
  731. if err = committer.Commit(); err != nil {
  732. if err2 := util.Rename(UserPath(newUserName), UserPath(oldUserName)); err2 != nil && !os.IsNotExist(err2) {
  733. 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)
  734. 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)
  735. }
  736. return err
  737. }
  738. return nil
  739. }
  740. // checkDupEmail checks whether there are the same email with the user
  741. func checkDupEmail(ctx context.Context, u *User) error {
  742. u.Email = strings.ToLower(u.Email)
  743. has, err := db.GetEngine(ctx).
  744. Where("id!=?", u.ID).
  745. And("type=?", u.Type).
  746. And("email=?", u.Email).
  747. Get(new(User))
  748. if err != nil {
  749. return err
  750. } else if has {
  751. return ErrEmailAlreadyUsed{
  752. Email: u.Email,
  753. }
  754. }
  755. return nil
  756. }
  757. // validateUser check if user is valid to insert / update into database
  758. func validateUser(u *User) error {
  759. if !setting.Service.AllowedUserVisibilityModesSlice.IsAllowedVisibility(u.Visibility) && !u.IsOrganization() {
  760. return fmt.Errorf("visibility Mode not allowed: %s", u.Visibility.String())
  761. }
  762. u.Email = strings.ToLower(u.Email)
  763. return ValidateEmail(u.Email)
  764. }
  765. // UpdateUser updates user's information.
  766. func UpdateUser(ctx context.Context, u *User, changePrimaryEmail bool, cols ...string) error {
  767. err := validateUser(u)
  768. if err != nil {
  769. return err
  770. }
  771. e := db.GetEngine(ctx)
  772. if changePrimaryEmail {
  773. var emailAddress EmailAddress
  774. has, err := e.Where("lower_email=?", strings.ToLower(u.Email)).Get(&emailAddress)
  775. if err != nil {
  776. return err
  777. }
  778. if has && emailAddress.UID != u.ID {
  779. return ErrEmailAlreadyUsed{
  780. Email: u.Email,
  781. }
  782. }
  783. // 1. Update old primary email
  784. if _, err = e.Where("uid=? AND is_primary=?", u.ID, true).Cols("is_primary").Update(&EmailAddress{
  785. IsPrimary: false,
  786. }); err != nil {
  787. return err
  788. }
  789. if !has {
  790. emailAddress.Email = u.Email
  791. emailAddress.UID = u.ID
  792. emailAddress.IsActivated = true
  793. emailAddress.IsPrimary = true
  794. if _, err := e.Insert(&emailAddress); err != nil {
  795. return err
  796. }
  797. } else if _, err := e.ID(emailAddress.ID).Cols("is_primary").Update(&EmailAddress{
  798. IsPrimary: true,
  799. }); err != nil {
  800. return err
  801. }
  802. } else if !u.IsOrganization() { // check if primary email in email_address table
  803. primaryEmailExist, err := e.Where("uid=? AND is_primary=?", u.ID, true).Exist(&EmailAddress{})
  804. if err != nil {
  805. return err
  806. }
  807. if !primaryEmailExist {
  808. if _, err := e.Insert(&EmailAddress{
  809. Email: u.Email,
  810. UID: u.ID,
  811. IsActivated: true,
  812. IsPrimary: true,
  813. }); err != nil {
  814. return err
  815. }
  816. }
  817. }
  818. if len(cols) == 0 {
  819. _, err = e.ID(u.ID).AllCols().Update(u)
  820. } else {
  821. _, err = e.ID(u.ID).Cols(cols...).Update(u)
  822. }
  823. return err
  824. }
  825. // UpdateUserCols update user according special columns
  826. func UpdateUserCols(ctx context.Context, u *User, cols ...string) error {
  827. if err := validateUser(u); err != nil {
  828. return err
  829. }
  830. _, err := db.GetEngine(ctx).ID(u.ID).Cols(cols...).Update(u)
  831. return err
  832. }
  833. // UpdateUserSetting updates user's settings.
  834. func UpdateUserSetting(u *User) (err error) {
  835. ctx, committer, err := db.TxContext(db.DefaultContext)
  836. if err != nil {
  837. return err
  838. }
  839. defer committer.Close()
  840. if !u.IsOrganization() {
  841. if err = checkDupEmail(ctx, u); err != nil {
  842. return err
  843. }
  844. }
  845. if err = UpdateUser(ctx, u, false); err != nil {
  846. return err
  847. }
  848. return committer.Commit()
  849. }
  850. // GetInactiveUsers gets all inactive users
  851. func GetInactiveUsers(ctx context.Context, olderThan time.Duration) ([]*User, error) {
  852. var cond builder.Cond = builder.Eq{"is_active": false}
  853. if olderThan > 0 {
  854. cond = cond.And(builder.Lt{"created_unix": time.Now().Add(-olderThan).Unix()})
  855. }
  856. users := make([]*User, 0, 10)
  857. return users, db.GetEngine(ctx).
  858. Where(cond).
  859. Find(&users)
  860. }
  861. // UserPath returns the path absolute path of user repositories.
  862. func UserPath(userName string) string { //revive:disable-line:exported
  863. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  864. }
  865. // GetUserByID returns the user object by given ID if exists.
  866. func GetUserByID(ctx context.Context, id int64) (*User, error) {
  867. u := new(User)
  868. has, err := db.GetEngine(ctx).ID(id).Get(u)
  869. if err != nil {
  870. return nil, err
  871. } else if !has {
  872. return nil, ErrUserNotExist{id, "", 0}
  873. }
  874. return u, nil
  875. }
  876. // GetUserByNameCtx returns user by given name.
  877. func GetUserByName(ctx context.Context, name string) (*User, error) {
  878. if len(name) == 0 {
  879. return nil, ErrUserNotExist{0, name, 0}
  880. }
  881. u := &User{LowerName: strings.ToLower(name)}
  882. has, err := db.GetEngine(ctx).Get(u)
  883. if err != nil {
  884. return nil, err
  885. } else if !has {
  886. return nil, ErrUserNotExist{0, name, 0}
  887. }
  888. return u, nil
  889. }
  890. // GetUserEmailsByNames returns a list of e-mails corresponds to names of users
  891. // that have their email notifications set to enabled or onmention.
  892. func GetUserEmailsByNames(ctx context.Context, names []string) []string {
  893. mails := make([]string, 0, len(names))
  894. for _, name := range names {
  895. u, err := GetUserByName(ctx, name)
  896. if err != nil {
  897. continue
  898. }
  899. if u.IsMailable() && u.EmailNotifications() != EmailNotificationsDisabled {
  900. mails = append(mails, u.Email)
  901. }
  902. }
  903. return mails
  904. }
  905. // GetMaileableUsersByIDs gets users from ids, but only if they can receive mails
  906. func GetMaileableUsersByIDs(ctx context.Context, ids []int64, isMention bool) ([]*User, error) {
  907. if len(ids) == 0 {
  908. return nil, nil
  909. }
  910. ous := make([]*User, 0, len(ids))
  911. if isMention {
  912. return ous, db.GetEngine(ctx).
  913. In("id", ids).
  914. Where("`type` = ?", UserTypeIndividual).
  915. And("`prohibit_login` = ?", false).
  916. And("`is_active` = ?", true).
  917. In("`email_notifications_preference`", EmailNotificationsEnabled, EmailNotificationsOnMention, EmailNotificationsAndYourOwn).
  918. Find(&ous)
  919. }
  920. return ous, db.GetEngine(ctx).
  921. In("id", ids).
  922. Where("`type` = ?", UserTypeIndividual).
  923. And("`prohibit_login` = ?", false).
  924. And("`is_active` = ?", true).
  925. In("`email_notifications_preference`", EmailNotificationsEnabled, EmailNotificationsAndYourOwn).
  926. Find(&ous)
  927. }
  928. // GetUserNamesByIDs returns usernames for all resolved users from a list of Ids.
  929. func GetUserNamesByIDs(ids []int64) ([]string, error) {
  930. unames := make([]string, 0, len(ids))
  931. err := db.GetEngine(db.DefaultContext).In("id", ids).
  932. Table("user").
  933. Asc("name").
  934. Cols("name").
  935. Find(&unames)
  936. return unames, err
  937. }
  938. // GetUserNameByID returns username for the id
  939. func GetUserNameByID(ctx context.Context, id int64) (string, error) {
  940. var name string
  941. has, err := db.GetEngine(ctx).Table("user").Where("id = ?", id).Cols("name").Get(&name)
  942. if err != nil {
  943. return "", err
  944. }
  945. if has {
  946. return name, nil
  947. }
  948. return "", nil
  949. }
  950. // GetUserIDsByNames returns a slice of ids corresponds to names.
  951. func GetUserIDsByNames(ctx context.Context, names []string, ignoreNonExistent bool) ([]int64, error) {
  952. ids := make([]int64, 0, len(names))
  953. for _, name := range names {
  954. u, err := GetUserByName(ctx, name)
  955. if err != nil {
  956. if ignoreNonExistent {
  957. continue
  958. } else {
  959. return nil, err
  960. }
  961. }
  962. ids = append(ids, u.ID)
  963. }
  964. return ids, nil
  965. }
  966. // GetUsersBySource returns a list of Users for a login source
  967. func GetUsersBySource(s *auth.Source) ([]*User, error) {
  968. var users []*User
  969. err := db.GetEngine(db.DefaultContext).Where("login_type = ? AND login_source = ?", s.Type, s.ID).Find(&users)
  970. return users, err
  971. }
  972. // UserCommit represents a commit with validation of user.
  973. type UserCommit struct { //revive:disable-line:exported
  974. User *User
  975. *git.Commit
  976. }
  977. // ValidateCommitWithEmail check if author's e-mail of commit is corresponding to a user.
  978. func ValidateCommitWithEmail(c *git.Commit) *User {
  979. if c.Author == nil {
  980. return nil
  981. }
  982. u, err := GetUserByEmail(c.Author.Email)
  983. if err != nil {
  984. return nil
  985. }
  986. return u
  987. }
  988. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  989. func ValidateCommitsWithEmails(oldCommits []*git.Commit) []*UserCommit {
  990. var (
  991. emails = make(map[string]*User)
  992. newCommits = make([]*UserCommit, 0, len(oldCommits))
  993. )
  994. for _, c := range oldCommits {
  995. var u *User
  996. if c.Author != nil {
  997. if v, ok := emails[c.Author.Email]; !ok {
  998. u, _ = GetUserByEmail(c.Author.Email)
  999. emails[c.Author.Email] = u
  1000. } else {
  1001. u = v
  1002. }
  1003. }
  1004. newCommits = append(newCommits, &UserCommit{
  1005. User: u,
  1006. Commit: c,
  1007. })
  1008. }
  1009. return newCommits
  1010. }
  1011. // GetUserByEmail returns the user object by given e-mail if exists.
  1012. func GetUserByEmail(email string) (*User, error) {
  1013. return GetUserByEmailContext(db.DefaultContext, email)
  1014. }
  1015. // GetUserByEmailContext returns the user object by given e-mail if exists with db context
  1016. func GetUserByEmailContext(ctx context.Context, email string) (*User, error) {
  1017. if len(email) == 0 {
  1018. return nil, ErrUserNotExist{0, email, 0}
  1019. }
  1020. email = strings.ToLower(email)
  1021. // Otherwise, check in alternative list for activated email addresses
  1022. emailAddress := &EmailAddress{LowerEmail: email, IsActivated: true}
  1023. has, err := db.GetEngine(ctx).Get(emailAddress)
  1024. if err != nil {
  1025. return nil, err
  1026. }
  1027. if has {
  1028. return GetUserByID(ctx, emailAddress.UID)
  1029. }
  1030. // Finally, if email address is the protected email address:
  1031. if strings.HasSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress)) {
  1032. username := strings.TrimSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress))
  1033. user := &User{}
  1034. has, err := db.GetEngine(ctx).Where("lower_name=?", username).Get(user)
  1035. if err != nil {
  1036. return nil, err
  1037. }
  1038. if has {
  1039. return user, nil
  1040. }
  1041. }
  1042. return nil, ErrUserNotExist{0, email, 0}
  1043. }
  1044. // GetUser checks if a user already exists
  1045. func GetUser(user *User) (bool, error) {
  1046. return db.GetEngine(db.DefaultContext).Get(user)
  1047. }
  1048. // GetUserByOpenID returns the user object by given OpenID if exists.
  1049. func GetUserByOpenID(uri string) (*User, error) {
  1050. if len(uri) == 0 {
  1051. return nil, ErrUserNotExist{0, uri, 0}
  1052. }
  1053. uri, err := openid.Normalize(uri)
  1054. if err != nil {
  1055. return nil, err
  1056. }
  1057. log.Trace("Normalized OpenID URI: " + uri)
  1058. // Otherwise, check in openid table
  1059. oid := &UserOpenID{}
  1060. has, err := db.GetEngine(db.DefaultContext).Where("uri=?", uri).Get(oid)
  1061. if err != nil {
  1062. return nil, err
  1063. }
  1064. if has {
  1065. return GetUserByID(db.DefaultContext, oid.UID)
  1066. }
  1067. return nil, ErrUserNotExist{0, uri, 0}
  1068. }
  1069. // GetAdminUser returns the first administrator
  1070. func GetAdminUser() (*User, error) {
  1071. var admin User
  1072. has, err := db.GetEngine(db.DefaultContext).
  1073. Where("is_admin=?", true).
  1074. Asc("id"). // Reliably get the admin with the lowest ID.
  1075. Get(&admin)
  1076. if err != nil {
  1077. return nil, err
  1078. } else if !has {
  1079. return nil, ErrUserNotExist{}
  1080. }
  1081. return &admin, nil
  1082. }
  1083. func isUserVisibleToViewerCond(viewer *User) builder.Cond {
  1084. if viewer != nil && viewer.IsAdmin {
  1085. return builder.NewCond()
  1086. }
  1087. if viewer == nil || viewer.IsRestricted {
  1088. return builder.Eq{
  1089. "`user`.visibility": structs.VisibleTypePublic,
  1090. }
  1091. }
  1092. return builder.Neq{
  1093. "`user`.visibility": structs.VisibleTypePrivate,
  1094. }.Or(
  1095. builder.In("`user`.id",
  1096. builder.
  1097. Select("`follow`.user_id").
  1098. From("follow").
  1099. Where(builder.Eq{"`follow`.follow_id": viewer.ID})),
  1100. builder.In("`user`.id",
  1101. builder.
  1102. Select("`team_user`.uid").
  1103. From("team_user").
  1104. Join("INNER", "`team_user` AS t2", "`team_user`.id = `t2`.id").
  1105. Where(builder.Eq{"`t2`.uid": viewer.ID})),
  1106. builder.In("`user`.id",
  1107. builder.
  1108. Select("`team_user`.uid").
  1109. From("team_user").
  1110. Join("INNER", "`team_user` AS t2", "`team_user`.org_id = `t2`.org_id").
  1111. Where(builder.Eq{"`t2`.uid": viewer.ID})))
  1112. }
  1113. // IsUserVisibleToViewer check if viewer is able to see user profile
  1114. func IsUserVisibleToViewer(ctx context.Context, u, viewer *User) bool {
  1115. if viewer != nil && (viewer.IsAdmin || viewer.ID == u.ID) {
  1116. return true
  1117. }
  1118. switch u.Visibility {
  1119. case structs.VisibleTypePublic:
  1120. return true
  1121. case structs.VisibleTypeLimited:
  1122. if viewer == nil || viewer.IsRestricted {
  1123. return false
  1124. }
  1125. return true
  1126. case structs.VisibleTypePrivate:
  1127. if viewer == nil || viewer.IsRestricted {
  1128. return false
  1129. }
  1130. // If they follow - they see each over
  1131. follower := IsFollowing(u.ID, viewer.ID)
  1132. if follower {
  1133. return true
  1134. }
  1135. // Now we need to check if they in some organization together
  1136. count, err := db.GetEngine(ctx).Table("team_user").
  1137. Where(
  1138. builder.And(
  1139. builder.Eq{"uid": viewer.ID},
  1140. builder.Or(
  1141. builder.Eq{"org_id": u.ID},
  1142. builder.In("org_id",
  1143. builder.Select("org_id").
  1144. From("team_user", "t2").
  1145. Where(builder.Eq{"uid": u.ID}))))).
  1146. Count()
  1147. if err != nil {
  1148. return false
  1149. }
  1150. if count == 0 {
  1151. // No common organization
  1152. return false
  1153. }
  1154. // they are in an organization together
  1155. return true
  1156. }
  1157. return false
  1158. }
  1159. // CountWrongUserType count OrgUser who have wrong type
  1160. func CountWrongUserType() (int64, error) {
  1161. return db.GetEngine(db.DefaultContext).Where(builder.Eq{"type": 0}.And(builder.Neq{"num_teams": 0})).Count(new(User))
  1162. }
  1163. // FixWrongUserType fix OrgUser who have wrong type
  1164. func FixWrongUserType() (int64, error) {
  1165. return db.GetEngine(db.DefaultContext).Where(builder.Eq{"type": 0}.And(builder.Neq{"num_teams": 0})).Cols("type").NoAutoTime().Update(&User{Type: 1})
  1166. }
  1167. func GetOrderByName() string {
  1168. if setting.UI.DefaultShowFullName {
  1169. return "full_name, name"
  1170. }
  1171. return "name"
  1172. }