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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911
  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. IsRestricted bool `xorm:"NOT NULL DEFAULT false"`
  115. AllowGitHook bool
  116. AllowImportLocal bool // Allow migrate repository by local path
  117. AllowCreateOrganization bool `xorm:"DEFAULT true"`
  118. ProhibitLogin bool `xorm:"NOT NULL DEFAULT false"`
  119. // Avatar
  120. Avatar string `xorm:"VARCHAR(2048) NOT NULL"`
  121. AvatarEmail string `xorm:"NOT NULL"`
  122. UseCustomAvatar bool
  123. // Counters
  124. NumFollowers int
  125. NumFollowing int `xorm:"NOT NULL DEFAULT 0"`
  126. NumStars int
  127. NumRepos int
  128. // For organization
  129. NumTeams int
  130. NumMembers int
  131. Teams []*Team `xorm:"-"`
  132. Members UserList `xorm:"-"`
  133. MembersIsPublic map[int64]bool `xorm:"-"`
  134. Visibility structs.VisibleType `xorm:"NOT NULL DEFAULT 0"`
  135. RepoAdminChangeTeamAccess bool `xorm:"NOT NULL DEFAULT false"`
  136. // Preferences
  137. DiffViewStyle string `xorm:"NOT NULL DEFAULT ''"`
  138. Theme string `xorm:"NOT NULL DEFAULT ''"`
  139. }
  140. // ColorFormat writes a colored string to identify this struct
  141. func (u *User) ColorFormat(s fmt.State) {
  142. log.ColorFprintf(s, "%d:%s",
  143. log.NewColoredIDValue(u.ID),
  144. log.NewColoredValue(u.Name))
  145. }
  146. // BeforeUpdate is invoked from XORM before updating this object.
  147. func (u *User) BeforeUpdate() {
  148. if u.MaxRepoCreation < -1 {
  149. u.MaxRepoCreation = -1
  150. }
  151. // Organization does not need email
  152. u.Email = strings.ToLower(u.Email)
  153. if !u.IsOrganization() {
  154. if len(u.AvatarEmail) == 0 {
  155. u.AvatarEmail = u.Email
  156. }
  157. if len(u.AvatarEmail) > 0 && u.Avatar == "" {
  158. u.Avatar = base.HashEmail(u.AvatarEmail)
  159. }
  160. }
  161. u.LowerName = strings.ToLower(u.Name)
  162. u.Location = base.TruncateString(u.Location, 255)
  163. u.Website = base.TruncateString(u.Website, 255)
  164. u.Description = base.TruncateString(u.Description, 255)
  165. }
  166. // AfterLoad is invoked from XORM after filling all the fields of this object.
  167. func (u *User) AfterLoad() {
  168. if u.Theme == "" {
  169. u.Theme = setting.UI.DefaultTheme
  170. }
  171. }
  172. // SetLastLogin set time to last login
  173. func (u *User) SetLastLogin() {
  174. u.LastLoginUnix = timeutil.TimeStampNow()
  175. }
  176. // UpdateDiffViewStyle updates the users diff view style
  177. func (u *User) UpdateDiffViewStyle(style string) error {
  178. u.DiffViewStyle = style
  179. return UpdateUserCols(u, "diff_view_style")
  180. }
  181. // UpdateTheme updates a users' theme irrespective of the site wide theme
  182. func (u *User) UpdateTheme(themeName string) error {
  183. u.Theme = themeName
  184. return UpdateUserCols(u, "theme")
  185. }
  186. // GetEmail returns an noreply email, if the user has set to keep his
  187. // email address private, otherwise the primary email address.
  188. func (u *User) GetEmail() string {
  189. if u.KeepEmailPrivate {
  190. return fmt.Sprintf("%s@%s", u.LowerName, setting.Service.NoReplyAddress)
  191. }
  192. return u.Email
  193. }
  194. // APIFormat converts a User to api.User
  195. func (u *User) APIFormat() *api.User {
  196. return &api.User{
  197. ID: u.ID,
  198. UserName: u.Name,
  199. FullName: u.FullName,
  200. Email: u.GetEmail(),
  201. AvatarURL: u.AvatarLink(),
  202. Language: u.Language,
  203. IsAdmin: u.IsAdmin,
  204. LastLogin: u.LastLoginUnix.AsTime(),
  205. Created: u.CreatedUnix.AsTime(),
  206. }
  207. }
  208. // IsLocal returns true if user login type is LoginPlain.
  209. func (u *User) IsLocal() bool {
  210. return u.LoginType <= LoginPlain
  211. }
  212. // IsOAuth2 returns true if user login type is LoginOAuth2.
  213. func (u *User) IsOAuth2() bool {
  214. return u.LoginType == LoginOAuth2
  215. }
  216. // HasForkedRepo checks if user has already forked a repository with given ID.
  217. func (u *User) HasForkedRepo(repoID int64) bool {
  218. _, has := HasForkedRepo(u.ID, repoID)
  219. return has
  220. }
  221. // MaxCreationLimit returns the number of repositories a user is allowed to create
  222. func (u *User) MaxCreationLimit() int {
  223. if u.MaxRepoCreation <= -1 {
  224. return setting.Repository.MaxCreationLimit
  225. }
  226. return u.MaxRepoCreation
  227. }
  228. // CanCreateRepo returns if user login can create a repository
  229. func (u *User) CanCreateRepo() bool {
  230. if u.IsAdmin {
  231. return true
  232. }
  233. if u.MaxRepoCreation <= -1 {
  234. if setting.Repository.MaxCreationLimit <= -1 {
  235. return true
  236. }
  237. return u.NumRepos < setting.Repository.MaxCreationLimit
  238. }
  239. return u.NumRepos < u.MaxRepoCreation
  240. }
  241. // CanCreateOrganization returns true if user can create organisation.
  242. func (u *User) CanCreateOrganization() bool {
  243. return u.IsAdmin || (u.AllowCreateOrganization && !setting.Admin.DisableRegularOrgCreation)
  244. }
  245. // CanEditGitHook returns true if user can edit Git hooks.
  246. func (u *User) CanEditGitHook() bool {
  247. return !setting.DisableGitHooks && (u.IsAdmin || u.AllowGitHook)
  248. }
  249. // CanImportLocal returns true if user can migrate repository by local path.
  250. func (u *User) CanImportLocal() bool {
  251. if !setting.ImportLocalPaths {
  252. return false
  253. }
  254. return u.IsAdmin || u.AllowImportLocal
  255. }
  256. // DashboardLink returns the user dashboard page link.
  257. func (u *User) DashboardLink() string {
  258. if u.IsOrganization() {
  259. return setting.AppSubURL + "/org/" + u.Name + "/dashboard/"
  260. }
  261. return setting.AppSubURL + "/"
  262. }
  263. // HomeLink returns the user or organization home page link.
  264. func (u *User) HomeLink() string {
  265. return setting.AppSubURL + "/" + u.Name
  266. }
  267. // HTMLURL returns the user or organization's full link.
  268. func (u *User) HTMLURL() string {
  269. return setting.AppURL + u.Name
  270. }
  271. // GenerateEmailActivateCode generates an activate code based on user information and given e-mail.
  272. func (u *User) GenerateEmailActivateCode(email string) string {
  273. code := base.CreateTimeLimitCode(
  274. com.ToStr(u.ID)+email+u.LowerName+u.Passwd+u.Rands,
  275. setting.Service.ActiveCodeLives, nil)
  276. // Add tail hex username
  277. code += hex.EncodeToString([]byte(u.LowerName))
  278. return code
  279. }
  280. // GenerateActivateCode generates an activate code based on user information.
  281. func (u *User) GenerateActivateCode() string {
  282. return u.GenerateEmailActivateCode(u.Email)
  283. }
  284. // CustomAvatarPath returns user custom avatar file path.
  285. func (u *User) CustomAvatarPath() string {
  286. return filepath.Join(setting.AvatarUploadPath, u.Avatar)
  287. }
  288. // GenerateRandomAvatar generates a random avatar for user.
  289. func (u *User) GenerateRandomAvatar() error {
  290. return u.generateRandomAvatar(x)
  291. }
  292. func (u *User) generateRandomAvatar(e Engine) error {
  293. seed := u.Email
  294. if len(seed) == 0 {
  295. seed = u.Name
  296. }
  297. img, err := avatar.RandomImage([]byte(seed))
  298. if err != nil {
  299. return fmt.Errorf("RandomImage: %v", err)
  300. }
  301. // NOTICE for random avatar, it still uses id as avatar name, but custom avatar use md5
  302. // since random image is not a user's photo, there is no security for enumable
  303. if u.Avatar == "" {
  304. u.Avatar = fmt.Sprintf("%d", u.ID)
  305. }
  306. if err = os.MkdirAll(filepath.Dir(u.CustomAvatarPath()), os.ModePerm); err != nil {
  307. return fmt.Errorf("MkdirAll: %v", err)
  308. }
  309. fw, err := os.Create(u.CustomAvatarPath())
  310. if err != nil {
  311. return fmt.Errorf("Create: %v", err)
  312. }
  313. defer fw.Close()
  314. if _, err := e.ID(u.ID).Cols("avatar").Update(u); err != nil {
  315. return err
  316. }
  317. if err = png.Encode(fw, img); err != nil {
  318. return fmt.Errorf("Encode: %v", err)
  319. }
  320. log.Info("New random avatar created: %d", u.ID)
  321. return nil
  322. }
  323. // SizedRelAvatarLink returns a link to the user's avatar via
  324. // the local explore page. Function returns immediately.
  325. // When applicable, the link is for an avatar of the indicated size (in pixels).
  326. func (u *User) SizedRelAvatarLink(size int) string {
  327. return strings.TrimRight(setting.AppSubURL, "/") + "/user/avatar/" + u.Name + "/" + strconv.Itoa(size)
  328. }
  329. // RealSizedAvatarLink returns a link to the user's avatar. When
  330. // applicable, the link is for an avatar of the indicated size (in pixels).
  331. //
  332. // This function make take time to return when federated avatars
  333. // are in use, due to a DNS lookup need
  334. //
  335. func (u *User) RealSizedAvatarLink(size int) string {
  336. if u.ID == -1 {
  337. return base.DefaultAvatarLink()
  338. }
  339. switch {
  340. case u.UseCustomAvatar:
  341. if !com.IsFile(u.CustomAvatarPath()) {
  342. return base.DefaultAvatarLink()
  343. }
  344. return setting.AppSubURL + "/avatars/" + u.Avatar
  345. case setting.DisableGravatar, setting.OfflineMode:
  346. if !com.IsFile(u.CustomAvatarPath()) {
  347. if err := u.GenerateRandomAvatar(); err != nil {
  348. log.Error("GenerateRandomAvatar: %v", err)
  349. }
  350. }
  351. return setting.AppSubURL + "/avatars/" + u.Avatar
  352. }
  353. return base.SizedAvatarLink(u.AvatarEmail, size)
  354. }
  355. // RelAvatarLink returns a relative link to the user's avatar. The link
  356. // may either be a sub-URL to this site, or a full URL to an external avatar
  357. // service.
  358. func (u *User) RelAvatarLink() string {
  359. return u.SizedRelAvatarLink(base.DefaultAvatarSize)
  360. }
  361. // AvatarLink returns user avatar absolute link.
  362. func (u *User) AvatarLink() string {
  363. link := u.RelAvatarLink()
  364. if link[0] == '/' && link[1] != '/' {
  365. return setting.AppURL + strings.TrimPrefix(link, setting.AppSubURL)[1:]
  366. }
  367. return link
  368. }
  369. // GetFollowers returns range of user's followers.
  370. func (u *User) GetFollowers(page int) ([]*User, error) {
  371. users := make([]*User, 0, ItemsPerPage)
  372. sess := x.
  373. Limit(ItemsPerPage, (page-1)*ItemsPerPage).
  374. Where("follow.follow_id=?", u.ID).
  375. Join("LEFT", "follow", "`user`.id=follow.user_id")
  376. return users, sess.Find(&users)
  377. }
  378. // IsFollowing returns true if user is following followID.
  379. func (u *User) IsFollowing(followID int64) bool {
  380. return IsFollowing(u.ID, followID)
  381. }
  382. // GetFollowing returns range of user's following.
  383. func (u *User) GetFollowing(page int) ([]*User, error) {
  384. users := make([]*User, 0, ItemsPerPage)
  385. sess := x.
  386. Limit(ItemsPerPage, (page-1)*ItemsPerPage).
  387. Where("follow.user_id=?", u.ID).
  388. Join("LEFT", "follow", "`user`.id=follow.follow_id")
  389. return users, sess.Find(&users)
  390. }
  391. // NewGitSig generates and returns the signature of given user.
  392. func (u *User) NewGitSig() *git.Signature {
  393. return &git.Signature{
  394. Name: u.GitName(),
  395. Email: u.GetEmail(),
  396. When: time.Now(),
  397. }
  398. }
  399. func hashPassword(passwd, salt, algo string) string {
  400. var tempPasswd []byte
  401. switch algo {
  402. case algoBcrypt:
  403. tempPasswd, _ = bcrypt.GenerateFromPassword([]byte(passwd), bcrypt.DefaultCost)
  404. return string(tempPasswd)
  405. case algoScrypt:
  406. tempPasswd, _ = scrypt.Key([]byte(passwd), []byte(salt), 65536, 16, 2, 50)
  407. case algoArgon2:
  408. tempPasswd = argon2.IDKey([]byte(passwd), []byte(salt), 2, 65536, 8, 50)
  409. case algoPbkdf2:
  410. fallthrough
  411. default:
  412. tempPasswd = pbkdf2.Key([]byte(passwd), []byte(salt), 10000, 50, sha256.New)
  413. }
  414. return fmt.Sprintf("%x", tempPasswd)
  415. }
  416. // HashPassword hashes a password using the algorithm defined in the config value of PASSWORD_HASH_ALGO.
  417. func (u *User) HashPassword(passwd string) {
  418. u.PasswdHashAlgo = setting.PasswordHashAlgo
  419. u.Passwd = hashPassword(passwd, u.Salt, setting.PasswordHashAlgo)
  420. }
  421. // ValidatePassword checks if given password matches the one belongs to the user.
  422. func (u *User) ValidatePassword(passwd string) bool {
  423. tempHash := hashPassword(passwd, u.Salt, u.PasswdHashAlgo)
  424. if u.PasswdHashAlgo != algoBcrypt && subtle.ConstantTimeCompare([]byte(u.Passwd), []byte(tempHash)) == 1 {
  425. return true
  426. }
  427. if u.PasswdHashAlgo == algoBcrypt && bcrypt.CompareHashAndPassword([]byte(u.Passwd), []byte(passwd)) == nil {
  428. return true
  429. }
  430. return false
  431. }
  432. // IsPasswordSet checks if the password is set or left empty
  433. func (u *User) IsPasswordSet() bool {
  434. return !u.ValidatePassword("")
  435. }
  436. // UploadAvatar saves custom avatar for user.
  437. // FIXME: split uploads to different subdirs in case we have massive users.
  438. func (u *User) UploadAvatar(data []byte) error {
  439. m, err := avatar.Prepare(data)
  440. if err != nil {
  441. return err
  442. }
  443. sess := x.NewSession()
  444. defer sess.Close()
  445. if err = sess.Begin(); err != nil {
  446. return err
  447. }
  448. u.UseCustomAvatar = true
  449. // Different users can upload same image as avatar
  450. // If we prefix it with u.ID, it will be separated
  451. // Otherwise, if any of the users delete his avatar
  452. // Other users will lose their avatars too.
  453. u.Avatar = fmt.Sprintf("%x", md5.Sum([]byte(fmt.Sprintf("%d-%x", u.ID, md5.Sum(data)))))
  454. if err = updateUser(sess, u); err != nil {
  455. return fmt.Errorf("updateUser: %v", err)
  456. }
  457. if err := os.MkdirAll(setting.AvatarUploadPath, os.ModePerm); err != nil {
  458. return fmt.Errorf("Failed to create dir %s: %v", setting.AvatarUploadPath, err)
  459. }
  460. fw, err := os.Create(u.CustomAvatarPath())
  461. if err != nil {
  462. return fmt.Errorf("Create: %v", err)
  463. }
  464. defer fw.Close()
  465. if err = png.Encode(fw, *m); err != nil {
  466. return fmt.Errorf("Encode: %v", err)
  467. }
  468. return sess.Commit()
  469. }
  470. // DeleteAvatar deletes the user's custom avatar.
  471. func (u *User) DeleteAvatar() error {
  472. log.Trace("DeleteAvatar[%d]: %s", u.ID, u.CustomAvatarPath())
  473. if len(u.Avatar) > 0 {
  474. if err := os.Remove(u.CustomAvatarPath()); err != nil {
  475. return fmt.Errorf("Failed to remove %s: %v", u.CustomAvatarPath(), err)
  476. }
  477. }
  478. u.UseCustomAvatar = false
  479. u.Avatar = ""
  480. if _, err := x.ID(u.ID).Cols("avatar, use_custom_avatar").Update(u); err != nil {
  481. return fmt.Errorf("UpdateUser: %v", err)
  482. }
  483. return nil
  484. }
  485. // IsOrganization returns true if user is actually a organization.
  486. func (u *User) IsOrganization() bool {
  487. return u.Type == UserTypeOrganization
  488. }
  489. // IsUserOrgOwner returns true if user is in the owner team of given organization.
  490. func (u *User) IsUserOrgOwner(orgID int64) bool {
  491. isOwner, err := IsOrganizationOwner(orgID, u.ID)
  492. if err != nil {
  493. log.Error("IsOrganizationOwner: %v", err)
  494. return false
  495. }
  496. return isOwner
  497. }
  498. // IsUserPartOfOrg returns true if user with userID is part of the u organisation.
  499. func (u *User) IsUserPartOfOrg(userID int64) bool {
  500. return u.isUserPartOfOrg(x, userID)
  501. }
  502. func (u *User) isUserPartOfOrg(e Engine, userID int64) bool {
  503. isMember, err := isOrganizationMember(e, u.ID, userID)
  504. if err != nil {
  505. log.Error("IsOrganizationMember: %v", err)
  506. return false
  507. }
  508. return isMember
  509. }
  510. // IsPublicMember returns true if user public his/her membership in given organization.
  511. func (u *User) IsPublicMember(orgID int64) bool {
  512. isMember, err := IsPublicMembership(orgID, u.ID)
  513. if err != nil {
  514. log.Error("IsPublicMembership: %v", err)
  515. return false
  516. }
  517. return isMember
  518. }
  519. func (u *User) getOrganizationCount(e Engine) (int64, error) {
  520. return e.
  521. Where("uid=?", u.ID).
  522. Count(new(OrgUser))
  523. }
  524. // GetOrganizationCount returns count of membership of organization of user.
  525. func (u *User) GetOrganizationCount() (int64, error) {
  526. return u.getOrganizationCount(x)
  527. }
  528. // GetRepositories returns repositories that user owns, including private repositories.
  529. func (u *User) GetRepositories(page, pageSize int) (err error) {
  530. u.Repos, err = GetUserRepositories(u.ID, true, page, pageSize, "")
  531. return err
  532. }
  533. // GetRepositoryIDs returns repositories IDs where user owned and has unittypes
  534. // Caller shall check that units is not globally disabled
  535. func (u *User) GetRepositoryIDs(units ...UnitType) ([]int64, error) {
  536. var ids []int64
  537. sess := x.Table("repository").Cols("repository.id")
  538. if len(units) > 0 {
  539. sess = sess.Join("INNER", "repo_unit", "repository.id = repo_unit.repo_id")
  540. sess = sess.In("repo_unit.type", units)
  541. }
  542. return ids, sess.Where("owner_id = ?", u.ID).Find(&ids)
  543. }
  544. // GetOrgRepositoryIDs returns repositories IDs where user's team owned and has unittypes
  545. // Caller shall check that units is not globally disabled
  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", "(? != ? and repository.is_private != ?) OR (team_user.team_id = team_repo.team_id AND repository.id = team_repo.repo_id)", true, u.IsRestricted, 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. // Caller shall check that units is not globally disabled
  563. func (u *User) GetAccessRepoIDs(units ...UnitType) ([]int64, error) {
  564. ids, err := u.GetRepositoryIDs(units...)
  565. if err != nil {
  566. return nil, err
  567. }
  568. ids2, err := u.GetOrgRepositoryIDs(units...)
  569. if err != nil {
  570. return nil, err
  571. }
  572. return append(ids, ids2...), nil
  573. }
  574. // GetMirrorRepositories returns mirror repositories that user owns, including private repositories.
  575. func (u *User) GetMirrorRepositories() ([]*Repository, error) {
  576. return GetUserMirrorRepositories(u.ID)
  577. }
  578. // GetOwnedOrganizations returns all organizations that user owns.
  579. func (u *User) GetOwnedOrganizations() (err error) {
  580. u.OwnedOrgs, err = GetOwnedOrgsByUserID(u.ID)
  581. return err
  582. }
  583. // GetOrganizations returns all organizations that user belongs to.
  584. func (u *User) GetOrganizations(all bool) error {
  585. ous, err := GetOrgUsersByUserID(u.ID, all)
  586. if err != nil {
  587. return err
  588. }
  589. u.Orgs = make([]*User, len(ous))
  590. for i, ou := range ous {
  591. u.Orgs[i], err = GetUserByID(ou.OrgID)
  592. if err != nil {
  593. return err
  594. }
  595. }
  596. return nil
  597. }
  598. // DisplayName returns full name if it's not empty,
  599. // returns username otherwise.
  600. func (u *User) DisplayName() string {
  601. trimmed := strings.TrimSpace(u.FullName)
  602. if len(trimmed) > 0 {
  603. return trimmed
  604. }
  605. return u.Name
  606. }
  607. // GetDisplayName returns full name if it's not empty and DEFAULT_SHOW_FULL_NAME is set,
  608. // returns username otherwise.
  609. func (u *User) GetDisplayName() string {
  610. trimmed := strings.TrimSpace(u.FullName)
  611. if len(trimmed) > 0 && setting.UI.DefaultShowFullName {
  612. return trimmed
  613. }
  614. return u.Name
  615. }
  616. func gitSafeName(name string) string {
  617. return strings.TrimSpace(strings.NewReplacer("\n", "", "<", "", ">", "").Replace(name))
  618. }
  619. // GitName returns a git safe name
  620. func (u *User) GitName() string {
  621. gitName := gitSafeName(u.FullName)
  622. if len(gitName) > 0 {
  623. return gitName
  624. }
  625. // Although u.Name should be safe if created in our system
  626. // LDAP users may have bad names
  627. gitName = gitSafeName(u.Name)
  628. if len(gitName) > 0 {
  629. return gitName
  630. }
  631. // Totally pathological name so it's got to be:
  632. return fmt.Sprintf("user-%d", u.ID)
  633. }
  634. // ShortName ellipses username to length
  635. func (u *User) ShortName(length int) string {
  636. return base.EllipsisString(u.Name, length)
  637. }
  638. // IsMailable checks if a user is eligible
  639. // to receive emails.
  640. func (u *User) IsMailable() bool {
  641. return u.IsActive
  642. }
  643. // EmailNotifications returns the User's email notification preference
  644. func (u *User) EmailNotifications() string {
  645. return u.EmailNotificationsPreference
  646. }
  647. // SetEmailNotifications sets the user's email notification preference
  648. func (u *User) SetEmailNotifications(set string) error {
  649. u.EmailNotificationsPreference = set
  650. if err := UpdateUserCols(u, "email_notifications_preference"); err != nil {
  651. log.Error("SetEmailNotifications: %v", err)
  652. return err
  653. }
  654. return nil
  655. }
  656. func isUserExist(e Engine, uid int64, name string) (bool, error) {
  657. if len(name) == 0 {
  658. return false, nil
  659. }
  660. return e.
  661. Where("id!=?", uid).
  662. Get(&User{LowerName: strings.ToLower(name)})
  663. }
  664. // IsUserExist checks if given user name exist,
  665. // the user name should be noncased unique.
  666. // If uid is presented, then check will rule out that one,
  667. // it is used when update a user name in settings page.
  668. func IsUserExist(uid int64, name string) (bool, error) {
  669. return isUserExist(x, uid, name)
  670. }
  671. // GetUserSalt returns a random user salt token.
  672. func GetUserSalt() (string, error) {
  673. return generate.GetRandomString(10)
  674. }
  675. // NewGhostUser creates and returns a fake user for someone has deleted his/her account.
  676. func NewGhostUser() *User {
  677. return &User{
  678. ID: -1,
  679. Name: "Ghost",
  680. LowerName: "ghost",
  681. }
  682. }
  683. // NewReplaceUser creates and returns a fake user for external user
  684. func NewReplaceUser(name string) *User {
  685. return &User{
  686. ID: -1,
  687. Name: name,
  688. LowerName: strings.ToLower(name),
  689. }
  690. }
  691. // IsGhost check if user is fake user for a deleted account
  692. func (u *User) IsGhost() bool {
  693. if u == nil {
  694. return false
  695. }
  696. return u.ID == -1 && u.Name == "Ghost"
  697. }
  698. var (
  699. reservedUsernames = []string{
  700. "attachments",
  701. "admin",
  702. "api",
  703. "assets",
  704. "avatars",
  705. "commits",
  706. "css",
  707. "debug",
  708. "error",
  709. "explore",
  710. "ghost",
  711. "help",
  712. "img",
  713. "install",
  714. "issues",
  715. "js",
  716. "less",
  717. "metrics",
  718. "new",
  719. "notifications",
  720. "org",
  721. "plugins",
  722. "pulls",
  723. "raw",
  724. "repo",
  725. "stars",
  726. "template",
  727. "user",
  728. "vendor",
  729. "login",
  730. "robots.txt",
  731. ".",
  732. "..",
  733. ".well-known",
  734. "search",
  735. }
  736. reservedUserPatterns = []string{"*.keys", "*.gpg"}
  737. )
  738. // isUsableName checks if name is reserved or pattern of name is not allowed
  739. // based on given reserved names and patterns.
  740. // Names are exact match, patterns can be prefix or suffix match with placeholder '*'.
  741. func isUsableName(names, patterns []string, name string) error {
  742. name = strings.TrimSpace(strings.ToLower(name))
  743. if utf8.RuneCountInString(name) == 0 {
  744. return ErrNameEmpty
  745. }
  746. for i := range names {
  747. if name == names[i] {
  748. return ErrNameReserved{name}
  749. }
  750. }
  751. for _, pat := range patterns {
  752. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  753. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  754. return ErrNamePatternNotAllowed{pat}
  755. }
  756. }
  757. return nil
  758. }
  759. // IsUsableUsername returns an error when a username is reserved
  760. func IsUsableUsername(name string) error {
  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{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{LowerName: username}
  1265. has, err := x.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. Visible []structs.VisibleType
  1287. Actor *User // The user doing the search
  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 len(opts.Visible) > 0 {
  1306. cond = cond.And(builder.In("visibility", opts.Visible))
  1307. } else {
  1308. cond = cond.And(builder.In("visibility", structs.VisibleTypePublic))
  1309. }
  1310. if opts.Actor != nil {
  1311. var exprCond builder.Cond
  1312. if setting.Database.UseMySQL {
  1313. exprCond = builder.Expr("org_user.org_id = user.id")
  1314. } else if setting.Database.UseMSSQL {
  1315. exprCond = builder.Expr("org_user.org_id = [user].id")
  1316. } else {
  1317. exprCond = builder.Expr("org_user.org_id = \"user\".id")
  1318. }
  1319. var accessCond = builder.NewCond()
  1320. if !opts.Actor.IsRestricted {
  1321. accessCond = builder.Or(
  1322. builder.In("id", builder.Select("org_id").From("org_user").LeftJoin("`user`", exprCond).Where(builder.And(builder.Eq{"uid": opts.Actor.ID}, builder.Eq{"visibility": structs.VisibleTypePrivate}))),
  1323. builder.In("visibility", structs.VisibleTypePublic, structs.VisibleTypeLimited))
  1324. } else {
  1325. // restricted users only see orgs they are a member of
  1326. accessCond = builder.In("id", builder.Select("org_id").From("org_user").LeftJoin("`user`", exprCond).Where(builder.And(builder.Eq{"uid": opts.Actor.ID})))
  1327. }
  1328. cond = cond.And(accessCond)
  1329. }
  1330. if opts.UID > 0 {
  1331. cond = cond.And(builder.Eq{"id": opts.UID})
  1332. }
  1333. if !opts.IsActive.IsNone() {
  1334. cond = cond.And(builder.Eq{"is_active": opts.IsActive.IsTrue()})
  1335. }
  1336. return cond
  1337. }
  1338. // SearchUsers takes options i.e. keyword and part of user name to search,
  1339. // it returns results in given range and number of total results.
  1340. func SearchUsers(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  1341. cond := opts.toConds()
  1342. count, err := x.Where(cond).Count(new(User))
  1343. if err != nil {
  1344. return nil, 0, fmt.Errorf("Count: %v", err)
  1345. }
  1346. if opts.PageSize == 0 || opts.PageSize > setting.UI.ExplorePagingNum {
  1347. opts.PageSize = setting.UI.ExplorePagingNum
  1348. }
  1349. if opts.Page <= 0 {
  1350. opts.Page = 1
  1351. }
  1352. if len(opts.OrderBy) == 0 {
  1353. opts.OrderBy = SearchOrderByAlphabetically
  1354. }
  1355. sess := x.Where(cond)
  1356. if opts.PageSize > 0 {
  1357. sess = sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize)
  1358. }
  1359. if opts.PageSize == -1 {
  1360. opts.PageSize = int(count)
  1361. }
  1362. users = make([]*User, 0, opts.PageSize)
  1363. return users, count, sess.OrderBy(opts.OrderBy.String()).Find(&users)
  1364. }
  1365. // GetStarredRepos returns the repos starred by a particular user
  1366. func GetStarredRepos(userID int64, private bool) ([]*Repository, error) {
  1367. sess := x.Where("star.uid=?", userID).
  1368. Join("LEFT", "star", "`repository`.id=`star`.repo_id")
  1369. if !private {
  1370. sess = sess.And("is_private=?", false)
  1371. }
  1372. repos := make([]*Repository, 0, 10)
  1373. err := sess.Find(&repos)
  1374. if err != nil {
  1375. return nil, err
  1376. }
  1377. return repos, nil
  1378. }
  1379. // GetWatchedRepos returns the repos watched by a particular user
  1380. func GetWatchedRepos(userID int64, private bool) ([]*Repository, error) {
  1381. sess := x.Where("watch.user_id=?", userID).
  1382. And("`watch`.mode<>?", RepoWatchModeDont).
  1383. Join("LEFT", "watch", "`repository`.id=`watch`.repo_id")
  1384. if !private {
  1385. sess = sess.And("is_private=?", false)
  1386. }
  1387. repos := make([]*Repository, 0, 10)
  1388. err := sess.Find(&repos)
  1389. if err != nil {
  1390. return nil, err
  1391. }
  1392. return repos, nil
  1393. }
  1394. // deleteKeysMarkedForDeletion returns true if ssh keys needs update
  1395. func deleteKeysMarkedForDeletion(keys []string) (bool, error) {
  1396. // Start session
  1397. sess := x.NewSession()
  1398. defer sess.Close()
  1399. if err := sess.Begin(); err != nil {
  1400. return false, err
  1401. }
  1402. // Delete keys marked for deletion
  1403. var sshKeysNeedUpdate bool
  1404. for _, KeyToDelete := range keys {
  1405. key, err := searchPublicKeyByContentWithEngine(sess, KeyToDelete)
  1406. if err != nil {
  1407. log.Error("SearchPublicKeyByContent: %v", err)
  1408. continue
  1409. }
  1410. if err = deletePublicKeys(sess, key.ID); err != nil {
  1411. log.Error("deletePublicKeys: %v", err)
  1412. continue
  1413. }
  1414. sshKeysNeedUpdate = true
  1415. }
  1416. if err := sess.Commit(); err != nil {
  1417. return false, err
  1418. }
  1419. return sshKeysNeedUpdate, nil
  1420. }
  1421. // addLdapSSHPublicKeys add a users public keys. Returns true if there are changes.
  1422. func addLdapSSHPublicKeys(usr *User, s *LoginSource, sshPublicKeys []string) bool {
  1423. var sshKeysNeedUpdate bool
  1424. for _, sshKey := range sshPublicKeys {
  1425. _, _, _, _, err := ssh.ParseAuthorizedKey([]byte(sshKey))
  1426. if err == nil {
  1427. sshKeyName := fmt.Sprintf("%s-%s", s.Name, sshKey[0:40])
  1428. if _, err := AddPublicKey(usr.ID, sshKeyName, sshKey, s.ID); err != nil {
  1429. if IsErrKeyAlreadyExist(err) {
  1430. log.Trace("addLdapSSHPublicKeys[%s]: LDAP Public SSH Key %s already exists for user", s.Name, usr.Name)
  1431. } else {
  1432. log.Error("addLdapSSHPublicKeys[%s]: Error adding LDAP Public SSH Key for user %s: %v", s.Name, usr.Name, err)
  1433. }
  1434. } else {
  1435. log.Trace("addLdapSSHPublicKeys[%s]: Added LDAP Public SSH Key for user %s", s.Name, usr.Name)
  1436. sshKeysNeedUpdate = true
  1437. }
  1438. } else {
  1439. log.Warn("addLdapSSHPublicKeys[%s]: Skipping invalid LDAP Public SSH Key for user %s: %v", s.Name, usr.Name, sshKey)
  1440. }
  1441. }
  1442. return sshKeysNeedUpdate
  1443. }
  1444. // synchronizeLdapSSHPublicKeys updates a users public keys. Returns true if there are changes.
  1445. func synchronizeLdapSSHPublicKeys(usr *User, s *LoginSource, sshPublicKeys []string) bool {
  1446. var sshKeysNeedUpdate bool
  1447. log.Trace("synchronizeLdapSSHPublicKeys[%s]: Handling LDAP Public SSH Key synchronization for user %s", s.Name, usr.Name)
  1448. // Get Public Keys from DB with current LDAP source
  1449. var giteaKeys []string
  1450. keys, err := ListPublicLdapSSHKeys(usr.ID, s.ID)
  1451. if err != nil {
  1452. log.Error("synchronizeLdapSSHPublicKeys[%s]: Error listing LDAP Public SSH Keys for user %s: %v", s.Name, usr.Name, err)
  1453. }
  1454. for _, v := range keys {
  1455. giteaKeys = append(giteaKeys, v.OmitEmail())
  1456. }
  1457. // Get Public Keys from LDAP and skip duplicate keys
  1458. var ldapKeys []string
  1459. for _, v := range sshPublicKeys {
  1460. sshKeySplit := strings.Split(v, " ")
  1461. if len(sshKeySplit) > 1 {
  1462. ldapKey := strings.Join(sshKeySplit[:2], " ")
  1463. if !util.ExistsInSlice(ldapKey, ldapKeys) {
  1464. ldapKeys = append(ldapKeys, ldapKey)
  1465. }
  1466. }
  1467. }
  1468. // Check if Public Key sync is needed
  1469. if util.IsEqualSlice(giteaKeys, ldapKeys) {
  1470. 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))
  1471. return false
  1472. }
  1473. log.Trace("synchronizeLdapSSHPublicKeys[%s]: LDAP Public Key needs update for user %s (LDAP:%v/DB:%v)", s.Name, usr.Name, len(ldapKeys), len(giteaKeys))
  1474. // Add LDAP Public SSH Keys that doesn't already exist in DB
  1475. var newLdapSSHKeys []string
  1476. for _, LDAPPublicSSHKey := range ldapKeys {
  1477. if !util.ExistsInSlice(LDAPPublicSSHKey, giteaKeys) {
  1478. newLdapSSHKeys = append(newLdapSSHKeys, LDAPPublicSSHKey)
  1479. }
  1480. }
  1481. if addLdapSSHPublicKeys(usr, s, newLdapSSHKeys) {
  1482. sshKeysNeedUpdate = true
  1483. }
  1484. // Mark LDAP keys from DB that doesn't exist in LDAP for deletion
  1485. var giteaKeysToDelete []string
  1486. for _, giteaKey := range giteaKeys {
  1487. if !util.ExistsInSlice(giteaKey, ldapKeys) {
  1488. log.Trace("synchronizeLdapSSHPublicKeys[%s]: Marking LDAP Public SSH Key for deletion for user %s: %v", s.Name, usr.Name, giteaKey)
  1489. giteaKeysToDelete = append(giteaKeysToDelete, giteaKey)
  1490. }
  1491. }
  1492. // Delete LDAP keys from DB that doesn't exist in LDAP
  1493. needUpd, err := deleteKeysMarkedForDeletion(giteaKeysToDelete)
  1494. if err != nil {
  1495. log.Error("synchronizeLdapSSHPublicKeys[%s]: Error deleting LDAP Public SSH Keys marked for deletion for user %s: %v", s.Name, usr.Name, err)
  1496. }
  1497. if needUpd {
  1498. sshKeysNeedUpdate = true
  1499. }
  1500. return sshKeysNeedUpdate
  1501. }
  1502. // SyncExternalUsers is used to synchronize users with external authorization source
  1503. func SyncExternalUsers(ctx context.Context) {
  1504. log.Trace("Doing: SyncExternalUsers")
  1505. ls, err := LoginSources()
  1506. if err != nil {
  1507. log.Error("SyncExternalUsers: %v", err)
  1508. return
  1509. }
  1510. updateExisting := setting.Cron.SyncExternalUsers.UpdateExisting
  1511. for _, s := range ls {
  1512. if !s.IsActived || !s.IsSyncEnabled {
  1513. continue
  1514. }
  1515. select {
  1516. case <-ctx.Done():
  1517. log.Warn("SyncExternalUsers: Aborted due to shutdown before update of %s", s.Name)
  1518. return
  1519. default:
  1520. }
  1521. if s.IsLDAP() {
  1522. log.Trace("Doing: SyncExternalUsers[%s]", s.Name)
  1523. var existingUsers []int64
  1524. var isAttributeSSHPublicKeySet = len(strings.TrimSpace(s.LDAP().AttributeSSHPublicKey)) > 0
  1525. var sshKeysNeedUpdate bool
  1526. // Find all users with this login type
  1527. var users []*User
  1528. err = x.Where("login_type = ?", LoginLDAP).
  1529. And("login_source = ?", s.ID).
  1530. Find(&users)
  1531. if err != nil {
  1532. log.Error("SyncExternalUsers: %v", err)
  1533. return
  1534. }
  1535. select {
  1536. case <-ctx.Done():
  1537. log.Warn("SyncExternalUsers: Aborted due to shutdown before update of %s", s.Name)
  1538. return
  1539. default:
  1540. }
  1541. sr, err := s.LDAP().SearchEntries()
  1542. if err != nil {
  1543. log.Error("SyncExternalUsers LDAP source failure [%s], skipped", s.Name)
  1544. continue
  1545. }
  1546. for _, su := range sr {
  1547. select {
  1548. case <-ctx.Done():
  1549. log.Warn("SyncExternalUsers: Aborted due to shutdown at update of %s before completed update of users", s.Name)
  1550. // Rewrite authorized_keys file if LDAP Public SSH Key attribute is set and any key was added or removed
  1551. if sshKeysNeedUpdate {
  1552. err = RewriteAllPublicKeys()
  1553. if err != nil {
  1554. log.Error("RewriteAllPublicKeys: %v", err)
  1555. }
  1556. }
  1557. return
  1558. default:
  1559. }
  1560. if len(su.Username) == 0 {
  1561. continue
  1562. }
  1563. if len(su.Mail) == 0 {
  1564. su.Mail = fmt.Sprintf("%s@localhost", su.Username)
  1565. }
  1566. var usr *User
  1567. // Search for existing user
  1568. for _, du := range users {
  1569. if du.LowerName == strings.ToLower(su.Username) {
  1570. usr = du
  1571. break
  1572. }
  1573. }
  1574. fullName := composeFullName(su.Name, su.Surname, su.Username)
  1575. // If no existing user found, create one
  1576. if usr == nil {
  1577. log.Trace("SyncExternalUsers[%s]: Creating user %s", s.Name, su.Username)
  1578. usr = &User{
  1579. LowerName: strings.ToLower(su.Username),
  1580. Name: su.Username,
  1581. FullName: fullName,
  1582. LoginType: s.Type,
  1583. LoginSource: s.ID,
  1584. LoginName: su.Username,
  1585. Email: su.Mail,
  1586. IsAdmin: su.IsAdmin,
  1587. IsActive: true,
  1588. }
  1589. err = CreateUser(usr)
  1590. if err != nil {
  1591. log.Error("SyncExternalUsers[%s]: Error creating user %s: %v", s.Name, su.Username, err)
  1592. } else if isAttributeSSHPublicKeySet {
  1593. log.Trace("SyncExternalUsers[%s]: Adding LDAP Public SSH Keys for user %s", s.Name, usr.Name)
  1594. if addLdapSSHPublicKeys(usr, s, su.SSHPublicKey) {
  1595. sshKeysNeedUpdate = true
  1596. }
  1597. }
  1598. } else if updateExisting {
  1599. existingUsers = append(existingUsers, usr.ID)
  1600. // Synchronize SSH Public Key if that attribute is set
  1601. if isAttributeSSHPublicKeySet && synchronizeLdapSSHPublicKeys(usr, s, su.SSHPublicKey) {
  1602. sshKeysNeedUpdate = true
  1603. }
  1604. // Check if user data has changed
  1605. if (len(s.LDAP().AdminFilter) > 0 && usr.IsAdmin != su.IsAdmin) ||
  1606. !strings.EqualFold(usr.Email, su.Mail) ||
  1607. usr.FullName != fullName ||
  1608. !usr.IsActive {
  1609. log.Trace("SyncExternalUsers[%s]: Updating user %s", s.Name, usr.Name)
  1610. usr.FullName = fullName
  1611. usr.Email = su.Mail
  1612. // Change existing admin flag only if AdminFilter option is set
  1613. if len(s.LDAP().AdminFilter) > 0 {
  1614. usr.IsAdmin = su.IsAdmin
  1615. }
  1616. usr.IsActive = true
  1617. err = UpdateUserCols(usr, "full_name", "email", "is_admin", "is_active")
  1618. if err != nil {
  1619. log.Error("SyncExternalUsers[%s]: Error updating user %s: %v", s.Name, usr.Name, err)
  1620. }
  1621. }
  1622. }
  1623. }
  1624. // Rewrite authorized_keys file if LDAP Public SSH Key attribute is set and any key was added or removed
  1625. if sshKeysNeedUpdate {
  1626. err = RewriteAllPublicKeys()
  1627. if err != nil {
  1628. log.Error("RewriteAllPublicKeys: %v", err)
  1629. }
  1630. }
  1631. select {
  1632. case <-ctx.Done():
  1633. log.Warn("SyncExternalUsers: Aborted due to shutdown at update of %s before delete users", s.Name)
  1634. return
  1635. default:
  1636. }
  1637. // Deactivate users not present in LDAP
  1638. if updateExisting {
  1639. for _, usr := range users {
  1640. found := false
  1641. for _, uid := range existingUsers {
  1642. if usr.ID == uid {
  1643. found = true
  1644. break
  1645. }
  1646. }
  1647. if !found {
  1648. log.Trace("SyncExternalUsers[%s]: Deactivating user %s", s.Name, usr.Name)
  1649. usr.IsActive = false
  1650. err = UpdateUserCols(usr, "is_active")
  1651. if err != nil {
  1652. log.Error("SyncExternalUsers[%s]: Error deactivating user %s: %v", s.Name, usr.Name, err)
  1653. }
  1654. }
  1655. }
  1656. }
  1657. }
  1658. }
  1659. }