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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "container/list"
  8. "context"
  9. "crypto/sha256"
  10. "crypto/subtle"
  11. "encoding/hex"
  12. "errors"
  13. "fmt"
  14. _ "image/jpeg" // Needed for jpeg support
  15. "os"
  16. "path/filepath"
  17. "regexp"
  18. "strings"
  19. "time"
  20. "unicode/utf8"
  21. "code.gitea.io/gitea/modules/base"
  22. "code.gitea.io/gitea/modules/generate"
  23. "code.gitea.io/gitea/modules/git"
  24. "code.gitea.io/gitea/modules/log"
  25. "code.gitea.io/gitea/modules/public"
  26. "code.gitea.io/gitea/modules/setting"
  27. "code.gitea.io/gitea/modules/storage"
  28. "code.gitea.io/gitea/modules/structs"
  29. "code.gitea.io/gitea/modules/timeutil"
  30. "code.gitea.io/gitea/modules/util"
  31. "github.com/unknwon/com"
  32. "golang.org/x/crypto/argon2"
  33. "golang.org/x/crypto/bcrypt"
  34. "golang.org/x/crypto/pbkdf2"
  35. "golang.org/x/crypto/scrypt"
  36. "golang.org/x/crypto/ssh"
  37. "xorm.io/builder"
  38. "xorm.io/xorm"
  39. )
  40. // UserType defines the user type
  41. type UserType int
  42. const (
  43. // UserTypeIndividual defines an individual user
  44. UserTypeIndividual UserType = iota // Historic reason to make it starts at 0.
  45. // UserTypeOrganization defines an organization
  46. UserTypeOrganization
  47. )
  48. const (
  49. algoBcrypt = "bcrypt"
  50. algoScrypt = "scrypt"
  51. algoArgon2 = "argon2"
  52. algoPbkdf2 = "pbkdf2"
  53. // EmailNotificationsEnabled indicates that the user would like to receive all email notifications
  54. EmailNotificationsEnabled = "enabled"
  55. // EmailNotificationsOnMention indicates that the user would like to be notified via email when mentioned.
  56. EmailNotificationsOnMention = "onmention"
  57. // EmailNotificationsDisabled indicates that the user would not like to be notified via email.
  58. EmailNotificationsDisabled = "disabled"
  59. )
  60. var (
  61. // ErrUserNotKeyOwner user does not own this key error
  62. ErrUserNotKeyOwner = errors.New("User does not own this public key")
  63. // ErrEmailNotExist e-mail does not exist error
  64. ErrEmailNotExist = errors.New("E-mail does not exist")
  65. // ErrEmailNotActivated e-mail address has not been activated error
  66. ErrEmailNotActivated = errors.New("E-mail address has not been activated")
  67. // ErrUserNameIllegal user name contains illegal characters error
  68. ErrUserNameIllegal = errors.New("User name contains illegal characters")
  69. // ErrLoginSourceNotActived login source is not actived error
  70. ErrLoginSourceNotActived = errors.New("Login source is not actived")
  71. // ErrUnsupportedLoginType login source is unknown error
  72. ErrUnsupportedLoginType = errors.New("Login source is unknown")
  73. // Characters prohibited in a user name (anything except A-Za-z0-9_.-)
  74. alphaDashDotPattern = regexp.MustCompile(`[^\w-\.]`)
  75. )
  76. // User represents the object of individual and member of organization.
  77. type User struct {
  78. ID int64 `xorm:"pk autoincr"`
  79. LowerName string `xorm:"UNIQUE NOT NULL"`
  80. Name string `xorm:"UNIQUE NOT NULL"`
  81. FullName string
  82. // Email is the primary email address (to be used for communication)
  83. Email string `xorm:"NOT NULL"`
  84. KeepEmailPrivate bool
  85. EmailNotificationsPreference string `xorm:"VARCHAR(20) NOT NULL DEFAULT 'enabled'"`
  86. Passwd string `xorm:"NOT NULL"`
  87. PasswdHashAlgo string `xorm:"NOT NULL DEFAULT 'argon2'"`
  88. // MustChangePassword is an attribute that determines if a user
  89. // is to change his/her password after registration.
  90. MustChangePassword bool `xorm:"NOT NULL DEFAULT false"`
  91. LoginType LoginType
  92. LoginSource int64 `xorm:"NOT NULL DEFAULT 0"`
  93. LoginName string
  94. Type UserType
  95. OwnedOrgs []*User `xorm:"-"`
  96. Orgs []*User `xorm:"-"`
  97. Repos []*Repository `xorm:"-"`
  98. Location string
  99. Website string
  100. Rands string `xorm:"VARCHAR(10)"`
  101. Salt string `xorm:"VARCHAR(10)"`
  102. Language string `xorm:"VARCHAR(5)"`
  103. Description string
  104. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  105. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  106. LastLoginUnix timeutil.TimeStamp `xorm:"INDEX"`
  107. // Remember visibility choice for convenience, true for private
  108. LastRepoVisibility bool
  109. // Maximum repository creation limit, -1 means use global default
  110. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1"`
  111. // Permissions
  112. IsActive bool `xorm:"INDEX"` // Activate primary email
  113. IsAdmin bool
  114. IsRestricted bool `xorm:"NOT NULL DEFAULT false"`
  115. AllowGitHook bool
  116. AllowImportLocal bool // Allow migrate repository by local path
  117. AllowCreateOrganization bool `xorm:"DEFAULT true"`
  118. ProhibitLogin bool `xorm:"NOT NULL DEFAULT false"`
  119. // Avatar
  120. Avatar string `xorm:"VARCHAR(2048) NOT NULL"`
  121. AvatarEmail string `xorm:"NOT NULL"`
  122. UseCustomAvatar bool
  123. // Counters
  124. NumFollowers int
  125. NumFollowing int `xorm:"NOT NULL DEFAULT 0"`
  126. NumStars int
  127. NumRepos int
  128. // For organization
  129. NumTeams int
  130. NumMembers int
  131. Teams []*Team `xorm:"-"`
  132. Members UserList `xorm:"-"`
  133. MembersIsPublic map[int64]bool `xorm:"-"`
  134. Visibility structs.VisibleType `xorm:"NOT NULL DEFAULT 0"`
  135. RepoAdminChangeTeamAccess bool `xorm:"NOT NULL DEFAULT false"`
  136. // Preferences
  137. DiffViewStyle string `xorm:"NOT NULL DEFAULT ''"`
  138. Theme string `xorm:"NOT NULL DEFAULT ''"`
  139. KeepActivityPrivate bool `xorm:"NOT NULL DEFAULT false"`
  140. }
  141. // SearchOrganizationsOptions options to filter organizations
  142. type SearchOrganizationsOptions struct {
  143. ListOptions
  144. All bool
  145. }
  146. // ColorFormat writes a colored string to identify this struct
  147. func (u *User) ColorFormat(s fmt.State) {
  148. log.ColorFprintf(s, "%d:%s",
  149. log.NewColoredIDValue(u.ID),
  150. log.NewColoredValue(u.Name))
  151. }
  152. // BeforeUpdate is invoked from XORM before updating this object.
  153. func (u *User) BeforeUpdate() {
  154. if u.MaxRepoCreation < -1 {
  155. u.MaxRepoCreation = -1
  156. }
  157. // Organization does not need email
  158. u.Email = strings.ToLower(u.Email)
  159. if !u.IsOrganization() {
  160. if len(u.AvatarEmail) == 0 {
  161. u.AvatarEmail = u.Email
  162. }
  163. }
  164. u.LowerName = strings.ToLower(u.Name)
  165. u.Location = base.TruncateString(u.Location, 255)
  166. u.Website = base.TruncateString(u.Website, 255)
  167. u.Description = base.TruncateString(u.Description, 255)
  168. }
  169. // AfterLoad is invoked from XORM after filling all the fields of this object.
  170. func (u *User) AfterLoad() {
  171. if u.Theme == "" {
  172. u.Theme = setting.UI.DefaultTheme
  173. }
  174. }
  175. // SetLastLogin set time to last login
  176. func (u *User) SetLastLogin() {
  177. u.LastLoginUnix = timeutil.TimeStampNow()
  178. }
  179. // UpdateDiffViewStyle updates the users diff view style
  180. func (u *User) UpdateDiffViewStyle(style string) error {
  181. u.DiffViewStyle = style
  182. return UpdateUserCols(u, "diff_view_style")
  183. }
  184. // UpdateTheme updates a users' theme irrespective of the site wide theme
  185. func (u *User) UpdateTheme(themeName string) error {
  186. u.Theme = themeName
  187. return UpdateUserCols(u, "theme")
  188. }
  189. // GetEmail returns an noreply email, if the user has set to keep his
  190. // email address private, otherwise the primary email address.
  191. func (u *User) GetEmail() string {
  192. if u.KeepEmailPrivate {
  193. return fmt.Sprintf("%s@%s", u.LowerName, setting.Service.NoReplyAddress)
  194. }
  195. return u.Email
  196. }
  197. // GetAllUsers returns a slice of all users found in DB.
  198. func GetAllUsers() ([]*User, error) {
  199. users := make([]*User, 0)
  200. return users, x.OrderBy("id").Find(&users)
  201. }
  202. // IsLocal returns true if user login type is LoginPlain.
  203. func (u *User) IsLocal() bool {
  204. return u.LoginType <= LoginPlain
  205. }
  206. // IsOAuth2 returns true if user login type is LoginOAuth2.
  207. func (u *User) IsOAuth2() bool {
  208. return u.LoginType == LoginOAuth2
  209. }
  210. // HasForkedRepo checks if user has already forked a repository with given ID.
  211. func (u *User) HasForkedRepo(repoID int64) bool {
  212. _, has := HasForkedRepo(u.ID, repoID)
  213. return has
  214. }
  215. // MaxCreationLimit returns the number of repositories a user is allowed to create
  216. func (u *User) MaxCreationLimit() int {
  217. if u.MaxRepoCreation <= -1 {
  218. return setting.Repository.MaxCreationLimit
  219. }
  220. return u.MaxRepoCreation
  221. }
  222. // CanCreateRepo returns if user login can create a repository
  223. // NOTE: functions calling this assume a failure due to repository count limit; if new checks are added, those functions should be revised
  224. func (u *User) CanCreateRepo() bool {
  225. if u.IsAdmin {
  226. return true
  227. }
  228. if u.MaxRepoCreation <= -1 {
  229. if setting.Repository.MaxCreationLimit <= -1 {
  230. return true
  231. }
  232. return u.NumRepos < setting.Repository.MaxCreationLimit
  233. }
  234. return u.NumRepos < u.MaxRepoCreation
  235. }
  236. // CanCreateOrganization returns true if user can create organisation.
  237. func (u *User) CanCreateOrganization() bool {
  238. return u.IsAdmin || (u.AllowCreateOrganization && !setting.Admin.DisableRegularOrgCreation)
  239. }
  240. // CanEditGitHook returns true if user can edit Git hooks.
  241. func (u *User) CanEditGitHook() bool {
  242. return !setting.DisableGitHooks && (u.IsAdmin || u.AllowGitHook)
  243. }
  244. // CanImportLocal returns true if user can migrate repository by local path.
  245. func (u *User) CanImportLocal() bool {
  246. if !setting.ImportLocalPaths {
  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 setting.AppSubURL + "/org/" + u.Name + "/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 + "/" + u.Name
  261. }
  262. // HTMLURL returns the user or organization's full link.
  263. func (u *User) HTMLURL() string {
  264. return setting.AppURL + u.Name
  265. }
  266. // GenerateEmailActivateCode generates an activate code based on user information and given e-mail.
  267. func (u *User) GenerateEmailActivateCode(email string) string {
  268. code := base.CreateTimeLimitCode(
  269. com.ToStr(u.ID)+email+u.LowerName+u.Passwd+u.Rands,
  270. setting.Service.ActiveCodeLives, nil)
  271. // Add tail hex username
  272. code += hex.EncodeToString([]byte(u.LowerName))
  273. return code
  274. }
  275. // GenerateActivateCode generates an activate code based on user information.
  276. func (u *User) GenerateActivateCode() string {
  277. return u.GenerateEmailActivateCode(u.Email)
  278. }
  279. // GetFollowers returns range of user's followers.
  280. func (u *User) GetFollowers(listOptions ListOptions) ([]*User, error) {
  281. sess := x.
  282. Where("follow.follow_id=?", u.ID).
  283. Join("LEFT", "follow", "`user`.id=follow.user_id")
  284. if listOptions.Page != 0 {
  285. sess = listOptions.setSessionPagination(sess)
  286. users := make([]*User, 0, listOptions.PageSize)
  287. return users, sess.Find(&users)
  288. }
  289. users := make([]*User, 0, 8)
  290. return users, sess.Find(&users)
  291. }
  292. // IsFollowing returns true if user is following followID.
  293. func (u *User) IsFollowing(followID int64) bool {
  294. return IsFollowing(u.ID, followID)
  295. }
  296. // GetFollowing returns range of user's following.
  297. func (u *User) GetFollowing(listOptions ListOptions) ([]*User, error) {
  298. sess := x.
  299. Where("follow.user_id=?", u.ID).
  300. Join("LEFT", "follow", "`user`.id=follow.follow_id")
  301. if listOptions.Page != 0 {
  302. sess = listOptions.setSessionPagination(sess)
  303. users := make([]*User, 0, listOptions.PageSize)
  304. return users, sess.Find(&users)
  305. }
  306. users := make([]*User, 0, 8)
  307. return users, sess.Find(&users)
  308. }
  309. // NewGitSig generates and returns the signature of given user.
  310. func (u *User) NewGitSig() *git.Signature {
  311. return &git.Signature{
  312. Name: u.GitName(),
  313. Email: u.GetEmail(),
  314. When: time.Now(),
  315. }
  316. }
  317. func hashPassword(passwd, salt, algo string) string {
  318. var tempPasswd []byte
  319. switch algo {
  320. case algoBcrypt:
  321. tempPasswd, _ = bcrypt.GenerateFromPassword([]byte(passwd), bcrypt.DefaultCost)
  322. return string(tempPasswd)
  323. case algoScrypt:
  324. tempPasswd, _ = scrypt.Key([]byte(passwd), []byte(salt), 65536, 16, 2, 50)
  325. case algoArgon2:
  326. tempPasswd = argon2.IDKey([]byte(passwd), []byte(salt), 2, 65536, 8, 50)
  327. case algoPbkdf2:
  328. fallthrough
  329. default:
  330. tempPasswd = pbkdf2.Key([]byte(passwd), []byte(salt), 10000, 50, sha256.New)
  331. }
  332. return fmt.Sprintf("%x", tempPasswd)
  333. }
  334. // HashPassword hashes a password using the algorithm defined in the config value of PASSWORD_HASH_ALGO.
  335. func (u *User) HashPassword(passwd string) {
  336. u.PasswdHashAlgo = setting.PasswordHashAlgo
  337. u.Passwd = hashPassword(passwd, u.Salt, setting.PasswordHashAlgo)
  338. }
  339. // ValidatePassword checks if given password matches the one belongs to the user.
  340. func (u *User) ValidatePassword(passwd string) bool {
  341. tempHash := hashPassword(passwd, u.Salt, u.PasswdHashAlgo)
  342. if u.PasswdHashAlgo != algoBcrypt && subtle.ConstantTimeCompare([]byte(u.Passwd), []byte(tempHash)) == 1 {
  343. return true
  344. }
  345. if u.PasswdHashAlgo == algoBcrypt && bcrypt.CompareHashAndPassword([]byte(u.Passwd), []byte(passwd)) == nil {
  346. return true
  347. }
  348. return false
  349. }
  350. // IsPasswordSet checks if the password is set or left empty
  351. func (u *User) IsPasswordSet() bool {
  352. return !u.ValidatePassword("")
  353. }
  354. // IsOrganization returns true if user is actually a organization.
  355. func (u *User) IsOrganization() bool {
  356. return u.Type == UserTypeOrganization
  357. }
  358. // IsUserOrgOwner returns true if user is in the owner team of given organization.
  359. func (u *User) IsUserOrgOwner(orgID int64) bool {
  360. isOwner, err := IsOrganizationOwner(orgID, u.ID)
  361. if err != nil {
  362. log.Error("IsOrganizationOwner: %v", err)
  363. return false
  364. }
  365. return isOwner
  366. }
  367. // HasMemberWithUserID returns true if user with userID is part of the u organisation.
  368. func (u *User) HasMemberWithUserID(userID int64) bool {
  369. return u.hasMemberWithUserID(x, userID)
  370. }
  371. func (u *User) hasMemberWithUserID(e Engine, userID int64) bool {
  372. isMember, err := isOrganizationMember(e, u.ID, userID)
  373. if err != nil {
  374. log.Error("IsOrganizationMember: %v", err)
  375. return false
  376. }
  377. return isMember
  378. }
  379. // IsPublicMember returns true if user public his/her membership in given organization.
  380. func (u *User) IsPublicMember(orgID int64) bool {
  381. isMember, err := IsPublicMembership(orgID, u.ID)
  382. if err != nil {
  383. log.Error("IsPublicMembership: %v", err)
  384. return false
  385. }
  386. return isMember
  387. }
  388. func (u *User) getOrganizationCount(e Engine) (int64, error) {
  389. return e.
  390. Where("uid=?", u.ID).
  391. Count(new(OrgUser))
  392. }
  393. // GetOrganizationCount returns count of membership of organization of user.
  394. func (u *User) GetOrganizationCount() (int64, error) {
  395. return u.getOrganizationCount(x)
  396. }
  397. // GetRepositories returns repositories that user owns, including private repositories.
  398. func (u *User) GetRepositories(listOpts ListOptions, names ...string) (err error) {
  399. u.Repos, _, err = GetUserRepositories(&SearchRepoOptions{Actor: u, Private: true, ListOptions: listOpts, LowerNames: names})
  400. return err
  401. }
  402. // GetRepositoryIDs returns repositories IDs where user owned and has unittypes
  403. // Caller shall check that units is not globally disabled
  404. func (u *User) GetRepositoryIDs(units ...UnitType) ([]int64, error) {
  405. var ids []int64
  406. sess := x.Table("repository").Cols("repository.id")
  407. if len(units) > 0 {
  408. sess = sess.Join("INNER", "repo_unit", "repository.id = repo_unit.repo_id")
  409. sess = sess.In("repo_unit.type", units)
  410. }
  411. return ids, sess.Where("owner_id = ?", u.ID).Find(&ids)
  412. }
  413. // GetOrgRepositoryIDs returns repositories IDs where user's team owned and has unittypes
  414. // Caller shall check that units is not globally disabled
  415. func (u *User) GetOrgRepositoryIDs(units ...UnitType) ([]int64, error) {
  416. var ids []int64
  417. if err := x.Table("repository").
  418. Cols("repository.id").
  419. Join("INNER", "team_user", "repository.owner_id = team_user.org_id").
  420. Join("INNER", "team_repo", "(? != ? and repository.is_private != ?) OR (team_user.team_id = team_repo.team_id AND repository.id = team_repo.repo_id)", true, u.IsRestricted, true).
  421. Where("team_user.uid = ?", u.ID).
  422. GroupBy("repository.id").Find(&ids); err != nil {
  423. return nil, err
  424. }
  425. if len(units) > 0 {
  426. return FilterOutRepoIdsWithoutUnitAccess(u, ids, units...)
  427. }
  428. return ids, nil
  429. }
  430. // GetAccessRepoIDs returns all repositories IDs where user's or user is a team member organizations
  431. // Caller shall check that units is not globally disabled
  432. func (u *User) GetAccessRepoIDs(units ...UnitType) ([]int64, error) {
  433. ids, err := u.GetRepositoryIDs(units...)
  434. if err != nil {
  435. return nil, err
  436. }
  437. ids2, err := u.GetOrgRepositoryIDs(units...)
  438. if err != nil {
  439. return nil, err
  440. }
  441. return append(ids, ids2...), nil
  442. }
  443. // GetMirrorRepositories returns mirror repositories that user owns, including private repositories.
  444. func (u *User) GetMirrorRepositories() ([]*Repository, error) {
  445. return GetUserMirrorRepositories(u.ID)
  446. }
  447. // GetOwnedOrganizations returns all organizations that user owns.
  448. func (u *User) GetOwnedOrganizations() (err error) {
  449. u.OwnedOrgs, err = GetOwnedOrgsByUserID(u.ID)
  450. return err
  451. }
  452. // GetOrganizations returns paginated organizations that user belongs to.
  453. func (u *User) GetOrganizations(opts *SearchOrganizationsOptions) error {
  454. sess := x.NewSession()
  455. defer sess.Close()
  456. schema, err := x.TableInfo(new(User))
  457. if err != nil {
  458. return err
  459. }
  460. groupByCols := &strings.Builder{}
  461. for _, col := range schema.Columns() {
  462. fmt.Fprintf(groupByCols, "`%s`.%s,", schema.Name, col.Name)
  463. }
  464. groupByStr := groupByCols.String()
  465. groupByStr = groupByStr[0 : len(groupByStr)-1]
  466. sess.Select("`user`.*, count(repo_id) as org_count").
  467. Table("user").
  468. Join("INNER", "org_user", "`org_user`.org_id=`user`.id").
  469. Join("LEFT", builder.
  470. Select("id as repo_id, owner_id as repo_owner_id").
  471. From("repository").
  472. Where(accessibleRepositoryCondition(u)), "`repository`.repo_owner_id = `org_user`.org_id").
  473. And("`org_user`.uid=?", u.ID).
  474. GroupBy(groupByStr)
  475. if opts.PageSize != 0 {
  476. sess = opts.setSessionPagination(sess)
  477. }
  478. type OrgCount struct {
  479. User `xorm:"extends"`
  480. OrgCount int
  481. }
  482. orgCounts := make([]*OrgCount, 0, 10)
  483. if err := sess.
  484. Asc("`user`.name").
  485. Find(&orgCounts); err != nil {
  486. return err
  487. }
  488. orgs := make([]*User, len(orgCounts))
  489. for i, orgCount := range orgCounts {
  490. orgCount.User.NumRepos = orgCount.OrgCount
  491. orgs[i] = &orgCount.User
  492. }
  493. u.Orgs = orgs
  494. return nil
  495. }
  496. // DisplayName returns full name if it's not empty,
  497. // returns username otherwise.
  498. func (u *User) DisplayName() string {
  499. trimmed := strings.TrimSpace(u.FullName)
  500. if len(trimmed) > 0 {
  501. return trimmed
  502. }
  503. return u.Name
  504. }
  505. // GetDisplayName returns full name if it's not empty and DEFAULT_SHOW_FULL_NAME is set,
  506. // returns username otherwise.
  507. func (u *User) GetDisplayName() string {
  508. if setting.UI.DefaultShowFullName {
  509. trimmed := strings.TrimSpace(u.FullName)
  510. if len(trimmed) > 0 {
  511. return trimmed
  512. }
  513. }
  514. return u.Name
  515. }
  516. func gitSafeName(name string) string {
  517. return strings.TrimSpace(strings.NewReplacer("\n", "", "<", "", ">", "").Replace(name))
  518. }
  519. // GitName returns a git safe name
  520. func (u *User) GitName() string {
  521. gitName := gitSafeName(u.FullName)
  522. if len(gitName) > 0 {
  523. return gitName
  524. }
  525. // Although u.Name should be safe if created in our system
  526. // LDAP users may have bad names
  527. gitName = gitSafeName(u.Name)
  528. if len(gitName) > 0 {
  529. return gitName
  530. }
  531. // Totally pathological name so it's got to be:
  532. return fmt.Sprintf("user-%d", u.ID)
  533. }
  534. // ShortName ellipses username to length
  535. func (u *User) ShortName(length int) string {
  536. return base.EllipsisString(u.Name, length)
  537. }
  538. // IsMailable checks if a user is eligible
  539. // to receive emails.
  540. func (u *User) IsMailable() bool {
  541. return u.IsActive
  542. }
  543. // EmailNotifications returns the User's email notification preference
  544. func (u *User) EmailNotifications() string {
  545. return u.EmailNotificationsPreference
  546. }
  547. // SetEmailNotifications sets the user's email notification preference
  548. func (u *User) SetEmailNotifications(set string) error {
  549. u.EmailNotificationsPreference = set
  550. if err := UpdateUserCols(u, "email_notifications_preference"); err != nil {
  551. log.Error("SetEmailNotifications: %v", err)
  552. return err
  553. }
  554. return nil
  555. }
  556. func isUserExist(e Engine, uid int64, name string) (bool, error) {
  557. if len(name) == 0 {
  558. return false, nil
  559. }
  560. return e.
  561. Where("id!=?", uid).
  562. Get(&User{LowerName: strings.ToLower(name)})
  563. }
  564. // IsUserExist checks if given user name exist,
  565. // the user name should be noncased unique.
  566. // If uid is presented, then check will rule out that one,
  567. // it is used when update a user name in settings page.
  568. func IsUserExist(uid int64, name string) (bool, error) {
  569. return isUserExist(x, uid, name)
  570. }
  571. // GetUserSalt returns a random user salt token.
  572. func GetUserSalt() (string, error) {
  573. return generate.GetRandomString(10)
  574. }
  575. // NewGhostUser creates and returns a fake user for someone has deleted his/her account.
  576. func NewGhostUser() *User {
  577. return &User{
  578. ID: -1,
  579. Name: "Ghost",
  580. LowerName: "ghost",
  581. }
  582. }
  583. // NewReplaceUser creates and returns a fake user for external user
  584. func NewReplaceUser(name string) *User {
  585. return &User{
  586. ID: -1,
  587. Name: name,
  588. LowerName: strings.ToLower(name),
  589. }
  590. }
  591. // IsGhost check if user is fake user for a deleted account
  592. func (u *User) IsGhost() bool {
  593. if u == nil {
  594. return false
  595. }
  596. return u.ID == -1 && u.Name == "Ghost"
  597. }
  598. var (
  599. reservedUsernames = append([]string{
  600. ".",
  601. "..",
  602. ".well-known",
  603. "admin",
  604. "api",
  605. "assets",
  606. "attachments",
  607. "avatars",
  608. "commits",
  609. "debug",
  610. "error",
  611. "explore",
  612. "ghost",
  613. "help",
  614. "install",
  615. "issues",
  616. "less",
  617. "login",
  618. "manifest.json",
  619. "metrics",
  620. "milestones",
  621. "new",
  622. "notifications",
  623. "org",
  624. "plugins",
  625. "pulls",
  626. "raw",
  627. "repo",
  628. "robots.txt",
  629. "search",
  630. "stars",
  631. "template",
  632. "user",
  633. }, public.KnownPublicEntries...)
  634. reservedUserPatterns = []string{"*.keys", "*.gpg"}
  635. )
  636. // isUsableName checks if name is reserved or pattern of name is not allowed
  637. // based on given reserved names and patterns.
  638. // Names are exact match, patterns can be prefix or suffix match with placeholder '*'.
  639. func isUsableName(names, patterns []string, name string) error {
  640. name = strings.TrimSpace(strings.ToLower(name))
  641. if utf8.RuneCountInString(name) == 0 {
  642. return ErrNameEmpty
  643. }
  644. for i := range names {
  645. if name == names[i] {
  646. return ErrNameReserved{name}
  647. }
  648. }
  649. for _, pat := range patterns {
  650. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  651. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  652. return ErrNamePatternNotAllowed{pat}
  653. }
  654. }
  655. return nil
  656. }
  657. // IsUsableUsername returns an error when a username is reserved
  658. func IsUsableUsername(name string) error {
  659. // Validate username make sure it satisfies requirement.
  660. if alphaDashDotPattern.MatchString(name) {
  661. // Note: usually this error is normally caught up earlier in the UI
  662. return ErrNameCharsNotAllowed{Name: name}
  663. }
  664. return isUsableName(reservedUsernames, reservedUserPatterns, name)
  665. }
  666. // CreateUser creates record of a new user.
  667. func CreateUser(u *User) (err error) {
  668. if err = IsUsableUsername(u.Name); err != nil {
  669. return err
  670. }
  671. sess := x.NewSession()
  672. defer sess.Close()
  673. if err = sess.Begin(); err != nil {
  674. return err
  675. }
  676. isExist, err := isUserExist(sess, 0, u.Name)
  677. if err != nil {
  678. return err
  679. } else if isExist {
  680. return ErrUserAlreadyExist{u.Name}
  681. }
  682. u.Email = strings.ToLower(u.Email)
  683. isExist, err = sess.
  684. Where("email=?", u.Email).
  685. Get(new(User))
  686. if err != nil {
  687. return err
  688. } else if isExist {
  689. return ErrEmailAlreadyUsed{u.Email}
  690. }
  691. isExist, err = isEmailUsed(sess, u.Email)
  692. if err != nil {
  693. return err
  694. } else if isExist {
  695. return ErrEmailAlreadyUsed{u.Email}
  696. }
  697. u.KeepEmailPrivate = setting.Service.DefaultKeepEmailPrivate
  698. u.LowerName = strings.ToLower(u.Name)
  699. u.AvatarEmail = u.Email
  700. if u.Rands, err = GetUserSalt(); err != nil {
  701. return err
  702. }
  703. if u.Salt, err = GetUserSalt(); err != nil {
  704. return err
  705. }
  706. u.HashPassword(u.Passwd)
  707. u.AllowCreateOrganization = setting.Service.DefaultAllowCreateOrganization && !setting.Admin.DisableRegularOrgCreation
  708. u.EmailNotificationsPreference = setting.Admin.DefaultEmailNotification
  709. u.MaxRepoCreation = -1
  710. u.Theme = setting.UI.DefaultTheme
  711. if _, err = sess.Insert(u); err != nil {
  712. return err
  713. }
  714. return sess.Commit()
  715. }
  716. func countUsers(e Engine) int64 {
  717. count, _ := e.
  718. Where("type=0").
  719. Count(new(User))
  720. return count
  721. }
  722. // CountUsers returns number of users.
  723. func CountUsers() int64 {
  724. return countUsers(x)
  725. }
  726. // get user by verify code
  727. func getVerifyUser(code string) (user *User) {
  728. if len(code) <= base.TimeLimitCodeLength {
  729. return nil
  730. }
  731. // use tail hex username query user
  732. hexStr := code[base.TimeLimitCodeLength:]
  733. if b, err := hex.DecodeString(hexStr); err == nil {
  734. if user, err = GetUserByName(string(b)); user != nil {
  735. return user
  736. }
  737. log.Error("user.getVerifyUser: %v", err)
  738. }
  739. return nil
  740. }
  741. // VerifyUserActiveCode verifies active code when active account
  742. func VerifyUserActiveCode(code string) (user *User) {
  743. minutes := setting.Service.ActiveCodeLives
  744. if user = getVerifyUser(code); user != nil {
  745. // time limit code
  746. prefix := code[:base.TimeLimitCodeLength]
  747. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands
  748. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  749. return user
  750. }
  751. }
  752. return nil
  753. }
  754. // VerifyActiveEmailCode verifies active email code when active account
  755. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  756. minutes := setting.Service.ActiveCodeLives
  757. if user := getVerifyUser(code); user != nil {
  758. // time limit code
  759. prefix := code[:base.TimeLimitCodeLength]
  760. data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands
  761. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  762. emailAddress := &EmailAddress{UID: user.ID, Email: email}
  763. if has, _ := x.Get(emailAddress); has {
  764. return emailAddress
  765. }
  766. }
  767. }
  768. return nil
  769. }
  770. // ChangeUserName changes all corresponding setting from old user name to new one.
  771. func ChangeUserName(u *User, newUserName string) (err error) {
  772. if err = IsUsableUsername(newUserName); err != nil {
  773. return err
  774. }
  775. isExist, err := IsUserExist(0, newUserName)
  776. if err != nil {
  777. return err
  778. } else if isExist {
  779. return ErrUserAlreadyExist{newUserName}
  780. }
  781. sess := x.NewSession()
  782. defer sess.Close()
  783. if err = sess.Begin(); err != nil {
  784. return err
  785. }
  786. if _, err = sess.Exec("UPDATE `repository` SET owner_name=? WHERE owner_name=?", newUserName, u.Name); err != nil {
  787. return fmt.Errorf("Change repo owner name: %v", err)
  788. }
  789. // Do not fail if directory does not exist
  790. if err = os.Rename(UserPath(u.Name), UserPath(newUserName)); err != nil && !os.IsNotExist(err) {
  791. return fmt.Errorf("Rename user directory: %v", err)
  792. }
  793. return sess.Commit()
  794. }
  795. // checkDupEmail checks whether there are the same email with the user
  796. func checkDupEmail(e Engine, u *User) error {
  797. u.Email = strings.ToLower(u.Email)
  798. has, err := e.
  799. Where("id!=?", u.ID).
  800. And("type=?", u.Type).
  801. And("email=?", u.Email).
  802. Get(new(User))
  803. if err != nil {
  804. return err
  805. } else if has {
  806. return ErrEmailAlreadyUsed{u.Email}
  807. }
  808. return nil
  809. }
  810. func updateUser(e Engine, u *User) error {
  811. _, err := e.ID(u.ID).AllCols().Update(u)
  812. return err
  813. }
  814. // UpdateUser updates user's information.
  815. func UpdateUser(u *User) error {
  816. return updateUser(x, u)
  817. }
  818. // UpdateUserCols update user according special columns
  819. func UpdateUserCols(u *User, cols ...string) error {
  820. return updateUserCols(x, u, cols...)
  821. }
  822. func updateUserCols(e Engine, u *User, cols ...string) error {
  823. _, err := e.ID(u.ID).Cols(cols...).Update(u)
  824. return err
  825. }
  826. // UpdateUserSetting updates user's settings.
  827. func UpdateUserSetting(u *User) error {
  828. if !u.IsOrganization() {
  829. if err := checkDupEmail(x, u); err != nil {
  830. return err
  831. }
  832. }
  833. return updateUser(x, u)
  834. }
  835. // deleteBeans deletes all given beans, beans should contain delete conditions.
  836. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  837. for i := range beans {
  838. if _, err = e.Delete(beans[i]); err != nil {
  839. return err
  840. }
  841. }
  842. return nil
  843. }
  844. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  845. func deleteUser(e *xorm.Session, u *User) error {
  846. // Note: A user owns any repository or belongs to any organization
  847. // cannot perform delete operation.
  848. // Check ownership of repository.
  849. count, err := getRepositoryCount(e, u)
  850. if err != nil {
  851. return fmt.Errorf("GetRepositoryCount: %v", err)
  852. } else if count > 0 {
  853. return ErrUserOwnRepos{UID: u.ID}
  854. }
  855. // Check membership of organization.
  856. count, err = u.getOrganizationCount(e)
  857. if err != nil {
  858. return fmt.Errorf("GetOrganizationCount: %v", err)
  859. } else if count > 0 {
  860. return ErrUserHasOrgs{UID: u.ID}
  861. }
  862. // ***** START: Watch *****
  863. watchedRepoIDs := make([]int64, 0, 10)
  864. if err = e.Table("watch").Cols("watch.repo_id").
  865. Where("watch.user_id = ?", u.ID).And("watch.mode <>?", RepoWatchModeDont).Find(&watchedRepoIDs); err != nil {
  866. return fmt.Errorf("get all watches: %v", err)
  867. }
  868. if _, err = e.Decr("num_watches").In("id", watchedRepoIDs).NoAutoTime().Update(new(Repository)); err != nil {
  869. return fmt.Errorf("decrease repository num_watches: %v", err)
  870. }
  871. // ***** END: Watch *****
  872. // ***** START: Star *****
  873. starredRepoIDs := make([]int64, 0, 10)
  874. if err = e.Table("star").Cols("star.repo_id").
  875. Where("star.uid = ?", u.ID).Find(&starredRepoIDs); err != nil {
  876. return fmt.Errorf("get all stars: %v", err)
  877. } else if _, err = e.Decr("num_stars").In("id", starredRepoIDs).NoAutoTime().Update(new(Repository)); err != nil {
  878. return fmt.Errorf("decrease repository num_stars: %v", err)
  879. }
  880. // ***** END: Star *****
  881. // ***** START: Follow *****
  882. followeeIDs := make([]int64, 0, 10)
  883. if err = e.Table("follow").Cols("follow.follow_id").
  884. Where("follow.user_id = ?", u.ID).Find(&followeeIDs); err != nil {
  885. return fmt.Errorf("get all followees: %v", err)
  886. } else if _, err = e.Decr("num_followers").In("id", followeeIDs).Update(new(User)); err != nil {
  887. return fmt.Errorf("decrease user num_followers: %v", err)
  888. }
  889. followerIDs := make([]int64, 0, 10)
  890. if err = e.Table("follow").Cols("follow.user_id").
  891. Where("follow.follow_id = ?", u.ID).Find(&followerIDs); err != nil {
  892. return fmt.Errorf("get all followers: %v", err)
  893. } else if _, err = e.Decr("num_following").In("id", followerIDs).Update(new(User)); err != nil {
  894. return fmt.Errorf("decrease user num_following: %v", err)
  895. }
  896. // ***** END: Follow *****
  897. if err = deleteBeans(e,
  898. &AccessToken{UID: u.ID},
  899. &Collaboration{UserID: u.ID},
  900. &Access{UserID: u.ID},
  901. &Watch{UserID: u.ID},
  902. &Star{UID: u.ID},
  903. &Follow{UserID: u.ID},
  904. &Follow{FollowID: u.ID},
  905. &Action{UserID: u.ID},
  906. &IssueUser{UID: u.ID},
  907. &EmailAddress{UID: u.ID},
  908. &UserOpenID{UID: u.ID},
  909. &Reaction{UserID: u.ID},
  910. &TeamUser{UID: u.ID},
  911. &Collaboration{UserID: u.ID},
  912. &Stopwatch{UserID: u.ID},
  913. ); err != nil {
  914. return fmt.Errorf("deleteBeans: %v", err)
  915. }
  916. // ***** START: PublicKey *****
  917. if _, err = e.Delete(&PublicKey{OwnerID: u.ID}); err != nil {
  918. return fmt.Errorf("deletePublicKeys: %v", err)
  919. }
  920. err = rewriteAllPublicKeys(e)
  921. if err != nil {
  922. return err
  923. }
  924. err = rewriteAllPrincipalKeys(e)
  925. if err != nil {
  926. return err
  927. }
  928. // ***** END: PublicKey *****
  929. // ***** START: GPGPublicKey *****
  930. if _, err = e.Delete(&GPGKey{OwnerID: u.ID}); err != nil {
  931. return fmt.Errorf("deleteGPGKeys: %v", err)
  932. }
  933. // ***** END: GPGPublicKey *****
  934. // Clear assignee.
  935. if err = clearAssigneeByUserID(e, u.ID); err != nil {
  936. return fmt.Errorf("clear assignee: %v", err)
  937. }
  938. // ***** START: ExternalLoginUser *****
  939. if err = removeAllAccountLinks(e, u); err != nil {
  940. return fmt.Errorf("ExternalLoginUser: %v", err)
  941. }
  942. // ***** END: ExternalLoginUser *****
  943. if _, err = e.ID(u.ID).Delete(new(User)); err != nil {
  944. return fmt.Errorf("Delete: %v", err)
  945. }
  946. // FIXME: system notice
  947. // Note: There are something just cannot be roll back,
  948. // so just keep error logs of those operations.
  949. path := UserPath(u.Name)
  950. if err := util.RemoveAll(path); err != nil {
  951. return fmt.Errorf("Failed to RemoveAll %s: %v", path, err)
  952. }
  953. if len(u.Avatar) > 0 {
  954. avatarPath := u.CustomAvatarRelativePath()
  955. if err := storage.Avatars.Delete(avatarPath); err != nil {
  956. return fmt.Errorf("Failed to remove %s: %v", avatarPath, err)
  957. }
  958. }
  959. return nil
  960. }
  961. // DeleteUser completely and permanently deletes everything of a user,
  962. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  963. func DeleteUser(u *User) (err error) {
  964. if u.IsOrganization() {
  965. return fmt.Errorf("%s is an organization not a user", u.Name)
  966. }
  967. sess := x.NewSession()
  968. defer sess.Close()
  969. if err = sess.Begin(); err != nil {
  970. return err
  971. }
  972. if err = deleteUser(sess, u); err != nil {
  973. // Note: don't wrapper error here.
  974. return err
  975. }
  976. return sess.Commit()
  977. }
  978. // DeleteInactiveUsers deletes all inactive users and email addresses.
  979. func DeleteInactiveUsers(ctx context.Context, olderThan time.Duration) (err error) {
  980. users := make([]*User, 0, 10)
  981. if olderThan > 0 {
  982. if err = x.
  983. Where("is_active = ? and created_unix < ?", false, time.Now().Add(-olderThan).Unix()).
  984. Find(&users); err != nil {
  985. return fmt.Errorf("get all inactive users: %v", err)
  986. }
  987. } else {
  988. if err = x.
  989. Where("is_active = ?", false).
  990. Find(&users); err != nil {
  991. return fmt.Errorf("get all inactive users: %v", err)
  992. }
  993. }
  994. // FIXME: should only update authorized_keys file once after all deletions.
  995. for _, u := range users {
  996. select {
  997. case <-ctx.Done():
  998. return ErrCancelledf("Before delete inactive user %s", u.Name)
  999. default:
  1000. }
  1001. if err = DeleteUser(u); err != nil {
  1002. // Ignore users that were set inactive by admin.
  1003. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  1004. continue
  1005. }
  1006. return err
  1007. }
  1008. }
  1009. _, err = x.
  1010. Where("is_activated = ?", false).
  1011. Delete(new(EmailAddress))
  1012. return err
  1013. }
  1014. // UserPath returns the path absolute path of user repositories.
  1015. func UserPath(userName string) string {
  1016. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  1017. }
  1018. func getUserByID(e Engine, id int64) (*User, error) {
  1019. u := new(User)
  1020. has, err := e.ID(id).Get(u)
  1021. if err != nil {
  1022. return nil, err
  1023. } else if !has {
  1024. return nil, ErrUserNotExist{id, "", 0}
  1025. }
  1026. return u, nil
  1027. }
  1028. // GetUserByID returns the user object by given ID if exists.
  1029. func GetUserByID(id int64) (*User, error) {
  1030. return getUserByID(x, id)
  1031. }
  1032. // GetUserByName returns user by given name.
  1033. func GetUserByName(name string) (*User, error) {
  1034. return getUserByName(x, name)
  1035. }
  1036. func getUserByName(e Engine, name string) (*User, error) {
  1037. if len(name) == 0 {
  1038. return nil, ErrUserNotExist{0, name, 0}
  1039. }
  1040. u := &User{LowerName: strings.ToLower(name)}
  1041. has, err := e.Get(u)
  1042. if err != nil {
  1043. return nil, err
  1044. } else if !has {
  1045. return nil, ErrUserNotExist{0, name, 0}
  1046. }
  1047. return u, nil
  1048. }
  1049. // GetUserEmailsByNames returns a list of e-mails corresponds to names of users
  1050. // that have their email notifications set to enabled or onmention.
  1051. func GetUserEmailsByNames(names []string) []string {
  1052. return getUserEmailsByNames(x, names)
  1053. }
  1054. func getUserEmailsByNames(e Engine, names []string) []string {
  1055. mails := make([]string, 0, len(names))
  1056. for _, name := range names {
  1057. u, err := getUserByName(e, name)
  1058. if err != nil {
  1059. continue
  1060. }
  1061. if u.IsMailable() && u.EmailNotifications() != EmailNotificationsDisabled {
  1062. mails = append(mails, u.Email)
  1063. }
  1064. }
  1065. return mails
  1066. }
  1067. // GetMaileableUsersByIDs gets users from ids, but only if they can receive mails
  1068. func GetMaileableUsersByIDs(ids []int64, isMention bool) ([]*User, error) {
  1069. if len(ids) == 0 {
  1070. return nil, nil
  1071. }
  1072. ous := make([]*User, 0, len(ids))
  1073. if isMention {
  1074. return ous, x.In("id", ids).
  1075. Where("`type` = ?", UserTypeIndividual).
  1076. And("`prohibit_login` = ?", false).
  1077. And("`is_active` = ?", true).
  1078. And("`email_notifications_preference` IN ( ?, ?)", EmailNotificationsEnabled, EmailNotificationsOnMention).
  1079. Find(&ous)
  1080. }
  1081. return ous, x.In("id", ids).
  1082. Where("`type` = ?", UserTypeIndividual).
  1083. And("`prohibit_login` = ?", false).
  1084. And("`is_active` = ?", true).
  1085. And("`email_notifications_preference` = ?", EmailNotificationsEnabled).
  1086. Find(&ous)
  1087. }
  1088. // GetUserNamesByIDs returns usernames for all resolved users from a list of Ids.
  1089. func GetUserNamesByIDs(ids []int64) ([]string, error) {
  1090. unames := make([]string, 0, len(ids))
  1091. err := x.In("id", ids).
  1092. Table("user").
  1093. Asc("name").
  1094. Cols("name").
  1095. Find(&unames)
  1096. return unames, err
  1097. }
  1098. // GetUsersByIDs returns all resolved users from a list of Ids.
  1099. func GetUsersByIDs(ids []int64) (UserList, error) {
  1100. ous := make([]*User, 0, len(ids))
  1101. if len(ids) == 0 {
  1102. return ous, nil
  1103. }
  1104. err := x.In("id", ids).
  1105. Asc("name").
  1106. Find(&ous)
  1107. return ous, err
  1108. }
  1109. // GetUserIDsByNames returns a slice of ids corresponds to names.
  1110. func GetUserIDsByNames(names []string, ignoreNonExistent bool) ([]int64, error) {
  1111. ids := make([]int64, 0, len(names))
  1112. for _, name := range names {
  1113. u, err := GetUserByName(name)
  1114. if err != nil {
  1115. if ignoreNonExistent {
  1116. continue
  1117. } else {
  1118. return nil, err
  1119. }
  1120. }
  1121. ids = append(ids, u.ID)
  1122. }
  1123. return ids, nil
  1124. }
  1125. // UserCommit represents a commit with validation of user.
  1126. type UserCommit struct {
  1127. User *User
  1128. *git.Commit
  1129. }
  1130. // ValidateCommitWithEmail check if author's e-mail of commit is corresponding to a user.
  1131. func ValidateCommitWithEmail(c *git.Commit) *User {
  1132. if c.Author == nil {
  1133. return nil
  1134. }
  1135. u, err := GetUserByEmail(c.Author.Email)
  1136. if err != nil {
  1137. return nil
  1138. }
  1139. return u
  1140. }
  1141. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  1142. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  1143. var (
  1144. u *User
  1145. emails = map[string]*User{}
  1146. newCommits = list.New()
  1147. e = oldCommits.Front()
  1148. )
  1149. for e != nil {
  1150. c := e.Value.(*git.Commit)
  1151. if c.Author != nil {
  1152. if v, ok := emails[c.Author.Email]; !ok {
  1153. u, _ = GetUserByEmail(c.Author.Email)
  1154. emails[c.Author.Email] = u
  1155. } else {
  1156. u = v
  1157. }
  1158. } else {
  1159. u = nil
  1160. }
  1161. newCommits.PushBack(UserCommit{
  1162. User: u,
  1163. Commit: c,
  1164. })
  1165. e = e.Next()
  1166. }
  1167. return newCommits
  1168. }
  1169. // GetUserByEmail returns the user object by given e-mail if exists.
  1170. func GetUserByEmail(email string) (*User, error) {
  1171. return GetUserByEmailContext(DefaultDBContext(), email)
  1172. }
  1173. // GetUserByEmailContext returns the user object by given e-mail if exists with db context
  1174. func GetUserByEmailContext(ctx DBContext, email string) (*User, error) {
  1175. if len(email) == 0 {
  1176. return nil, ErrUserNotExist{0, email, 0}
  1177. }
  1178. email = strings.ToLower(email)
  1179. // First try to find the user by primary email
  1180. user := &User{Email: email}
  1181. has, err := ctx.e.Get(user)
  1182. if err != nil {
  1183. return nil, err
  1184. }
  1185. if has {
  1186. return user, nil
  1187. }
  1188. // Otherwise, check in alternative list for activated email addresses
  1189. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  1190. has, err = ctx.e.Get(emailAddress)
  1191. if err != nil {
  1192. return nil, err
  1193. }
  1194. if has {
  1195. return getUserByID(ctx.e, emailAddress.UID)
  1196. }
  1197. // Finally, if email address is the protected email address:
  1198. if strings.HasSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress)) {
  1199. username := strings.TrimSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress))
  1200. user := &User{}
  1201. has, err := ctx.e.Where("lower_name=?", username).Get(user)
  1202. if err != nil {
  1203. return nil, err
  1204. }
  1205. if has {
  1206. return user, nil
  1207. }
  1208. }
  1209. return nil, ErrUserNotExist{0, email, 0}
  1210. }
  1211. // GetUser checks if a user already exists
  1212. func GetUser(user *User) (bool, error) {
  1213. return x.Get(user)
  1214. }
  1215. // SearchUserOptions contains the options for searching
  1216. type SearchUserOptions struct {
  1217. ListOptions
  1218. Keyword string
  1219. Type UserType
  1220. UID int64
  1221. OrderBy SearchOrderBy
  1222. Visible []structs.VisibleType
  1223. Actor *User // The user doing the search
  1224. IsActive util.OptionalBool
  1225. SearchByEmail bool // Search by email as well as username/full name
  1226. }
  1227. func (opts *SearchUserOptions) toConds() builder.Cond {
  1228. var cond builder.Cond = builder.Eq{"type": opts.Type}
  1229. if len(opts.Keyword) > 0 {
  1230. lowerKeyword := strings.ToLower(opts.Keyword)
  1231. keywordCond := builder.Or(
  1232. builder.Like{"lower_name", lowerKeyword},
  1233. builder.Like{"LOWER(full_name)", lowerKeyword},
  1234. )
  1235. if opts.SearchByEmail {
  1236. keywordCond = keywordCond.Or(builder.Like{"LOWER(email)", lowerKeyword})
  1237. }
  1238. cond = cond.And(keywordCond)
  1239. }
  1240. if len(opts.Visible) > 0 {
  1241. cond = cond.And(builder.In("visibility", opts.Visible))
  1242. } else {
  1243. cond = cond.And(builder.In("visibility", structs.VisibleTypePublic))
  1244. }
  1245. if opts.Actor != nil {
  1246. var exprCond builder.Cond
  1247. if setting.Database.UseMySQL {
  1248. exprCond = builder.Expr("org_user.org_id = user.id")
  1249. } else if setting.Database.UseMSSQL {
  1250. exprCond = builder.Expr("org_user.org_id = [user].id")
  1251. } else {
  1252. exprCond = builder.Expr("org_user.org_id = \"user\".id")
  1253. }
  1254. var accessCond = builder.NewCond()
  1255. if !opts.Actor.IsRestricted {
  1256. accessCond = builder.Or(
  1257. builder.In("id", builder.Select("org_id").From("org_user").LeftJoin("`user`", exprCond).Where(builder.And(builder.Eq{"uid": opts.Actor.ID}, builder.Eq{"visibility": structs.VisibleTypePrivate}))),
  1258. builder.In("visibility", structs.VisibleTypePublic, structs.VisibleTypeLimited))
  1259. } else {
  1260. // restricted users only see orgs they are a member of
  1261. accessCond = builder.In("id", builder.Select("org_id").From("org_user").LeftJoin("`user`", exprCond).Where(builder.And(builder.Eq{"uid": opts.Actor.ID})))
  1262. }
  1263. cond = cond.And(accessCond)
  1264. }
  1265. if opts.UID > 0 {
  1266. cond = cond.And(builder.Eq{"id": opts.UID})
  1267. }
  1268. if !opts.IsActive.IsNone() {
  1269. cond = cond.And(builder.Eq{"is_active": opts.IsActive.IsTrue()})
  1270. }
  1271. return cond
  1272. }
  1273. // SearchUsers takes options i.e. keyword and part of user name to search,
  1274. // it returns results in given range and number of total results.
  1275. func SearchUsers(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  1276. cond := opts.toConds()
  1277. count, err := x.Where(cond).Count(new(User))
  1278. if err != nil {
  1279. return nil, 0, fmt.Errorf("Count: %v", err)
  1280. }
  1281. if len(opts.OrderBy) == 0 {
  1282. opts.OrderBy = SearchOrderByAlphabetically
  1283. }
  1284. sess := x.Where(cond).OrderBy(opts.OrderBy.String())
  1285. if opts.Page != 0 {
  1286. sess = opts.setSessionPagination(sess)
  1287. }
  1288. users = make([]*User, 0, opts.PageSize)
  1289. return users, count, sess.Find(&users)
  1290. }
  1291. // GetStarredRepos returns the repos starred by a particular user
  1292. func GetStarredRepos(userID int64, private bool, listOptions ListOptions) ([]*Repository, error) {
  1293. sess := x.Where("star.uid=?", userID).
  1294. Join("LEFT", "star", "`repository`.id=`star`.repo_id")
  1295. if !private {
  1296. sess = sess.And("is_private=?", false)
  1297. }
  1298. if listOptions.Page != 0 {
  1299. sess = listOptions.setSessionPagination(sess)
  1300. repos := make([]*Repository, 0, listOptions.PageSize)
  1301. return repos, sess.Find(&repos)
  1302. }
  1303. repos := make([]*Repository, 0, 10)
  1304. return repos, sess.Find(&repos)
  1305. }
  1306. // GetWatchedRepos returns the repos watched by a particular user
  1307. func GetWatchedRepos(userID int64, private bool, listOptions ListOptions) ([]*Repository, error) {
  1308. sess := x.Where("watch.user_id=?", userID).
  1309. And("`watch`.mode<>?", RepoWatchModeDont).
  1310. Join("LEFT", "watch", "`repository`.id=`watch`.repo_id")
  1311. if !private {
  1312. sess = sess.And("is_private=?", false)
  1313. }
  1314. if listOptions.Page != 0 {
  1315. sess = listOptions.setSessionPagination(sess)
  1316. repos := make([]*Repository, 0, listOptions.PageSize)
  1317. return repos, sess.Find(&repos)
  1318. }
  1319. repos := make([]*Repository, 0, 10)
  1320. return repos, sess.Find(&repos)
  1321. }
  1322. // deleteKeysMarkedForDeletion returns true if ssh keys needs update
  1323. func deleteKeysMarkedForDeletion(keys []string) (bool, error) {
  1324. // Start session
  1325. sess := x.NewSession()
  1326. defer sess.Close()
  1327. if err := sess.Begin(); err != nil {
  1328. return false, err
  1329. }
  1330. // Delete keys marked for deletion
  1331. var sshKeysNeedUpdate bool
  1332. for _, KeyToDelete := range keys {
  1333. key, err := searchPublicKeyByContentWithEngine(sess, KeyToDelete)
  1334. if err != nil {
  1335. log.Error("SearchPublicKeyByContent: %v", err)
  1336. continue
  1337. }
  1338. if err = deletePublicKeys(sess, key.ID); err != nil {
  1339. log.Error("deletePublicKeys: %v", err)
  1340. continue
  1341. }
  1342. sshKeysNeedUpdate = true
  1343. }
  1344. if err := sess.Commit(); err != nil {
  1345. return false, err
  1346. }
  1347. return sshKeysNeedUpdate, nil
  1348. }
  1349. // addLdapSSHPublicKeys add a users public keys. Returns true if there are changes.
  1350. func addLdapSSHPublicKeys(usr *User, s *LoginSource, sshPublicKeys []string) bool {
  1351. var sshKeysNeedUpdate bool
  1352. for _, sshKey := range sshPublicKeys {
  1353. _, _, _, _, err := ssh.ParseAuthorizedKey([]byte(sshKey))
  1354. if err == nil {
  1355. sshKeyName := fmt.Sprintf("%s-%s", s.Name, sshKey[0:40])
  1356. if _, err := AddPublicKey(usr.ID, sshKeyName, sshKey, s.ID); err != nil {
  1357. if IsErrKeyAlreadyExist(err) {
  1358. log.Trace("addLdapSSHPublicKeys[%s]: LDAP Public SSH Key %s already exists for user", s.Name, usr.Name)
  1359. } else {
  1360. log.Error("addLdapSSHPublicKeys[%s]: Error adding LDAP Public SSH Key for user %s: %v", s.Name, usr.Name, err)
  1361. }
  1362. } else {
  1363. log.Trace("addLdapSSHPublicKeys[%s]: Added LDAP Public SSH Key for user %s", s.Name, usr.Name)
  1364. sshKeysNeedUpdate = true
  1365. }
  1366. } else {
  1367. log.Warn("addLdapSSHPublicKeys[%s]: Skipping invalid LDAP Public SSH Key for user %s: %v", s.Name, usr.Name, sshKey)
  1368. }
  1369. }
  1370. return sshKeysNeedUpdate
  1371. }
  1372. // synchronizeLdapSSHPublicKeys updates a users public keys. Returns true if there are changes.
  1373. func synchronizeLdapSSHPublicKeys(usr *User, s *LoginSource, sshPublicKeys []string) bool {
  1374. var sshKeysNeedUpdate bool
  1375. log.Trace("synchronizeLdapSSHPublicKeys[%s]: Handling LDAP Public SSH Key synchronization for user %s", s.Name, usr.Name)
  1376. // Get Public Keys from DB with current LDAP source
  1377. var giteaKeys []string
  1378. keys, err := ListPublicLdapSSHKeys(usr.ID, s.ID)
  1379. if err != nil {
  1380. log.Error("synchronizeLdapSSHPublicKeys[%s]: Error listing LDAP Public SSH Keys for user %s: %v", s.Name, usr.Name, err)
  1381. }
  1382. for _, v := range keys {
  1383. giteaKeys = append(giteaKeys, v.OmitEmail())
  1384. }
  1385. // Get Public Keys from LDAP and skip duplicate keys
  1386. var ldapKeys []string
  1387. for _, v := range sshPublicKeys {
  1388. sshKeySplit := strings.Split(v, " ")
  1389. if len(sshKeySplit) > 1 {
  1390. ldapKey := strings.Join(sshKeySplit[:2], " ")
  1391. if !util.ExistsInSlice(ldapKey, ldapKeys) {
  1392. ldapKeys = append(ldapKeys, ldapKey)
  1393. }
  1394. }
  1395. }
  1396. // Check if Public Key sync is needed
  1397. if util.IsEqualSlice(giteaKeys, ldapKeys) {
  1398. log.Trace("synchronizeLdapSSHPublicKeys[%s]: LDAP Public Keys are already in sync for %s (LDAP:%v/DB:%v)", s.Name, usr.Name, len(ldapKeys), len(giteaKeys))
  1399. return false
  1400. }
  1401. log.Trace("synchronizeLdapSSHPublicKeys[%s]: LDAP Public Key needs update for user %s (LDAP:%v/DB:%v)", s.Name, usr.Name, len(ldapKeys), len(giteaKeys))
  1402. // Add LDAP Public SSH Keys that doesn't already exist in DB
  1403. var newLdapSSHKeys []string
  1404. for _, LDAPPublicSSHKey := range ldapKeys {
  1405. if !util.ExistsInSlice(LDAPPublicSSHKey, giteaKeys) {
  1406. newLdapSSHKeys = append(newLdapSSHKeys, LDAPPublicSSHKey)
  1407. }
  1408. }
  1409. if addLdapSSHPublicKeys(usr, s, newLdapSSHKeys) {
  1410. sshKeysNeedUpdate = true
  1411. }
  1412. // Mark LDAP keys from DB that doesn't exist in LDAP for deletion
  1413. var giteaKeysToDelete []string
  1414. for _, giteaKey := range giteaKeys {
  1415. if !util.ExistsInSlice(giteaKey, ldapKeys) {
  1416. log.Trace("synchronizeLdapSSHPublicKeys[%s]: Marking LDAP Public SSH Key for deletion for user %s: %v", s.Name, usr.Name, giteaKey)
  1417. giteaKeysToDelete = append(giteaKeysToDelete, giteaKey)
  1418. }
  1419. }
  1420. // Delete LDAP keys from DB that doesn't exist in LDAP
  1421. needUpd, err := deleteKeysMarkedForDeletion(giteaKeysToDelete)
  1422. if err != nil {
  1423. log.Error("synchronizeLdapSSHPublicKeys[%s]: Error deleting LDAP Public SSH Keys marked for deletion for user %s: %v", s.Name, usr.Name, err)
  1424. }
  1425. if needUpd {
  1426. sshKeysNeedUpdate = true
  1427. }
  1428. return sshKeysNeedUpdate
  1429. }
  1430. // SyncExternalUsers is used to synchronize users with external authorization source
  1431. func SyncExternalUsers(ctx context.Context, updateExisting bool) error {
  1432. log.Trace("Doing: SyncExternalUsers")
  1433. ls, err := LoginSources()
  1434. if err != nil {
  1435. log.Error("SyncExternalUsers: %v", err)
  1436. return err
  1437. }
  1438. for _, s := range ls {
  1439. if !s.IsActived || !s.IsSyncEnabled {
  1440. continue
  1441. }
  1442. select {
  1443. case <-ctx.Done():
  1444. log.Warn("SyncExternalUsers: Cancelled before update of %s", s.Name)
  1445. return ErrCancelledf("Before update of %s", s.Name)
  1446. default:
  1447. }
  1448. if s.IsLDAP() {
  1449. log.Trace("Doing: SyncExternalUsers[%s]", s.Name)
  1450. var existingUsers []int64
  1451. var isAttributeSSHPublicKeySet = len(strings.TrimSpace(s.LDAP().AttributeSSHPublicKey)) > 0
  1452. var sshKeysNeedUpdate bool
  1453. // Find all users with this login type
  1454. var users []*User
  1455. err = x.Where("login_type = ?", LoginLDAP).
  1456. And("login_source = ?", s.ID).
  1457. Find(&users)
  1458. if err != nil {
  1459. log.Error("SyncExternalUsers: %v", err)
  1460. return err
  1461. }
  1462. select {
  1463. case <-ctx.Done():
  1464. log.Warn("SyncExternalUsers: Cancelled before update of %s", s.Name)
  1465. return ErrCancelledf("Before update of %s", s.Name)
  1466. default:
  1467. }
  1468. sr, err := s.LDAP().SearchEntries()
  1469. if err != nil {
  1470. log.Error("SyncExternalUsers LDAP source failure [%s], skipped", s.Name)
  1471. continue
  1472. }
  1473. if len(sr) == 0 {
  1474. if !s.LDAP().AllowDeactivateAll {
  1475. log.Error("LDAP search found no entries but did not report an error. Refusing to deactivate all users")
  1476. continue
  1477. } else {
  1478. log.Warn("LDAP search found no entries but did not report an error. All users will be deactivated as per settings")
  1479. }
  1480. }
  1481. for _, su := range sr {
  1482. select {
  1483. case <-ctx.Done():
  1484. log.Warn("SyncExternalUsers: Cancelled at update of %s before completed update of users", s.Name)
  1485. // Rewrite authorized_keys file if LDAP Public SSH Key attribute is set and any key was added or removed
  1486. if sshKeysNeedUpdate {
  1487. err = RewriteAllPublicKeys()
  1488. if err != nil {
  1489. log.Error("RewriteAllPublicKeys: %v", err)
  1490. }
  1491. }
  1492. return ErrCancelledf("During update of %s before completed update of users", s.Name)
  1493. default:
  1494. }
  1495. if len(su.Username) == 0 {
  1496. continue
  1497. }
  1498. if len(su.Mail) == 0 {
  1499. su.Mail = fmt.Sprintf("%s@localhost", su.Username)
  1500. }
  1501. var usr *User
  1502. // Search for existing user
  1503. for _, du := range users {
  1504. if du.LowerName == strings.ToLower(su.Username) {
  1505. usr = du
  1506. break
  1507. }
  1508. }
  1509. fullName := composeFullName(su.Name, su.Surname, su.Username)
  1510. // If no existing user found, create one
  1511. if usr == nil {
  1512. log.Trace("SyncExternalUsers[%s]: Creating user %s", s.Name, su.Username)
  1513. usr = &User{
  1514. LowerName: strings.ToLower(su.Username),
  1515. Name: su.Username,
  1516. FullName: fullName,
  1517. LoginType: s.Type,
  1518. LoginSource: s.ID,
  1519. LoginName: su.Username,
  1520. Email: su.Mail,
  1521. IsAdmin: su.IsAdmin,
  1522. IsRestricted: su.IsRestricted,
  1523. IsActive: true,
  1524. }
  1525. err = CreateUser(usr)
  1526. if err != nil {
  1527. log.Error("SyncExternalUsers[%s]: Error creating user %s: %v", s.Name, su.Username, err)
  1528. } else if isAttributeSSHPublicKeySet {
  1529. log.Trace("SyncExternalUsers[%s]: Adding LDAP Public SSH Keys for user %s", s.Name, usr.Name)
  1530. if addLdapSSHPublicKeys(usr, s, su.SSHPublicKey) {
  1531. sshKeysNeedUpdate = true
  1532. }
  1533. }
  1534. } else if updateExisting {
  1535. existingUsers = append(existingUsers, usr.ID)
  1536. // Synchronize SSH Public Key if that attribute is set
  1537. if isAttributeSSHPublicKeySet && synchronizeLdapSSHPublicKeys(usr, s, su.SSHPublicKey) {
  1538. sshKeysNeedUpdate = true
  1539. }
  1540. // Check if user data has changed
  1541. if (len(s.LDAP().AdminFilter) > 0 && usr.IsAdmin != su.IsAdmin) ||
  1542. (len(s.LDAP().RestrictedFilter) > 0 && usr.IsRestricted != su.IsRestricted) ||
  1543. !strings.EqualFold(usr.Email, su.Mail) ||
  1544. usr.FullName != fullName ||
  1545. !usr.IsActive {
  1546. log.Trace("SyncExternalUsers[%s]: Updating user %s", s.Name, usr.Name)
  1547. usr.FullName = fullName
  1548. usr.Email = su.Mail
  1549. // Change existing admin flag only if AdminFilter option is set
  1550. if len(s.LDAP().AdminFilter) > 0 {
  1551. usr.IsAdmin = su.IsAdmin
  1552. }
  1553. // Change existing restricted flag only if RestrictedFilter option is set
  1554. if !usr.IsAdmin && len(s.LDAP().RestrictedFilter) > 0 {
  1555. usr.IsRestricted = su.IsRestricted
  1556. }
  1557. usr.IsActive = true
  1558. err = UpdateUserCols(usr, "full_name", "email", "is_admin", "is_restricted", "is_active")
  1559. if err != nil {
  1560. log.Error("SyncExternalUsers[%s]: Error updating user %s: %v", s.Name, usr.Name, err)
  1561. }
  1562. }
  1563. }
  1564. }
  1565. // Rewrite authorized_keys file if LDAP Public SSH Key attribute is set and any key was added or removed
  1566. if sshKeysNeedUpdate {
  1567. err = RewriteAllPublicKeys()
  1568. if err != nil {
  1569. log.Error("RewriteAllPublicKeys: %v", err)
  1570. }
  1571. }
  1572. select {
  1573. case <-ctx.Done():
  1574. log.Warn("SyncExternalUsers: Cancelled during update of %s before delete users", s.Name)
  1575. return ErrCancelledf("During update of %s before delete users", s.Name)
  1576. default:
  1577. }
  1578. // Deactivate users not present in LDAP
  1579. if updateExisting {
  1580. for _, usr := range users {
  1581. found := false
  1582. for _, uid := range existingUsers {
  1583. if usr.ID == uid {
  1584. found = true
  1585. break
  1586. }
  1587. }
  1588. if !found {
  1589. log.Trace("SyncExternalUsers[%s]: Deactivating user %s", s.Name, usr.Name)
  1590. usr.IsActive = false
  1591. err = UpdateUserCols(usr, "is_active")
  1592. if err != nil {
  1593. log.Error("SyncExternalUsers[%s]: Error deactivating user %s: %v", s.Name, usr.Name, err)
  1594. }
  1595. }
  1596. }
  1597. }
  1598. }
  1599. }
  1600. return nil
  1601. }
  1602. // IterateUser iterate users
  1603. func IterateUser(f func(user *User) error) error {
  1604. var start int
  1605. var batchSize = setting.Database.IterateBufferSize
  1606. for {
  1607. var users = make([]*User, 0, batchSize)
  1608. if err := x.Limit(batchSize, start).Find(&users); err != nil {
  1609. return err
  1610. }
  1611. if len(users) == 0 {
  1612. return nil
  1613. }
  1614. start += len(users)
  1615. for _, user := range users {
  1616. if err := f(user); err != nil {
  1617. return err
  1618. }
  1619. }
  1620. }
  1621. }