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

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