Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

user.go 57KB

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