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

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