You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

user.go 53KB

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