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.

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