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

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