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

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