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

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