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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892
  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 !u.ValidatePassword("")
  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. if err := 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. Where("team_user.uid = ?", u.ID).
  550. GroupBy("repository.id").Find(&ids); err != nil {
  551. return nil, err
  552. }
  553. if len(units) > 0 {
  554. return FilterOutRepoIdsWithoutUnitAccess(u, ids, units...)
  555. }
  556. return ids, nil
  557. }
  558. // GetAccessRepoIDs returns all repositories IDs where user's or user is a team member organizations
  559. func (u *User) GetAccessRepoIDs(units ...UnitType) ([]int64, error) {
  560. ids, err := u.GetRepositoryIDs(units...)
  561. if err != nil {
  562. return nil, err
  563. }
  564. ids2, err := u.GetOrgRepositoryIDs(units...)
  565. if err != nil {
  566. return nil, err
  567. }
  568. return append(ids, ids2...), nil
  569. }
  570. // GetMirrorRepositories returns mirror repositories that user owns, including private repositories.
  571. func (u *User) GetMirrorRepositories() ([]*Repository, error) {
  572. return GetUserMirrorRepositories(u.ID)
  573. }
  574. // GetOwnedOrganizations returns all organizations that user owns.
  575. func (u *User) GetOwnedOrganizations() (err error) {
  576. u.OwnedOrgs, err = GetOwnedOrgsByUserID(u.ID)
  577. return err
  578. }
  579. // GetOrganizations returns all organizations that user belongs to.
  580. func (u *User) GetOrganizations(all bool) error {
  581. ous, err := GetOrgUsersByUserID(u.ID, all)
  582. if err != nil {
  583. return err
  584. }
  585. u.Orgs = make([]*User, len(ous))
  586. for i, ou := range ous {
  587. u.Orgs[i], err = GetUserByID(ou.OrgID)
  588. if err != nil {
  589. return err
  590. }
  591. }
  592. return nil
  593. }
  594. // DisplayName returns full name if it's not empty,
  595. // returns username otherwise.
  596. func (u *User) DisplayName() string {
  597. trimmed := strings.TrimSpace(u.FullName)
  598. if len(trimmed) > 0 {
  599. return trimmed
  600. }
  601. return u.Name
  602. }
  603. // GetDisplayName returns full name if it's not empty and DEFAULT_SHOW_FULL_NAME is set,
  604. // returns username otherwise.
  605. func (u *User) GetDisplayName() string {
  606. trimmed := strings.TrimSpace(u.FullName)
  607. if len(trimmed) > 0 && setting.UI.DefaultShowFullName {
  608. return trimmed
  609. }
  610. return u.Name
  611. }
  612. func gitSafeName(name string) string {
  613. return strings.TrimSpace(strings.NewReplacer("\n", "", "<", "", ">", "").Replace(name))
  614. }
  615. // GitName returns a git safe name
  616. func (u *User) GitName() string {
  617. gitName := gitSafeName(u.FullName)
  618. if len(gitName) > 0 {
  619. return gitName
  620. }
  621. // Although u.Name should be safe if created in our system
  622. // LDAP users may have bad names
  623. gitName = gitSafeName(u.Name)
  624. if len(gitName) > 0 {
  625. return gitName
  626. }
  627. // Totally pathological name so it's got to be:
  628. return fmt.Sprintf("user-%d", u.ID)
  629. }
  630. // ShortName ellipses username to length
  631. func (u *User) ShortName(length int) string {
  632. return base.EllipsisString(u.Name, length)
  633. }
  634. // IsMailable checks if a user is eligible
  635. // to receive emails.
  636. func (u *User) IsMailable() bool {
  637. return u.IsActive
  638. }
  639. // EmailNotifications returns the User's email notification preference
  640. func (u *User) EmailNotifications() string {
  641. return u.EmailNotificationsPreference
  642. }
  643. // SetEmailNotifications sets the user's email notification preference
  644. func (u *User) SetEmailNotifications(set string) error {
  645. u.EmailNotificationsPreference = set
  646. if err := UpdateUserCols(u, "email_notifications_preference"); err != nil {
  647. log.Error("SetEmailNotifications: %v", err)
  648. return err
  649. }
  650. return nil
  651. }
  652. func isUserExist(e Engine, uid int64, name string) (bool, error) {
  653. if len(name) == 0 {
  654. return false, nil
  655. }
  656. return e.
  657. Where("id!=?", uid).
  658. Get(&User{LowerName: strings.ToLower(name)})
  659. }
  660. // IsUserExist checks if given user name exist,
  661. // the user name should be noncased unique.
  662. // If uid is presented, then check will rule out that one,
  663. // it is used when update a user name in settings page.
  664. func IsUserExist(uid int64, name string) (bool, error) {
  665. return isUserExist(x, uid, name)
  666. }
  667. // GetUserSalt returns a random user salt token.
  668. func GetUserSalt() (string, error) {
  669. return generate.GetRandomString(10)
  670. }
  671. // NewGhostUser creates and returns a fake user for someone has deleted his/her account.
  672. func NewGhostUser() *User {
  673. return &User{
  674. ID: -1,
  675. Name: "Ghost",
  676. LowerName: "ghost",
  677. }
  678. }
  679. // IsGhost check if user is fake user for a deleted account
  680. func (u *User) IsGhost() bool {
  681. if u == nil {
  682. return false
  683. }
  684. return u.ID == -1 && u.Name == "Ghost"
  685. }
  686. var (
  687. reservedUsernames = []string{
  688. "attachments",
  689. "admin",
  690. "api",
  691. "assets",
  692. "avatars",
  693. "commits",
  694. "css",
  695. "debug",
  696. "error",
  697. "explore",
  698. "ghost",
  699. "help",
  700. "img",
  701. "install",
  702. "issues",
  703. "js",
  704. "less",
  705. "metrics",
  706. "new",
  707. "notifications",
  708. "org",
  709. "plugins",
  710. "pulls",
  711. "raw",
  712. "repo",
  713. "stars",
  714. "template",
  715. "user",
  716. "vendor",
  717. "login",
  718. "robots.txt",
  719. ".",
  720. "..",
  721. ".well-known",
  722. "search",
  723. }
  724. reservedUserPatterns = []string{"*.keys", "*.gpg"}
  725. )
  726. // isUsableName checks if name is reserved or pattern of name is not allowed
  727. // based on given reserved names and patterns.
  728. // Names are exact match, patterns can be prefix or suffix match with placeholder '*'.
  729. func isUsableName(names, patterns []string, name string) error {
  730. name = strings.TrimSpace(strings.ToLower(name))
  731. if utf8.RuneCountInString(name) == 0 {
  732. return ErrNameEmpty
  733. }
  734. for i := range names {
  735. if name == names[i] {
  736. return ErrNameReserved{name}
  737. }
  738. }
  739. for _, pat := range patterns {
  740. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  741. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  742. return ErrNamePatternNotAllowed{pat}
  743. }
  744. }
  745. return nil
  746. }
  747. // IsUsableUsername returns an error when a username is reserved
  748. func IsUsableUsername(name string) error {
  749. return isUsableName(reservedUsernames, reservedUserPatterns, name)
  750. }
  751. // CreateUser creates record of a new user.
  752. func CreateUser(u *User) (err error) {
  753. if err = IsUsableUsername(u.Name); err != nil {
  754. return err
  755. }
  756. sess := x.NewSession()
  757. defer sess.Close()
  758. if err = sess.Begin(); err != nil {
  759. return err
  760. }
  761. isExist, err := isUserExist(sess, 0, u.Name)
  762. if err != nil {
  763. return err
  764. } else if isExist {
  765. return ErrUserAlreadyExist{u.Name}
  766. }
  767. u.Email = strings.ToLower(u.Email)
  768. isExist, err = sess.
  769. Where("email=?", u.Email).
  770. Get(new(User))
  771. if err != nil {
  772. return err
  773. } else if isExist {
  774. return ErrEmailAlreadyUsed{u.Email}
  775. }
  776. isExist, err = isEmailUsed(sess, u.Email)
  777. if err != nil {
  778. return err
  779. } else if isExist {
  780. return ErrEmailAlreadyUsed{u.Email}
  781. }
  782. u.KeepEmailPrivate = setting.Service.DefaultKeepEmailPrivate
  783. u.LowerName = strings.ToLower(u.Name)
  784. u.AvatarEmail = u.Email
  785. u.Avatar = base.HashEmail(u.AvatarEmail)
  786. if u.Rands, err = GetUserSalt(); err != nil {
  787. return err
  788. }
  789. if u.Salt, err = GetUserSalt(); err != nil {
  790. return err
  791. }
  792. u.HashPassword(u.Passwd)
  793. u.AllowCreateOrganization = setting.Service.DefaultAllowCreateOrganization && !setting.Admin.DisableRegularOrgCreation
  794. u.EmailNotificationsPreference = setting.Admin.DefaultEmailNotification
  795. u.MaxRepoCreation = -1
  796. u.Theme = setting.UI.DefaultTheme
  797. if _, err = sess.Insert(u); err != nil {
  798. return err
  799. }
  800. return sess.Commit()
  801. }
  802. func countUsers(e Engine) int64 {
  803. count, _ := e.
  804. Where("type=0").
  805. Count(new(User))
  806. return count
  807. }
  808. // CountUsers returns number of users.
  809. func CountUsers() int64 {
  810. return countUsers(x)
  811. }
  812. // get user by verify code
  813. func getVerifyUser(code string) (user *User) {
  814. if len(code) <= base.TimeLimitCodeLength {
  815. return nil
  816. }
  817. // use tail hex username query user
  818. hexStr := code[base.TimeLimitCodeLength:]
  819. if b, err := hex.DecodeString(hexStr); err == nil {
  820. if user, err = GetUserByName(string(b)); user != nil {
  821. return user
  822. }
  823. log.Error("user.getVerifyUser: %v", err)
  824. }
  825. return nil
  826. }
  827. // VerifyUserActiveCode verifies active code when active account
  828. func VerifyUserActiveCode(code string) (user *User) {
  829. minutes := setting.Service.ActiveCodeLives
  830. if user = getVerifyUser(code); user != nil {
  831. // time limit code
  832. prefix := code[:base.TimeLimitCodeLength]
  833. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands
  834. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  835. return user
  836. }
  837. }
  838. return nil
  839. }
  840. // VerifyActiveEmailCode verifies active email code when active account
  841. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  842. minutes := setting.Service.ActiveCodeLives
  843. if user := getVerifyUser(code); user != nil {
  844. // time limit code
  845. prefix := code[:base.TimeLimitCodeLength]
  846. data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands
  847. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  848. emailAddress := &EmailAddress{Email: email}
  849. if has, _ := x.Get(emailAddress); has {
  850. return emailAddress
  851. }
  852. }
  853. }
  854. return nil
  855. }
  856. // ChangeUserName changes all corresponding setting from old user name to new one.
  857. func ChangeUserName(u *User, newUserName string) (err error) {
  858. if err = IsUsableUsername(newUserName); err != nil {
  859. return err
  860. }
  861. isExist, err := IsUserExist(0, newUserName)
  862. if err != nil {
  863. return err
  864. } else if isExist {
  865. return ErrUserAlreadyExist{newUserName}
  866. }
  867. // Do not fail if directory does not exist
  868. if err = os.Rename(UserPath(u.Name), UserPath(newUserName)); err != nil && !os.IsNotExist(err) {
  869. return fmt.Errorf("Rename user directory: %v", err)
  870. }
  871. return nil
  872. }
  873. // checkDupEmail checks whether there are the same email with the user
  874. func checkDupEmail(e Engine, u *User) error {
  875. u.Email = strings.ToLower(u.Email)
  876. has, err := e.
  877. Where("id!=?", u.ID).
  878. And("type=?", u.Type).
  879. And("email=?", u.Email).
  880. Get(new(User))
  881. if err != nil {
  882. return err
  883. } else if has {
  884. return ErrEmailAlreadyUsed{u.Email}
  885. }
  886. return nil
  887. }
  888. func updateUser(e Engine, u *User) error {
  889. _, err := e.ID(u.ID).AllCols().Update(u)
  890. return err
  891. }
  892. // UpdateUser updates user's information.
  893. func UpdateUser(u *User) error {
  894. return updateUser(x, u)
  895. }
  896. // UpdateUserCols update user according special columns
  897. func UpdateUserCols(u *User, cols ...string) error {
  898. return updateUserCols(x, u, cols...)
  899. }
  900. func updateUserCols(e Engine, u *User, cols ...string) error {
  901. _, err := e.ID(u.ID).Cols(cols...).Update(u)
  902. return err
  903. }
  904. // UpdateUserSetting updates user's settings.
  905. func UpdateUserSetting(u *User) error {
  906. if !u.IsOrganization() {
  907. if err := checkDupEmail(x, u); err != nil {
  908. return err
  909. }
  910. }
  911. return updateUser(x, u)
  912. }
  913. // deleteBeans deletes all given beans, beans should contain delete conditions.
  914. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  915. for i := range beans {
  916. if _, err = e.Delete(beans[i]); err != nil {
  917. return err
  918. }
  919. }
  920. return nil
  921. }
  922. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  923. func deleteUser(e *xorm.Session, u *User) error {
  924. // Note: A user owns any repository or belongs to any organization
  925. // cannot perform delete operation.
  926. // Check ownership of repository.
  927. count, err := getRepositoryCount(e, u)
  928. if err != nil {
  929. return fmt.Errorf("GetRepositoryCount: %v", err)
  930. } else if count > 0 {
  931. return ErrUserOwnRepos{UID: u.ID}
  932. }
  933. // Check membership of organization.
  934. count, err = u.getOrganizationCount(e)
  935. if err != nil {
  936. return fmt.Errorf("GetOrganizationCount: %v", err)
  937. } else if count > 0 {
  938. return ErrUserHasOrgs{UID: u.ID}
  939. }
  940. // ***** START: Watch *****
  941. watchedRepoIDs := make([]int64, 0, 10)
  942. if err = e.Table("watch").Cols("watch.repo_id").
  943. Where("watch.user_id = ?", u.ID).And("watch.mode <>?", RepoWatchModeDont).Find(&watchedRepoIDs); err != nil {
  944. return fmt.Errorf("get all watches: %v", err)
  945. }
  946. if _, err = e.Decr("num_watches").In("id", watchedRepoIDs).NoAutoTime().Update(new(Repository)); err != nil {
  947. return fmt.Errorf("decrease repository num_watches: %v", err)
  948. }
  949. // ***** END: Watch *****
  950. // ***** START: Star *****
  951. starredRepoIDs := make([]int64, 0, 10)
  952. if err = e.Table("star").Cols("star.repo_id").
  953. Where("star.uid = ?", u.ID).Find(&starredRepoIDs); err != nil {
  954. return fmt.Errorf("get all stars: %v", err)
  955. } else if _, err = e.Decr("num_stars").In("id", starredRepoIDs).NoAutoTime().Update(new(Repository)); err != nil {
  956. return fmt.Errorf("decrease repository num_stars: %v", err)
  957. }
  958. // ***** END: Star *****
  959. // ***** START: Follow *****
  960. followeeIDs := make([]int64, 0, 10)
  961. if err = e.Table("follow").Cols("follow.follow_id").
  962. Where("follow.user_id = ?", u.ID).Find(&followeeIDs); err != nil {
  963. return fmt.Errorf("get all followees: %v", err)
  964. } else if _, err = e.Decr("num_followers").In("id", followeeIDs).Update(new(User)); err != nil {
  965. return fmt.Errorf("decrease user num_followers: %v", err)
  966. }
  967. followerIDs := make([]int64, 0, 10)
  968. if err = e.Table("follow").Cols("follow.user_id").
  969. Where("follow.follow_id = ?", u.ID).Find(&followerIDs); err != nil {
  970. return fmt.Errorf("get all followers: %v", err)
  971. } else if _, err = e.Decr("num_following").In("id", followerIDs).Update(new(User)); err != nil {
  972. return fmt.Errorf("decrease user num_following: %v", err)
  973. }
  974. // ***** END: Follow *****
  975. if err = deleteBeans(e,
  976. &AccessToken{UID: u.ID},
  977. &Collaboration{UserID: u.ID},
  978. &Access{UserID: u.ID},
  979. &Watch{UserID: u.ID},
  980. &Star{UID: u.ID},
  981. &Follow{UserID: u.ID},
  982. &Follow{FollowID: u.ID},
  983. &Action{UserID: u.ID},
  984. &IssueUser{UID: u.ID},
  985. &EmailAddress{UID: u.ID},
  986. &UserOpenID{UID: u.ID},
  987. &Reaction{UserID: u.ID},
  988. &TeamUser{UID: u.ID},
  989. &Collaboration{UserID: u.ID},
  990. &Stopwatch{UserID: u.ID},
  991. ); err != nil {
  992. return fmt.Errorf("deleteBeans: %v", err)
  993. }
  994. // ***** START: PublicKey *****
  995. if _, err = e.Delete(&PublicKey{OwnerID: u.ID}); err != nil {
  996. return fmt.Errorf("deletePublicKeys: %v", err)
  997. }
  998. err = rewriteAllPublicKeys(e)
  999. if err != nil {
  1000. return err
  1001. }
  1002. // ***** END: PublicKey *****
  1003. // ***** START: GPGPublicKey *****
  1004. if _, err = e.Delete(&GPGKey{OwnerID: u.ID}); err != nil {
  1005. return fmt.Errorf("deleteGPGKeys: %v", err)
  1006. }
  1007. // ***** END: GPGPublicKey *****
  1008. // Clear assignee.
  1009. if err = clearAssigneeByUserID(e, u.ID); err != nil {
  1010. return fmt.Errorf("clear assignee: %v", err)
  1011. }
  1012. // ***** START: ExternalLoginUser *****
  1013. if err = removeAllAccountLinks(e, u); err != nil {
  1014. return fmt.Errorf("ExternalLoginUser: %v", err)
  1015. }
  1016. // ***** END: ExternalLoginUser *****
  1017. if _, err = e.ID(u.ID).Delete(new(User)); err != nil {
  1018. return fmt.Errorf("Delete: %v", err)
  1019. }
  1020. // FIXME: system notice
  1021. // Note: There are something just cannot be roll back,
  1022. // so just keep error logs of those operations.
  1023. path := UserPath(u.Name)
  1024. if err := os.RemoveAll(path); err != nil {
  1025. return fmt.Errorf("Failed to RemoveAll %s: %v", path, err)
  1026. }
  1027. if len(u.Avatar) > 0 {
  1028. avatarPath := u.CustomAvatarPath()
  1029. if com.IsExist(avatarPath) {
  1030. if err := os.Remove(avatarPath); err != nil {
  1031. return fmt.Errorf("Failed to remove %s: %v", avatarPath, err)
  1032. }
  1033. }
  1034. }
  1035. return nil
  1036. }
  1037. // DeleteUser completely and permanently deletes everything of a user,
  1038. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  1039. func DeleteUser(u *User) (err error) {
  1040. sess := x.NewSession()
  1041. defer sess.Close()
  1042. if err = sess.Begin(); err != nil {
  1043. return err
  1044. }
  1045. if err = deleteUser(sess, u); err != nil {
  1046. // Note: don't wrapper error here.
  1047. return err
  1048. }
  1049. return sess.Commit()
  1050. }
  1051. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  1052. func DeleteInactivateUsers() (err error) {
  1053. users := make([]*User, 0, 10)
  1054. if err = x.
  1055. Where("is_active = ?", false).
  1056. Find(&users); err != nil {
  1057. return fmt.Errorf("get all inactive users: %v", err)
  1058. }
  1059. // FIXME: should only update authorized_keys file once after all deletions.
  1060. for _, u := range users {
  1061. if err = DeleteUser(u); err != nil {
  1062. // Ignore users that were set inactive by admin.
  1063. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  1064. continue
  1065. }
  1066. return err
  1067. }
  1068. }
  1069. _, err = x.
  1070. Where("is_activated = ?", false).
  1071. Delete(new(EmailAddress))
  1072. return err
  1073. }
  1074. // UserPath returns the path absolute path of user repositories.
  1075. func UserPath(userName string) string {
  1076. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  1077. }
  1078. // GetUserByKeyID get user information by user's public key id
  1079. func GetUserByKeyID(keyID int64) (*User, error) {
  1080. var user User
  1081. has, err := x.Join("INNER", "public_key", "`public_key`.owner_id = `user`.id").
  1082. Where("`public_key`.id=?", keyID).
  1083. Get(&user)
  1084. if err != nil {
  1085. return nil, err
  1086. }
  1087. if !has {
  1088. return nil, ErrUserNotExist{0, "", keyID}
  1089. }
  1090. return &user, nil
  1091. }
  1092. func getUserByID(e Engine, id int64) (*User, error) {
  1093. u := new(User)
  1094. has, err := e.ID(id).Get(u)
  1095. if err != nil {
  1096. return nil, err
  1097. } else if !has {
  1098. return nil, ErrUserNotExist{id, "", 0}
  1099. }
  1100. return u, nil
  1101. }
  1102. // GetUserByID returns the user object by given ID if exists.
  1103. func GetUserByID(id int64) (*User, error) {
  1104. return getUserByID(x, id)
  1105. }
  1106. // GetUserByName returns user by given name.
  1107. func GetUserByName(name string) (*User, error) {
  1108. return getUserByName(x, name)
  1109. }
  1110. func getUserByName(e Engine, name string) (*User, error) {
  1111. if len(name) == 0 {
  1112. return nil, ErrUserNotExist{0, name, 0}
  1113. }
  1114. u := &User{LowerName: strings.ToLower(name)}
  1115. has, err := e.Get(u)
  1116. if err != nil {
  1117. return nil, err
  1118. } else if !has {
  1119. return nil, ErrUserNotExist{0, name, 0}
  1120. }
  1121. return u, nil
  1122. }
  1123. // GetUserEmailsByNames returns a list of e-mails corresponds to names of users
  1124. // that have their email notifications set to enabled or onmention.
  1125. func GetUserEmailsByNames(names []string) []string {
  1126. return getUserEmailsByNames(x, names)
  1127. }
  1128. func getUserEmailsByNames(e Engine, names []string) []string {
  1129. mails := make([]string, 0, len(names))
  1130. for _, name := range names {
  1131. u, err := getUserByName(e, name)
  1132. if err != nil {
  1133. continue
  1134. }
  1135. if u.IsMailable() && u.EmailNotifications() != EmailNotificationsDisabled {
  1136. mails = append(mails, u.Email)
  1137. }
  1138. }
  1139. return mails
  1140. }
  1141. // GetMaileableUsersByIDs gets users from ids, but only if they can receive mails
  1142. func GetMaileableUsersByIDs(ids []int64) ([]*User, error) {
  1143. if len(ids) == 0 {
  1144. return nil, nil
  1145. }
  1146. ous := make([]*User, 0, len(ids))
  1147. return ous, x.In("id", ids).
  1148. Where("`type` = ?", UserTypeIndividual).
  1149. And("`prohibit_login` = ?", false).
  1150. And("`is_active` = ?", true).
  1151. And("`email_notifications_preference` = ?", EmailNotificationsEnabled).
  1152. Find(&ous)
  1153. }
  1154. // GetUsersByIDs returns all resolved users from a list of Ids.
  1155. func GetUsersByIDs(ids []int64) ([]*User, error) {
  1156. ous := make([]*User, 0, len(ids))
  1157. if len(ids) == 0 {
  1158. return ous, nil
  1159. }
  1160. err := x.In("id", ids).
  1161. Asc("name").
  1162. Find(&ous)
  1163. return ous, err
  1164. }
  1165. // GetUserIDsByNames returns a slice of ids corresponds to names.
  1166. func GetUserIDsByNames(names []string, ignoreNonExistent bool) ([]int64, error) {
  1167. ids := make([]int64, 0, len(names))
  1168. for _, name := range names {
  1169. u, err := GetUserByName(name)
  1170. if err != nil {
  1171. if ignoreNonExistent {
  1172. continue
  1173. } else {
  1174. return nil, err
  1175. }
  1176. }
  1177. ids = append(ids, u.ID)
  1178. }
  1179. return ids, nil
  1180. }
  1181. // UserCommit represents a commit with validation of user.
  1182. type UserCommit struct {
  1183. User *User
  1184. *git.Commit
  1185. }
  1186. // ValidateCommitWithEmail check if author's e-mail of commit is corresponding to a user.
  1187. func ValidateCommitWithEmail(c *git.Commit) *User {
  1188. if c.Author == nil {
  1189. return nil
  1190. }
  1191. u, err := GetUserByEmail(c.Author.Email)
  1192. if err != nil {
  1193. return nil
  1194. }
  1195. return u
  1196. }
  1197. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  1198. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  1199. var (
  1200. u *User
  1201. emails = map[string]*User{}
  1202. newCommits = list.New()
  1203. e = oldCommits.Front()
  1204. )
  1205. for e != nil {
  1206. c := e.Value.(*git.Commit)
  1207. if c.Author != nil {
  1208. if v, ok := emails[c.Author.Email]; !ok {
  1209. u, _ = GetUserByEmail(c.Author.Email)
  1210. emails[c.Author.Email] = u
  1211. } else {
  1212. u = v
  1213. }
  1214. } else {
  1215. u = nil
  1216. }
  1217. newCommits.PushBack(UserCommit{
  1218. User: u,
  1219. Commit: c,
  1220. })
  1221. e = e.Next()
  1222. }
  1223. return newCommits
  1224. }
  1225. // GetUserByEmail returns the user object by given e-mail if exists.
  1226. func GetUserByEmail(email string) (*User, error) {
  1227. if len(email) == 0 {
  1228. return nil, ErrUserNotExist{0, email, 0}
  1229. }
  1230. email = strings.ToLower(email)
  1231. // First try to find the user by primary email
  1232. user := &User{Email: email}
  1233. has, err := x.Get(user)
  1234. if err != nil {
  1235. return nil, err
  1236. }
  1237. if has {
  1238. return user, nil
  1239. }
  1240. // Otherwise, check in alternative list for activated email addresses
  1241. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  1242. has, err = x.Get(emailAddress)
  1243. if err != nil {
  1244. return nil, err
  1245. }
  1246. if has {
  1247. return GetUserByID(emailAddress.UID)
  1248. }
  1249. // Finally, if email address is the protected email address:
  1250. if strings.HasSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress)) {
  1251. username := strings.TrimSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress))
  1252. user := &User{LowerName: username}
  1253. has, err := x.Get(user)
  1254. if err != nil {
  1255. return nil, err
  1256. }
  1257. if has {
  1258. return user, nil
  1259. }
  1260. }
  1261. return nil, ErrUserNotExist{0, email, 0}
  1262. }
  1263. // GetUser checks if a user already exists
  1264. func GetUser(user *User) (bool, error) {
  1265. return x.Get(user)
  1266. }
  1267. // SearchUserOptions contains the options for searching
  1268. type SearchUserOptions struct {
  1269. Keyword string
  1270. Type UserType
  1271. UID int64
  1272. OrderBy SearchOrderBy
  1273. Page int
  1274. Visible []structs.VisibleType
  1275. OwnerID int64 // id of user for visibility calculation
  1276. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  1277. IsActive util.OptionalBool
  1278. SearchByEmail bool // Search by email as well as username/full name
  1279. }
  1280. func (opts *SearchUserOptions) toConds() builder.Cond {
  1281. var cond builder.Cond = builder.Eq{"type": opts.Type}
  1282. if len(opts.Keyword) > 0 {
  1283. lowerKeyword := strings.ToLower(opts.Keyword)
  1284. keywordCond := builder.Or(
  1285. builder.Like{"lower_name", lowerKeyword},
  1286. builder.Like{"LOWER(full_name)", lowerKeyword},
  1287. )
  1288. if opts.SearchByEmail {
  1289. keywordCond = keywordCond.Or(builder.Like{"LOWER(email)", lowerKeyword})
  1290. }
  1291. cond = cond.And(keywordCond)
  1292. }
  1293. if len(opts.Visible) > 0 {
  1294. cond = cond.And(builder.In("visibility", opts.Visible))
  1295. } else {
  1296. cond = cond.And(builder.In("visibility", structs.VisibleTypePublic))
  1297. }
  1298. if opts.OwnerID > 0 {
  1299. var exprCond builder.Cond
  1300. if setting.Database.UseMySQL {
  1301. exprCond = builder.Expr("org_user.org_id = user.id")
  1302. } else if setting.Database.UseMSSQL {
  1303. exprCond = builder.Expr("org_user.org_id = [user].id")
  1304. } else {
  1305. exprCond = builder.Expr("org_user.org_id = \"user\".id")
  1306. }
  1307. accessCond := builder.Or(
  1308. 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}))),
  1309. builder.In("visibility", structs.VisibleTypePublic, structs.VisibleTypeLimited))
  1310. cond = cond.And(accessCond)
  1311. }
  1312. if opts.UID > 0 {
  1313. cond = cond.And(builder.Eq{"id": opts.UID})
  1314. }
  1315. if !opts.IsActive.IsNone() {
  1316. cond = cond.And(builder.Eq{"is_active": opts.IsActive.IsTrue()})
  1317. }
  1318. return cond
  1319. }
  1320. // SearchUsers takes options i.e. keyword and part of user name to search,
  1321. // it returns results in given range and number of total results.
  1322. func SearchUsers(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  1323. cond := opts.toConds()
  1324. count, err := x.Where(cond).Count(new(User))
  1325. if err != nil {
  1326. return nil, 0, fmt.Errorf("Count: %v", err)
  1327. }
  1328. if opts.PageSize == 0 || opts.PageSize > setting.UI.ExplorePagingNum {
  1329. opts.PageSize = setting.UI.ExplorePagingNum
  1330. }
  1331. if opts.Page <= 0 {
  1332. opts.Page = 1
  1333. }
  1334. if len(opts.OrderBy) == 0 {
  1335. opts.OrderBy = SearchOrderByAlphabetically
  1336. }
  1337. sess := x.Where(cond)
  1338. if opts.PageSize > 0 {
  1339. sess = sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize)
  1340. }
  1341. if opts.PageSize == -1 {
  1342. opts.PageSize = int(count)
  1343. }
  1344. users = make([]*User, 0, opts.PageSize)
  1345. return users, count, sess.OrderBy(opts.OrderBy.String()).Find(&users)
  1346. }
  1347. // GetStarredRepos returns the repos starred by a particular user
  1348. func GetStarredRepos(userID int64, private bool) ([]*Repository, error) {
  1349. sess := x.Where("star.uid=?", userID).
  1350. Join("LEFT", "star", "`repository`.id=`star`.repo_id")
  1351. if !private {
  1352. sess = sess.And("is_private=?", false)
  1353. }
  1354. repos := make([]*Repository, 0, 10)
  1355. err := sess.Find(&repos)
  1356. if err != nil {
  1357. return nil, err
  1358. }
  1359. return repos, nil
  1360. }
  1361. // GetWatchedRepos returns the repos watched by a particular user
  1362. func GetWatchedRepos(userID int64, private bool) ([]*Repository, error) {
  1363. sess := x.Where("watch.user_id=?", userID).
  1364. And("`watch`.mode<>?", RepoWatchModeDont).
  1365. Join("LEFT", "watch", "`repository`.id=`watch`.repo_id")
  1366. if !private {
  1367. sess = sess.And("is_private=?", false)
  1368. }
  1369. repos := make([]*Repository, 0, 10)
  1370. err := sess.Find(&repos)
  1371. if err != nil {
  1372. return nil, err
  1373. }
  1374. return repos, nil
  1375. }
  1376. // deleteKeysMarkedForDeletion returns true if ssh keys needs update
  1377. func deleteKeysMarkedForDeletion(keys []string) (bool, error) {
  1378. // Start session
  1379. sess := x.NewSession()
  1380. defer sess.Close()
  1381. if err := sess.Begin(); err != nil {
  1382. return false, err
  1383. }
  1384. // Delete keys marked for deletion
  1385. var sshKeysNeedUpdate bool
  1386. for _, KeyToDelete := range keys {
  1387. key, err := searchPublicKeyByContentWithEngine(sess, KeyToDelete)
  1388. if err != nil {
  1389. log.Error("SearchPublicKeyByContent: %v", err)
  1390. continue
  1391. }
  1392. if err = deletePublicKeys(sess, key.ID); err != nil {
  1393. log.Error("deletePublicKeys: %v", err)
  1394. continue
  1395. }
  1396. sshKeysNeedUpdate = true
  1397. }
  1398. if err := sess.Commit(); err != nil {
  1399. return false, err
  1400. }
  1401. return sshKeysNeedUpdate, nil
  1402. }
  1403. // addLdapSSHPublicKeys add a users public keys. Returns true if there are changes.
  1404. func addLdapSSHPublicKeys(usr *User, s *LoginSource, sshPublicKeys []string) bool {
  1405. var sshKeysNeedUpdate bool
  1406. for _, sshKey := range sshPublicKeys {
  1407. _, _, _, _, err := ssh.ParseAuthorizedKey([]byte(sshKey))
  1408. if err == nil {
  1409. sshKeyName := fmt.Sprintf("%s-%s", s.Name, sshKey[0:40])
  1410. if _, err := AddPublicKey(usr.ID, sshKeyName, sshKey, s.ID); err != nil {
  1411. if IsErrKeyAlreadyExist(err) {
  1412. log.Trace("addLdapSSHPublicKeys[%s]: LDAP Public SSH Key %s already exists for user", s.Name, usr.Name)
  1413. } else {
  1414. log.Error("addLdapSSHPublicKeys[%s]: Error adding LDAP Public SSH Key for user %s: %v", s.Name, usr.Name, err)
  1415. }
  1416. } else {
  1417. log.Trace("addLdapSSHPublicKeys[%s]: Added LDAP Public SSH Key for user %s", s.Name, usr.Name)
  1418. sshKeysNeedUpdate = true
  1419. }
  1420. } else {
  1421. log.Warn("addLdapSSHPublicKeys[%s]: Skipping invalid LDAP Public SSH Key for user %s: %v", s.Name, usr.Name, sshKey)
  1422. }
  1423. }
  1424. return sshKeysNeedUpdate
  1425. }
  1426. // synchronizeLdapSSHPublicKeys updates a users public keys. Returns true if there are changes.
  1427. func synchronizeLdapSSHPublicKeys(usr *User, s *LoginSource, sshPublicKeys []string) bool {
  1428. var sshKeysNeedUpdate bool
  1429. log.Trace("synchronizeLdapSSHPublicKeys[%s]: Handling LDAP Public SSH Key synchronization for user %s", s.Name, usr.Name)
  1430. // Get Public Keys from DB with current LDAP source
  1431. var giteaKeys []string
  1432. keys, err := ListPublicLdapSSHKeys(usr.ID, s.ID)
  1433. if err != nil {
  1434. log.Error("synchronizeLdapSSHPublicKeys[%s]: Error listing LDAP Public SSH Keys for user %s: %v", s.Name, usr.Name, err)
  1435. }
  1436. for _, v := range keys {
  1437. giteaKeys = append(giteaKeys, v.OmitEmail())
  1438. }
  1439. // Get Public Keys from LDAP and skip duplicate keys
  1440. var ldapKeys []string
  1441. for _, v := range sshPublicKeys {
  1442. sshKeySplit := strings.Split(v, " ")
  1443. if len(sshKeySplit) > 1 {
  1444. ldapKey := strings.Join(sshKeySplit[:2], " ")
  1445. if !util.ExistsInSlice(ldapKey, ldapKeys) {
  1446. ldapKeys = append(ldapKeys, ldapKey)
  1447. }
  1448. }
  1449. }
  1450. // Check if Public Key sync is needed
  1451. if util.IsEqualSlice(giteaKeys, ldapKeys) {
  1452. 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))
  1453. return false
  1454. }
  1455. log.Trace("synchronizeLdapSSHPublicKeys[%s]: LDAP Public Key needs update for user %s (LDAP:%v/DB:%v)", s.Name, usr.Name, len(ldapKeys), len(giteaKeys))
  1456. // Add LDAP Public SSH Keys that doesn't already exist in DB
  1457. var newLdapSSHKeys []string
  1458. for _, LDAPPublicSSHKey := range ldapKeys {
  1459. if !util.ExistsInSlice(LDAPPublicSSHKey, giteaKeys) {
  1460. newLdapSSHKeys = append(newLdapSSHKeys, LDAPPublicSSHKey)
  1461. }
  1462. }
  1463. if addLdapSSHPublicKeys(usr, s, newLdapSSHKeys) {
  1464. sshKeysNeedUpdate = true
  1465. }
  1466. // Mark LDAP keys from DB that doesn't exist in LDAP for deletion
  1467. var giteaKeysToDelete []string
  1468. for _, giteaKey := range giteaKeys {
  1469. if !util.ExistsInSlice(giteaKey, ldapKeys) {
  1470. log.Trace("synchronizeLdapSSHPublicKeys[%s]: Marking LDAP Public SSH Key for deletion for user %s: %v", s.Name, usr.Name, giteaKey)
  1471. giteaKeysToDelete = append(giteaKeysToDelete, giteaKey)
  1472. }
  1473. }
  1474. // Delete LDAP keys from DB that doesn't exist in LDAP
  1475. needUpd, err := deleteKeysMarkedForDeletion(giteaKeysToDelete)
  1476. if err != nil {
  1477. log.Error("synchronizeLdapSSHPublicKeys[%s]: Error deleting LDAP Public SSH Keys marked for deletion for user %s: %v", s.Name, usr.Name, err)
  1478. }
  1479. if needUpd {
  1480. sshKeysNeedUpdate = true
  1481. }
  1482. return sshKeysNeedUpdate
  1483. }
  1484. // SyncExternalUsers is used to synchronize users with external authorization source
  1485. func SyncExternalUsers(ctx context.Context) {
  1486. log.Trace("Doing: SyncExternalUsers")
  1487. ls, err := LoginSources()
  1488. if err != nil {
  1489. log.Error("SyncExternalUsers: %v", err)
  1490. return
  1491. }
  1492. updateExisting := setting.Cron.SyncExternalUsers.UpdateExisting
  1493. for _, s := range ls {
  1494. if !s.IsActived || !s.IsSyncEnabled {
  1495. continue
  1496. }
  1497. select {
  1498. case <-ctx.Done():
  1499. log.Warn("SyncExternalUsers: Aborted due to shutdown before update of %s", s.Name)
  1500. return
  1501. default:
  1502. }
  1503. if s.IsLDAP() {
  1504. log.Trace("Doing: SyncExternalUsers[%s]", s.Name)
  1505. var existingUsers []int64
  1506. var isAttributeSSHPublicKeySet = len(strings.TrimSpace(s.LDAP().AttributeSSHPublicKey)) > 0
  1507. var sshKeysNeedUpdate bool
  1508. // Find all users with this login type
  1509. var users []*User
  1510. err = x.Where("login_type = ?", LoginLDAP).
  1511. And("login_source = ?", s.ID).
  1512. Find(&users)
  1513. if err != nil {
  1514. log.Error("SyncExternalUsers: %v", err)
  1515. return
  1516. }
  1517. select {
  1518. case <-ctx.Done():
  1519. log.Warn("SyncExternalUsers: Aborted due to shutdown before update of %s", s.Name)
  1520. return
  1521. default:
  1522. }
  1523. sr, err := s.LDAP().SearchEntries()
  1524. if err != nil {
  1525. log.Error("SyncExternalUsers LDAP source failure [%s], skipped", s.Name)
  1526. continue
  1527. }
  1528. for _, su := range sr {
  1529. select {
  1530. case <-ctx.Done():
  1531. log.Warn("SyncExternalUsers: Aborted due to shutdown at update of %s before completed update of users", s.Name)
  1532. // Rewrite authorized_keys file if LDAP Public SSH Key attribute is set and any key was added or removed
  1533. if sshKeysNeedUpdate {
  1534. err = RewriteAllPublicKeys()
  1535. if err != nil {
  1536. log.Error("RewriteAllPublicKeys: %v", err)
  1537. }
  1538. }
  1539. return
  1540. default:
  1541. }
  1542. if len(su.Username) == 0 {
  1543. continue
  1544. }
  1545. if len(su.Mail) == 0 {
  1546. su.Mail = fmt.Sprintf("%s@localhost", su.Username)
  1547. }
  1548. var usr *User
  1549. // Search for existing user
  1550. for _, du := range users {
  1551. if du.LowerName == strings.ToLower(su.Username) {
  1552. usr = du
  1553. break
  1554. }
  1555. }
  1556. fullName := composeFullName(su.Name, su.Surname, su.Username)
  1557. // If no existing user found, create one
  1558. if usr == nil {
  1559. log.Trace("SyncExternalUsers[%s]: Creating user %s", s.Name, su.Username)
  1560. usr = &User{
  1561. LowerName: strings.ToLower(su.Username),
  1562. Name: su.Username,
  1563. FullName: fullName,
  1564. LoginType: s.Type,
  1565. LoginSource: s.ID,
  1566. LoginName: su.Username,
  1567. Email: su.Mail,
  1568. IsAdmin: su.IsAdmin,
  1569. IsActive: true,
  1570. }
  1571. err = CreateUser(usr)
  1572. if err != nil {
  1573. log.Error("SyncExternalUsers[%s]: Error creating user %s: %v", s.Name, su.Username, err)
  1574. } else if isAttributeSSHPublicKeySet {
  1575. log.Trace("SyncExternalUsers[%s]: Adding LDAP Public SSH Keys for user %s", s.Name, usr.Name)
  1576. if addLdapSSHPublicKeys(usr, s, su.SSHPublicKey) {
  1577. sshKeysNeedUpdate = true
  1578. }
  1579. }
  1580. } else if updateExisting {
  1581. existingUsers = append(existingUsers, usr.ID)
  1582. // Synchronize SSH Public Key if that attribute is set
  1583. if isAttributeSSHPublicKeySet && synchronizeLdapSSHPublicKeys(usr, s, su.SSHPublicKey) {
  1584. sshKeysNeedUpdate = true
  1585. }
  1586. // Check if user data has changed
  1587. if (len(s.LDAP().AdminFilter) > 0 && usr.IsAdmin != su.IsAdmin) ||
  1588. !strings.EqualFold(usr.Email, su.Mail) ||
  1589. usr.FullName != fullName ||
  1590. !usr.IsActive {
  1591. log.Trace("SyncExternalUsers[%s]: Updating user %s", s.Name, usr.Name)
  1592. usr.FullName = fullName
  1593. usr.Email = su.Mail
  1594. // Change existing admin flag only if AdminFilter option is set
  1595. if len(s.LDAP().AdminFilter) > 0 {
  1596. usr.IsAdmin = su.IsAdmin
  1597. }
  1598. usr.IsActive = true
  1599. err = UpdateUserCols(usr, "full_name", "email", "is_admin", "is_active")
  1600. if err != nil {
  1601. log.Error("SyncExternalUsers[%s]: Error updating user %s: %v", s.Name, usr.Name, err)
  1602. }
  1603. }
  1604. }
  1605. }
  1606. // Rewrite authorized_keys file if LDAP Public SSH Key attribute is set and any key was added or removed
  1607. if sshKeysNeedUpdate {
  1608. err = RewriteAllPublicKeys()
  1609. if err != nil {
  1610. log.Error("RewriteAllPublicKeys: %v", err)
  1611. }
  1612. }
  1613. select {
  1614. case <-ctx.Done():
  1615. log.Warn("SyncExternalUsers: Aborted due to shutdown at update of %s before delete users", s.Name)
  1616. return
  1617. default:
  1618. }
  1619. // Deactivate users not present in LDAP
  1620. if updateExisting {
  1621. for _, usr := range users {
  1622. found := false
  1623. for _, uid := range existingUsers {
  1624. if usr.ID == uid {
  1625. found = true
  1626. break
  1627. }
  1628. }
  1629. if !found {
  1630. log.Trace("SyncExternalUsers[%s]: Deactivating user %s", s.Name, usr.Name)
  1631. usr.IsActive = false
  1632. err = UpdateUserCols(usr, "is_active")
  1633. if err != nil {
  1634. log.Error("SyncExternalUsers[%s]: Error deactivating user %s: %v", s.Name, usr.Name, err)
  1635. }
  1636. }
  1637. }
  1638. }
  1639. }
  1640. }
  1641. }