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

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