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

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