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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747
  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. "context"
  8. "crypto/sha256"
  9. "crypto/subtle"
  10. "encoding/hex"
  11. "errors"
  12. "fmt"
  13. "net/url"
  14. "os"
  15. "path/filepath"
  16. "regexp"
  17. "strings"
  18. "time"
  19. "unicode/utf8"
  20. _ "image/jpeg" // Needed for jpeg support
  21. "code.gitea.io/gitea/models/db"
  22. "code.gitea.io/gitea/models/login"
  23. "code.gitea.io/gitea/models/unit"
  24. user_model "code.gitea.io/gitea/models/user"
  25. "code.gitea.io/gitea/modules/auth/openid"
  26. "code.gitea.io/gitea/modules/base"
  27. "code.gitea.io/gitea/modules/git"
  28. "code.gitea.io/gitea/modules/log"
  29. "code.gitea.io/gitea/modules/setting"
  30. "code.gitea.io/gitea/modules/structs"
  31. "code.gitea.io/gitea/modules/timeutil"
  32. "code.gitea.io/gitea/modules/util"
  33. "golang.org/x/crypto/argon2"
  34. "golang.org/x/crypto/bcrypt"
  35. "golang.org/x/crypto/pbkdf2"
  36. "golang.org/x/crypto/scrypt"
  37. "xorm.io/builder"
  38. "xorm.io/xorm"
  39. )
  40. // UserType defines the user type
  41. type UserType int
  42. const (
  43. // UserTypeIndividual defines an individual user
  44. UserTypeIndividual UserType = iota // Historic reason to make it starts at 0.
  45. // UserTypeOrganization defines an organization
  46. UserTypeOrganization
  47. )
  48. const (
  49. algoBcrypt = "bcrypt"
  50. algoScrypt = "scrypt"
  51. algoArgon2 = "argon2"
  52. algoPbkdf2 = "pbkdf2"
  53. )
  54. // AvailableHashAlgorithms represents the available password hashing algorithms
  55. var AvailableHashAlgorithms = []string{
  56. algoPbkdf2,
  57. algoArgon2,
  58. algoScrypt,
  59. algoBcrypt,
  60. }
  61. const (
  62. // EmailNotificationsEnabled indicates that the user would like to receive all email notifications
  63. EmailNotificationsEnabled = "enabled"
  64. // EmailNotificationsOnMention indicates that the user would like to be notified via email when mentioned.
  65. EmailNotificationsOnMention = "onmention"
  66. // EmailNotificationsDisabled indicates that the user would not like to be notified via email.
  67. EmailNotificationsDisabled = "disabled"
  68. )
  69. var (
  70. // ErrUserNameIllegal user name contains illegal characters error
  71. ErrUserNameIllegal = errors.New("User name contains illegal characters")
  72. // ErrLoginSourceNotActived login source is not actived error
  73. ErrLoginSourceNotActived = errors.New("Login source is not actived")
  74. // ErrUnsupportedLoginType login source is unknown error
  75. ErrUnsupportedLoginType = errors.New("Login source is unknown")
  76. // Characters prohibited in a user name (anything except A-Za-z0-9_.-)
  77. alphaDashDotPattern = regexp.MustCompile(`[^\w-\.]`)
  78. )
  79. // User represents the object of individual and member of organization.
  80. type User struct {
  81. ID int64 `xorm:"pk autoincr"`
  82. LowerName string `xorm:"UNIQUE NOT NULL"`
  83. Name string `xorm:"UNIQUE NOT NULL"`
  84. FullName string
  85. // Email is the primary email address (to be used for communication)
  86. Email string `xorm:"NOT NULL"`
  87. KeepEmailPrivate bool
  88. EmailNotificationsPreference string `xorm:"VARCHAR(20) NOT NULL DEFAULT 'enabled'"`
  89. Passwd string `xorm:"NOT NULL"`
  90. PasswdHashAlgo string `xorm:"NOT NULL DEFAULT 'argon2'"`
  91. // MustChangePassword is an attribute that determines if a user
  92. // is to change his/her password after registration.
  93. MustChangePassword bool `xorm:"NOT NULL DEFAULT false"`
  94. LoginType login.Type
  95. LoginSource int64 `xorm:"NOT NULL DEFAULT 0"`
  96. LoginName string
  97. Type UserType
  98. OwnedOrgs []*User `xorm:"-"`
  99. Repos []*Repository `xorm:"-"`
  100. Location string
  101. Website string
  102. Rands string `xorm:"VARCHAR(10)"`
  103. Salt string `xorm:"VARCHAR(10)"`
  104. Language string `xorm:"VARCHAR(5)"`
  105. Description string
  106. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  107. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  108. LastLoginUnix timeutil.TimeStamp `xorm:"INDEX"`
  109. // Remember visibility choice for convenience, true for private
  110. LastRepoVisibility bool
  111. // Maximum repository creation limit, -1 means use global default
  112. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1"`
  113. // IsActive true: primary email is activated, user can access Web UI and Git SSH.
  114. // false: an inactive user can only log in Web UI for account operations (ex: activate the account by email), no other access.
  115. IsActive bool `xorm:"INDEX"`
  116. // the user is a Gitea admin, who can access all repositories and the admin pages.
  117. IsAdmin bool
  118. // true: the user is only allowed to see organizations/repositories that they has explicit rights to.
  119. // (ex: in private Gitea instances user won't be allowed to see even organizations/repositories that are set as public)
  120. IsRestricted bool `xorm:"NOT NULL DEFAULT false"`
  121. AllowGitHook bool
  122. AllowImportLocal bool // Allow migrate repository by local path
  123. AllowCreateOrganization bool `xorm:"DEFAULT true"`
  124. // true: the user is not allowed to log in Web UI. Git/SSH access could still be allowed (please refer to Git/SSH access related code/documents)
  125. ProhibitLogin bool `xorm:"NOT NULL DEFAULT false"`
  126. // Avatar
  127. Avatar string `xorm:"VARCHAR(2048) NOT NULL"`
  128. AvatarEmail string `xorm:"NOT NULL"`
  129. UseCustomAvatar bool
  130. // Counters
  131. NumFollowers int
  132. NumFollowing int `xorm:"NOT NULL DEFAULT 0"`
  133. NumStars int
  134. NumRepos int
  135. // For organization
  136. NumTeams int
  137. NumMembers int
  138. Visibility structs.VisibleType `xorm:"NOT NULL DEFAULT 0"`
  139. RepoAdminChangeTeamAccess bool `xorm:"NOT NULL DEFAULT false"`
  140. // Preferences
  141. DiffViewStyle string `xorm:"NOT NULL DEFAULT ''"`
  142. Theme string `xorm:"NOT NULL DEFAULT ''"`
  143. KeepActivityPrivate bool `xorm:"NOT NULL DEFAULT false"`
  144. }
  145. func init() {
  146. db.RegisterModel(new(User))
  147. }
  148. // SearchOrganizationsOptions options to filter organizations
  149. type SearchOrganizationsOptions struct {
  150. db.ListOptions
  151. All bool
  152. }
  153. // ColorFormat writes a colored string to identify this struct
  154. func (u *User) ColorFormat(s fmt.State) {
  155. log.ColorFprintf(s, "%d:%s",
  156. log.NewColoredIDValue(u.ID),
  157. log.NewColoredValue(u.Name))
  158. }
  159. // BeforeUpdate is invoked from XORM before updating this object.
  160. func (u *User) BeforeUpdate() {
  161. if u.MaxRepoCreation < -1 {
  162. u.MaxRepoCreation = -1
  163. }
  164. // Organization does not need email
  165. u.Email = strings.ToLower(u.Email)
  166. if !u.IsOrganization() {
  167. if len(u.AvatarEmail) == 0 {
  168. u.AvatarEmail = u.Email
  169. }
  170. }
  171. u.LowerName = strings.ToLower(u.Name)
  172. u.Location = base.TruncateString(u.Location, 255)
  173. u.Website = base.TruncateString(u.Website, 255)
  174. u.Description = base.TruncateString(u.Description, 255)
  175. }
  176. // AfterLoad is invoked from XORM after filling all the fields of this object.
  177. func (u *User) AfterLoad() {
  178. if u.Theme == "" {
  179. u.Theme = setting.UI.DefaultTheme
  180. }
  181. }
  182. // SetLastLogin set time to last login
  183. func (u *User) SetLastLogin() {
  184. u.LastLoginUnix = timeutil.TimeStampNow()
  185. }
  186. // UpdateDiffViewStyle updates the users diff view style
  187. func (u *User) UpdateDiffViewStyle(style string) error {
  188. u.DiffViewStyle = style
  189. return UpdateUserCols(u, "diff_view_style")
  190. }
  191. // UpdateTheme updates a users' theme irrespective of the site wide theme
  192. func (u *User) UpdateTheme(themeName string) error {
  193. u.Theme = themeName
  194. return UpdateUserCols(u, "theme")
  195. }
  196. // GetEmail returns an noreply email, if the user has set to keep his
  197. // email address private, otherwise the primary email address.
  198. func (u *User) GetEmail() string {
  199. if u.KeepEmailPrivate {
  200. return fmt.Sprintf("%s@%s", u.LowerName, setting.Service.NoReplyAddress)
  201. }
  202. return u.Email
  203. }
  204. // GetAllUsers returns a slice of all individual users found in DB.
  205. func GetAllUsers() ([]*User, error) {
  206. users := make([]*User, 0)
  207. return users, db.GetEngine(db.DefaultContext).OrderBy("id").Where("type = ?", UserTypeIndividual).Find(&users)
  208. }
  209. // IsLocal returns true if user login type is LoginPlain.
  210. func (u *User) IsLocal() bool {
  211. return u.LoginType <= login.Plain
  212. }
  213. // IsOAuth2 returns true if user login type is LoginOAuth2.
  214. func (u *User) IsOAuth2() bool {
  215. return u.LoginType == login.OAuth2
  216. }
  217. // HasForkedRepo checks if user has already forked a repository with given ID.
  218. func (u *User) HasForkedRepo(repoID int64) bool {
  219. _, has := HasForkedRepo(u.ID, repoID)
  220. return has
  221. }
  222. // MaxCreationLimit returns the number of repositories a user is allowed to create
  223. func (u *User) MaxCreationLimit() int {
  224. if u.MaxRepoCreation <= -1 {
  225. return setting.Repository.MaxCreationLimit
  226. }
  227. return u.MaxRepoCreation
  228. }
  229. // CanCreateRepo returns if user login can create a repository
  230. // NOTE: functions calling this assume a failure due to repository count limit; if new checks are added, those functions should be revised
  231. func (u *User) CanCreateRepo() bool {
  232. if u.IsAdmin {
  233. return true
  234. }
  235. if u.MaxRepoCreation <= -1 {
  236. if setting.Repository.MaxCreationLimit <= -1 {
  237. return true
  238. }
  239. return u.NumRepos < setting.Repository.MaxCreationLimit
  240. }
  241. return u.NumRepos < u.MaxRepoCreation
  242. }
  243. // CanCreateOrganization returns true if user can create organisation.
  244. func (u *User) CanCreateOrganization() bool {
  245. return u.IsAdmin || (u.AllowCreateOrganization && !setting.Admin.DisableRegularOrgCreation)
  246. }
  247. // CanEditGitHook returns true if user can edit Git hooks.
  248. func (u *User) CanEditGitHook() bool {
  249. return !setting.DisableGitHooks && (u.IsAdmin || u.AllowGitHook)
  250. }
  251. // CanImportLocal returns true if user can migrate repository by local path.
  252. func (u *User) CanImportLocal() bool {
  253. if !setting.ImportLocalPaths || u == nil {
  254. return false
  255. }
  256. return u.IsAdmin || u.AllowImportLocal
  257. }
  258. // DashboardLink returns the user dashboard page link.
  259. func (u *User) DashboardLink() string {
  260. if u.IsOrganization() {
  261. return u.OrganisationLink() + "/dashboard"
  262. }
  263. return setting.AppSubURL + "/"
  264. }
  265. // HomeLink returns the user or organization home page link.
  266. func (u *User) HomeLink() string {
  267. return setting.AppSubURL + "/" + url.PathEscape(u.Name)
  268. }
  269. // HTMLURL returns the user or organization's full link.
  270. func (u *User) HTMLURL() string {
  271. return setting.AppURL + url.PathEscape(u.Name)
  272. }
  273. // OrganisationLink returns the organization sub page link.
  274. func (u *User) OrganisationLink() string {
  275. return setting.AppSubURL + "/org/" + url.PathEscape(u.Name)
  276. }
  277. // GenerateEmailActivateCode generates an activate code based on user information and given e-mail.
  278. func (u *User) GenerateEmailActivateCode(email string) string {
  279. code := base.CreateTimeLimitCode(
  280. fmt.Sprintf("%d%s%s%s%s", u.ID, email, u.LowerName, u.Passwd, u.Rands),
  281. setting.Service.ActiveCodeLives, nil)
  282. // Add tail hex username
  283. code += hex.EncodeToString([]byte(u.LowerName))
  284. return code
  285. }
  286. // GetFollowers returns range of user's followers.
  287. func (u *User) GetFollowers(listOptions db.ListOptions) ([]*User, error) {
  288. sess := db.GetEngine(db.DefaultContext).
  289. Where("follow.follow_id=?", u.ID).
  290. Join("LEFT", "follow", "`user`.id=follow.user_id")
  291. if listOptions.Page != 0 {
  292. sess = db.SetSessionPagination(sess, &listOptions)
  293. users := make([]*User, 0, listOptions.PageSize)
  294. return users, sess.Find(&users)
  295. }
  296. users := make([]*User, 0, 8)
  297. return users, sess.Find(&users)
  298. }
  299. // IsFollowing returns true if user is following followID.
  300. func (u *User) IsFollowing(followID int64) bool {
  301. return user_model.IsFollowing(u.ID, followID)
  302. }
  303. // GetFollowing returns range of user's following.
  304. func (u *User) GetFollowing(listOptions db.ListOptions) ([]*User, error) {
  305. sess := db.GetEngine(db.DefaultContext).
  306. Where("follow.user_id=?", u.ID).
  307. Join("LEFT", "follow", "`user`.id=follow.follow_id")
  308. if listOptions.Page != 0 {
  309. sess = db.SetSessionPagination(sess, &listOptions)
  310. users := make([]*User, 0, listOptions.PageSize)
  311. return users, sess.Find(&users)
  312. }
  313. users := make([]*User, 0, 8)
  314. return users, sess.Find(&users)
  315. }
  316. // NewGitSig generates and returns the signature of given user.
  317. func (u *User) NewGitSig() *git.Signature {
  318. return &git.Signature{
  319. Name: u.GitName(),
  320. Email: u.GetEmail(),
  321. When: time.Now(),
  322. }
  323. }
  324. func hashPassword(passwd, salt, algo string) string {
  325. var tempPasswd []byte
  326. switch algo {
  327. case algoBcrypt:
  328. tempPasswd, _ = bcrypt.GenerateFromPassword([]byte(passwd), bcrypt.DefaultCost)
  329. return string(tempPasswd)
  330. case algoScrypt:
  331. tempPasswd, _ = scrypt.Key([]byte(passwd), []byte(salt), 65536, 16, 2, 50)
  332. case algoArgon2:
  333. tempPasswd = argon2.IDKey([]byte(passwd), []byte(salt), 2, 65536, 8, 50)
  334. case algoPbkdf2:
  335. fallthrough
  336. default:
  337. tempPasswd = pbkdf2.Key([]byte(passwd), []byte(salt), 10000, 50, sha256.New)
  338. }
  339. return fmt.Sprintf("%x", tempPasswd)
  340. }
  341. // SetPassword hashes a password using the algorithm defined in the config value of PASSWORD_HASH_ALGO
  342. // change passwd, salt and passwd_hash_algo fields
  343. func (u *User) SetPassword(passwd string) (err error) {
  344. if len(passwd) == 0 {
  345. u.Passwd = ""
  346. u.Salt = ""
  347. u.PasswdHashAlgo = ""
  348. return nil
  349. }
  350. if u.Salt, err = GetUserSalt(); err != nil {
  351. return err
  352. }
  353. u.PasswdHashAlgo = setting.PasswordHashAlgo
  354. u.Passwd = hashPassword(passwd, u.Salt, setting.PasswordHashAlgo)
  355. return nil
  356. }
  357. // ValidatePassword checks if given password matches the one belongs to the user.
  358. func (u *User) ValidatePassword(passwd string) bool {
  359. tempHash := hashPassword(passwd, u.Salt, u.PasswdHashAlgo)
  360. if u.PasswdHashAlgo != algoBcrypt && subtle.ConstantTimeCompare([]byte(u.Passwd), []byte(tempHash)) == 1 {
  361. return true
  362. }
  363. if u.PasswdHashAlgo == algoBcrypt && bcrypt.CompareHashAndPassword([]byte(u.Passwd), []byte(passwd)) == nil {
  364. return true
  365. }
  366. return false
  367. }
  368. // IsPasswordSet checks if the password is set or left empty
  369. func (u *User) IsPasswordSet() bool {
  370. return len(u.Passwd) != 0
  371. }
  372. // IsVisibleToUser check if viewer is able to see user profile
  373. func (u *User) IsVisibleToUser(viewer *User) bool {
  374. return u.isVisibleToUser(db.GetEngine(db.DefaultContext), viewer)
  375. }
  376. func (u *User) isVisibleToUser(e db.Engine, viewer *User) bool {
  377. if viewer != nil && viewer.IsAdmin {
  378. return true
  379. }
  380. switch u.Visibility {
  381. case structs.VisibleTypePublic:
  382. return true
  383. case structs.VisibleTypeLimited:
  384. if viewer == nil || viewer.IsRestricted {
  385. return false
  386. }
  387. return true
  388. case structs.VisibleTypePrivate:
  389. if viewer == nil || viewer.IsRestricted {
  390. return false
  391. }
  392. // If they follow - they see each over
  393. follower := user_model.IsFollowing(u.ID, viewer.ID)
  394. if follower {
  395. return true
  396. }
  397. // Now we need to check if they in some organization together
  398. count, err := e.Table("team_user").
  399. Where(
  400. builder.And(
  401. builder.Eq{"uid": viewer.ID},
  402. builder.Or(
  403. builder.Eq{"org_id": u.ID},
  404. builder.In("org_id",
  405. builder.Select("org_id").
  406. From("team_user", "t2").
  407. Where(builder.Eq{"uid": u.ID}))))).
  408. Count(new(TeamUser))
  409. if err != nil {
  410. return false
  411. }
  412. if count < 0 {
  413. // No common organization
  414. return false
  415. }
  416. // they are in an organization together
  417. return true
  418. }
  419. return false
  420. }
  421. // IsOrganization returns true if user is actually a organization.
  422. func (u *User) IsOrganization() bool {
  423. return u.Type == UserTypeOrganization
  424. }
  425. // IsUserOrgOwner returns true if user is in the owner team of given organization.
  426. func (u *User) IsUserOrgOwner(orgID int64) bool {
  427. isOwner, err := IsOrganizationOwner(orgID, u.ID)
  428. if err != nil {
  429. log.Error("IsOrganizationOwner: %v", err)
  430. return false
  431. }
  432. return isOwner
  433. }
  434. // IsPublicMember returns true if user public his/her membership in given organization.
  435. func (u *User) IsPublicMember(orgID int64) bool {
  436. isMember, err := IsPublicMembership(orgID, u.ID)
  437. if err != nil {
  438. log.Error("IsPublicMembership: %v", err)
  439. return false
  440. }
  441. return isMember
  442. }
  443. // GetOrganizationCount returns count of membership of organization of the user.
  444. func GetOrganizationCount(ctx context.Context, u *User) (int64, error) {
  445. return db.GetEngine(ctx).
  446. Where("uid=?", u.ID).
  447. Count(new(OrgUser))
  448. }
  449. // GetOrganizationCount returns count of membership of organization of user.
  450. func (u *User) GetOrganizationCount() (int64, error) {
  451. return GetOrganizationCount(db.DefaultContext, u)
  452. }
  453. // GetRepositories returns repositories that user owns, including private repositories.
  454. func (u *User) GetRepositories(listOpts db.ListOptions, names ...string) (err error) {
  455. u.Repos, _, err = GetUserRepositories(&SearchRepoOptions{Actor: u, Private: true, ListOptions: listOpts, LowerNames: names})
  456. return err
  457. }
  458. // GetRepositoryIDs returns repositories IDs where user owned and has unittypes
  459. // Caller shall check that units is not globally disabled
  460. func (u *User) GetRepositoryIDs(units ...unit.Type) ([]int64, error) {
  461. var ids []int64
  462. sess := db.GetEngine(db.DefaultContext).Table("repository").Cols("repository.id")
  463. if len(units) > 0 {
  464. sess = sess.Join("INNER", "repo_unit", "repository.id = repo_unit.repo_id")
  465. sess = sess.In("repo_unit.type", units)
  466. }
  467. return ids, sess.Where("owner_id = ?", u.ID).Find(&ids)
  468. }
  469. // GetActiveRepositoryIDs returns non-archived repositories IDs where user owned and has unittypes
  470. // Caller shall check that units is not globally disabled
  471. func (u *User) GetActiveRepositoryIDs(units ...unit.Type) ([]int64, error) {
  472. var ids []int64
  473. sess := db.GetEngine(db.DefaultContext).Table("repository").Cols("repository.id")
  474. if len(units) > 0 {
  475. sess = sess.Join("INNER", "repo_unit", "repository.id = repo_unit.repo_id")
  476. sess = sess.In("repo_unit.type", units)
  477. }
  478. sess.Where(builder.Eq{"is_archived": false})
  479. return ids, sess.Where("owner_id = ?", u.ID).GroupBy("repository.id").Find(&ids)
  480. }
  481. // GetOrgRepositoryIDs returns repositories IDs where user's team owned and has unittypes
  482. // Caller shall check that units is not globally disabled
  483. func (u *User) GetOrgRepositoryIDs(units ...unit.Type) ([]int64, error) {
  484. var ids []int64
  485. if err := db.GetEngine(db.DefaultContext).Table("repository").
  486. Cols("repository.id").
  487. Join("INNER", "team_user", "repository.owner_id = team_user.org_id").
  488. 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).
  489. Where("team_user.uid = ?", u.ID).
  490. GroupBy("repository.id").Find(&ids); err != nil {
  491. return nil, err
  492. }
  493. if len(units) > 0 {
  494. return FilterOutRepoIdsWithoutUnitAccess(u, ids, units...)
  495. }
  496. return ids, nil
  497. }
  498. // GetActiveOrgRepositoryIDs returns non-archived repositories IDs where user's team owned and has unittypes
  499. // Caller shall check that units is not globally disabled
  500. func (u *User) GetActiveOrgRepositoryIDs(units ...unit.Type) ([]int64, error) {
  501. var ids []int64
  502. if err := db.GetEngine(db.DefaultContext).Table("repository").
  503. Cols("repository.id").
  504. Join("INNER", "team_user", "repository.owner_id = team_user.org_id").
  505. 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).
  506. Where("team_user.uid = ?", u.ID).
  507. Where(builder.Eq{"is_archived": false}).
  508. GroupBy("repository.id").Find(&ids); err != nil {
  509. return nil, err
  510. }
  511. if len(units) > 0 {
  512. return FilterOutRepoIdsWithoutUnitAccess(u, ids, units...)
  513. }
  514. return ids, nil
  515. }
  516. // GetAccessRepoIDs returns all repositories IDs where user's or user is a team member organizations
  517. // Caller shall check that units is not globally disabled
  518. func (u *User) GetAccessRepoIDs(units ...unit.Type) ([]int64, error) {
  519. ids, err := u.GetRepositoryIDs(units...)
  520. if err != nil {
  521. return nil, err
  522. }
  523. ids2, err := u.GetOrgRepositoryIDs(units...)
  524. if err != nil {
  525. return nil, err
  526. }
  527. return append(ids, ids2...), nil
  528. }
  529. // GetActiveAccessRepoIDs returns all non-archived repositories IDs where user's or user is a team member organizations
  530. // Caller shall check that units is not globally disabled
  531. func (u *User) GetActiveAccessRepoIDs(units ...unit.Type) ([]int64, error) {
  532. ids, err := u.GetActiveRepositoryIDs(units...)
  533. if err != nil {
  534. return nil, err
  535. }
  536. ids2, err := u.GetActiveOrgRepositoryIDs(units...)
  537. if err != nil {
  538. return nil, err
  539. }
  540. return append(ids, ids2...), nil
  541. }
  542. // GetMirrorRepositories returns mirror repositories that user owns, including private repositories.
  543. func (u *User) GetMirrorRepositories() ([]*Repository, error) {
  544. return GetUserMirrorRepositories(u.ID)
  545. }
  546. // GetOwnedOrganizations returns all organizations that user owns.
  547. func (u *User) GetOwnedOrganizations() (err error) {
  548. u.OwnedOrgs, err = GetOwnedOrgsByUserID(u.ID)
  549. return err
  550. }
  551. // DisplayName returns full name if it's not empty,
  552. // returns username otherwise.
  553. func (u *User) DisplayName() string {
  554. trimmed := strings.TrimSpace(u.FullName)
  555. if len(trimmed) > 0 {
  556. return trimmed
  557. }
  558. return u.Name
  559. }
  560. // GetDisplayName returns full name if it's not empty and DEFAULT_SHOW_FULL_NAME is set,
  561. // returns username otherwise.
  562. func (u *User) GetDisplayName() string {
  563. if setting.UI.DefaultShowFullName {
  564. trimmed := strings.TrimSpace(u.FullName)
  565. if len(trimmed) > 0 {
  566. return trimmed
  567. }
  568. }
  569. return u.Name
  570. }
  571. func gitSafeName(name string) string {
  572. return strings.TrimSpace(strings.NewReplacer("\n", "", "<", "", ">", "").Replace(name))
  573. }
  574. // GitName returns a git safe name
  575. func (u *User) GitName() string {
  576. gitName := gitSafeName(u.FullName)
  577. if len(gitName) > 0 {
  578. return gitName
  579. }
  580. // Although u.Name should be safe if created in our system
  581. // LDAP users may have bad names
  582. gitName = gitSafeName(u.Name)
  583. if len(gitName) > 0 {
  584. return gitName
  585. }
  586. // Totally pathological name so it's got to be:
  587. return fmt.Sprintf("user-%d", u.ID)
  588. }
  589. // ShortName ellipses username to length
  590. func (u *User) ShortName(length int) string {
  591. return base.EllipsisString(u.Name, length)
  592. }
  593. // IsMailable checks if a user is eligible
  594. // to receive emails.
  595. func (u *User) IsMailable() bool {
  596. return u.IsActive
  597. }
  598. // EmailNotifications returns the User's email notification preference
  599. func (u *User) EmailNotifications() string {
  600. return u.EmailNotificationsPreference
  601. }
  602. // SetEmailNotifications sets the user's email notification preference
  603. func (u *User) SetEmailNotifications(set string) error {
  604. u.EmailNotificationsPreference = set
  605. if err := UpdateUserCols(u, "email_notifications_preference"); err != nil {
  606. log.Error("SetEmailNotifications: %v", err)
  607. return err
  608. }
  609. return nil
  610. }
  611. func isUserExist(e db.Engine, uid int64, name string) (bool, error) {
  612. if len(name) == 0 {
  613. return false, nil
  614. }
  615. return e.
  616. Where("id!=?", uid).
  617. Get(&User{LowerName: strings.ToLower(name)})
  618. }
  619. // IsUserExist checks if given user name exist,
  620. // the user name should be noncased unique.
  621. // If uid is presented, then check will rule out that one,
  622. // it is used when update a user name in settings page.
  623. func IsUserExist(uid int64, name string) (bool, error) {
  624. return isUserExist(db.GetEngine(db.DefaultContext), uid, name)
  625. }
  626. // GetUserSalt returns a random user salt token.
  627. func GetUserSalt() (string, error) {
  628. return util.RandomString(10)
  629. }
  630. // NewGhostUser creates and returns a fake user for someone has deleted his/her account.
  631. func NewGhostUser() *User {
  632. return &User{
  633. ID: -1,
  634. Name: "Ghost",
  635. LowerName: "ghost",
  636. }
  637. }
  638. // NewReplaceUser creates and returns a fake user for external user
  639. func NewReplaceUser(name string) *User {
  640. return &User{
  641. ID: -1,
  642. Name: name,
  643. LowerName: strings.ToLower(name),
  644. }
  645. }
  646. // IsGhost check if user is fake user for a deleted account
  647. func (u *User) IsGhost() bool {
  648. if u == nil {
  649. return false
  650. }
  651. return u.ID == -1 && u.Name == "Ghost"
  652. }
  653. var (
  654. reservedUsernames = []string{
  655. ".",
  656. "..",
  657. ".well-known",
  658. "admin",
  659. "api",
  660. "assets",
  661. "attachments",
  662. "avatars",
  663. "captcha",
  664. "commits",
  665. "debug",
  666. "error",
  667. "explore",
  668. "favicon.ico",
  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. "serviceworker.js",
  688. "stars",
  689. "template",
  690. "user",
  691. }
  692. reservedUserPatterns = []string{"*.keys", "*.gpg", "*.rss", "*.atom"}
  693. )
  694. // isUsableName checks if name is reserved or pattern of name is not allowed
  695. // based on given reserved names and patterns.
  696. // Names are exact match, patterns can be prefix or suffix match with placeholder '*'.
  697. func isUsableName(names, patterns []string, name string) error {
  698. name = strings.TrimSpace(strings.ToLower(name))
  699. if utf8.RuneCountInString(name) == 0 {
  700. return ErrNameEmpty
  701. }
  702. for i := range names {
  703. if name == names[i] {
  704. return ErrNameReserved{name}
  705. }
  706. }
  707. for _, pat := range patterns {
  708. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  709. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  710. return ErrNamePatternNotAllowed{pat}
  711. }
  712. }
  713. return nil
  714. }
  715. // IsUsableUsername returns an error when a username is reserved
  716. func IsUsableUsername(name string) error {
  717. // Validate username make sure it satisfies requirement.
  718. if alphaDashDotPattern.MatchString(name) {
  719. // Note: usually this error is normally caught up earlier in the UI
  720. return ErrNameCharsNotAllowed{Name: name}
  721. }
  722. return isUsableName(reservedUsernames, reservedUserPatterns, name)
  723. }
  724. // CreateUserOverwriteOptions are an optional options who overwrite system defaults on user creation
  725. type CreateUserOverwriteOptions struct {
  726. Visibility structs.VisibleType
  727. }
  728. // CreateUser creates record of a new user.
  729. func CreateUser(u *User, overwriteDefault ...*CreateUserOverwriteOptions) (err error) {
  730. if err = IsUsableUsername(u.Name); err != nil {
  731. return err
  732. }
  733. // set system defaults
  734. u.KeepEmailPrivate = setting.Service.DefaultKeepEmailPrivate
  735. u.Visibility = setting.Service.DefaultUserVisibilityMode
  736. u.AllowCreateOrganization = setting.Service.DefaultAllowCreateOrganization && !setting.Admin.DisableRegularOrgCreation
  737. u.EmailNotificationsPreference = setting.Admin.DefaultEmailNotification
  738. u.MaxRepoCreation = -1
  739. u.Theme = setting.UI.DefaultTheme
  740. // overwrite defaults if set
  741. if len(overwriteDefault) != 0 && overwriteDefault[0] != nil {
  742. u.Visibility = overwriteDefault[0].Visibility
  743. }
  744. ctx, committer, err := db.TxContext()
  745. if err != nil {
  746. return err
  747. }
  748. defer committer.Close()
  749. sess := db.GetEngine(ctx)
  750. // validate data
  751. if err := validateUser(u); err != nil {
  752. return err
  753. }
  754. isExist, err := isUserExist(sess, 0, u.Name)
  755. if err != nil {
  756. return err
  757. } else if isExist {
  758. return ErrUserAlreadyExist{u.Name}
  759. }
  760. isExist, err = user_model.IsEmailUsed(ctx, u.Email)
  761. if err != nil {
  762. return err
  763. } else if isExist {
  764. return user_model.ErrEmailAlreadyUsed{
  765. Email: u.Email,
  766. }
  767. }
  768. // prepare for database
  769. u.LowerName = strings.ToLower(u.Name)
  770. u.AvatarEmail = u.Email
  771. if u.Rands, err = GetUserSalt(); err != nil {
  772. return err
  773. }
  774. if err = u.SetPassword(u.Passwd); err != nil {
  775. return err
  776. }
  777. // save changes to database
  778. if err = user_model.DeleteUserRedirect(ctx, u.Name); err != nil {
  779. return err
  780. }
  781. if err = db.Insert(ctx, u); err != nil {
  782. return err
  783. }
  784. // insert email address
  785. if err := db.Insert(ctx, &user_model.EmailAddress{
  786. UID: u.ID,
  787. Email: u.Email,
  788. LowerEmail: strings.ToLower(u.Email),
  789. IsActivated: u.IsActive,
  790. IsPrimary: true,
  791. }); err != nil {
  792. return err
  793. }
  794. return committer.Commit()
  795. }
  796. func countUsers(e db.Engine) int64 {
  797. count, _ := e.
  798. Where("type=0").
  799. Count(new(User))
  800. return count
  801. }
  802. // CountUsers returns number of users.
  803. func CountUsers() int64 {
  804. return countUsers(db.GetEngine(db.DefaultContext))
  805. }
  806. // get user by verify code
  807. func getVerifyUser(code string) (user *User) {
  808. if len(code) <= base.TimeLimitCodeLength {
  809. return nil
  810. }
  811. // use tail hex username query user
  812. hexStr := code[base.TimeLimitCodeLength:]
  813. if b, err := hex.DecodeString(hexStr); err == nil {
  814. if user, err = GetUserByName(string(b)); user != nil {
  815. return user
  816. }
  817. log.Error("user.getVerifyUser: %v", err)
  818. }
  819. return nil
  820. }
  821. // VerifyUserActiveCode verifies active code when active account
  822. func VerifyUserActiveCode(code string) (user *User) {
  823. minutes := setting.Service.ActiveCodeLives
  824. if user = getVerifyUser(code); user != nil {
  825. // time limit code
  826. prefix := code[:base.TimeLimitCodeLength]
  827. data := fmt.Sprintf("%d%s%s%s%s", user.ID, user.Email, user.LowerName, user.Passwd, user.Rands)
  828. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  829. return user
  830. }
  831. }
  832. return nil
  833. }
  834. // VerifyActiveEmailCode verifies active email code when active account
  835. func VerifyActiveEmailCode(code, email string) *user_model.EmailAddress {
  836. minutes := setting.Service.ActiveCodeLives
  837. if user := getVerifyUser(code); user != nil {
  838. // time limit code
  839. prefix := code[:base.TimeLimitCodeLength]
  840. data := fmt.Sprintf("%d%s%s%s%s", user.ID, email, user.LowerName, user.Passwd, user.Rands)
  841. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  842. emailAddress := &user_model.EmailAddress{UID: user.ID, Email: email}
  843. if has, _ := db.GetEngine(db.DefaultContext).Get(emailAddress); has {
  844. return emailAddress
  845. }
  846. }
  847. }
  848. return nil
  849. }
  850. // ChangeUserName changes all corresponding setting from old user name to new one.
  851. func ChangeUserName(u *User, newUserName string) (err error) {
  852. oldUserName := u.Name
  853. if err = IsUsableUsername(newUserName); err != nil {
  854. return err
  855. }
  856. ctx, committer, err := db.TxContext()
  857. if err != nil {
  858. return err
  859. }
  860. defer committer.Close()
  861. sess := db.GetEngine(ctx)
  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 = user_model.NewUserRedirect(ctx, u.ID, oldUserName, newUserName); err != nil {
  876. return err
  877. }
  878. if err = committer.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 db.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 user_model.ErrEmailAlreadyUsed{
  899. Email: u.Email,
  900. }
  901. }
  902. return nil
  903. }
  904. // validateUser check if user is valid to insert / update into database
  905. func validateUser(u *User) error {
  906. if !setting.Service.AllowedUserVisibilityModesSlice.IsAllowedVisibility(u.Visibility) && !u.IsOrganization() {
  907. return fmt.Errorf("visibility Mode not allowed: %s", u.Visibility.String())
  908. }
  909. u.Email = strings.ToLower(u.Email)
  910. return user_model.ValidateEmail(u.Email)
  911. }
  912. func updateUser(e db.Engine, u *User) error {
  913. if err := validateUser(u); err != nil {
  914. return err
  915. }
  916. _, err := e.ID(u.ID).AllCols().Update(u)
  917. return err
  918. }
  919. // UpdateUser updates user's information.
  920. func UpdateUser(u *User) error {
  921. return updateUser(db.GetEngine(db.DefaultContext), u)
  922. }
  923. // UpdateUserCols update user according special columns
  924. func UpdateUserCols(u *User, cols ...string) error {
  925. return updateUserCols(db.GetEngine(db.DefaultContext), u, cols...)
  926. }
  927. func updateUserCols(e db.Engine, u *User, cols ...string) error {
  928. if err := validateUser(u); err != nil {
  929. return err
  930. }
  931. _, err := e.ID(u.ID).Cols(cols...).Update(u)
  932. return err
  933. }
  934. // UpdateUserSetting updates user's settings.
  935. func UpdateUserSetting(u *User) (err error) {
  936. ctx, committer, err := db.TxContext()
  937. if err != nil {
  938. return err
  939. }
  940. defer committer.Close()
  941. sess := db.GetEngine(ctx)
  942. if !u.IsOrganization() {
  943. if err = checkDupEmail(sess, u); err != nil {
  944. return err
  945. }
  946. }
  947. if err = updateUser(sess, u); err != nil {
  948. return err
  949. }
  950. return committer.Commit()
  951. }
  952. // deleteBeans deletes all given beans, beans should contain delete conditions.
  953. func deleteBeans(e db.Engine, beans ...interface{}) (err error) {
  954. for i := range beans {
  955. if _, err = e.Delete(beans[i]); err != nil {
  956. return err
  957. }
  958. }
  959. return nil
  960. }
  961. // DeleteUser deletes models associated to an user.
  962. func DeleteUser(ctx context.Context, u *User) (err error) {
  963. e := db.GetEngine(ctx)
  964. // ***** START: Watch *****
  965. watchedRepoIDs := make([]int64, 0, 10)
  966. if err = e.Table("watch").Cols("watch.repo_id").
  967. Where("watch.user_id = ?", u.ID).And("watch.mode <>?", RepoWatchModeDont).Find(&watchedRepoIDs); err != nil {
  968. return fmt.Errorf("get all watches: %v", err)
  969. }
  970. if _, err = e.Decr("num_watches").In("id", watchedRepoIDs).NoAutoTime().Update(new(Repository)); err != nil {
  971. return fmt.Errorf("decrease repository num_watches: %v", err)
  972. }
  973. // ***** END: Watch *****
  974. // ***** START: Star *****
  975. starredRepoIDs := make([]int64, 0, 10)
  976. if err = e.Table("star").Cols("star.repo_id").
  977. Where("star.uid = ?", u.ID).Find(&starredRepoIDs); err != nil {
  978. return fmt.Errorf("get all stars: %v", err)
  979. } else if _, err = e.Decr("num_stars").In("id", starredRepoIDs).NoAutoTime().Update(new(Repository)); err != nil {
  980. return fmt.Errorf("decrease repository num_stars: %v", err)
  981. }
  982. // ***** END: Star *****
  983. // ***** START: Follow *****
  984. followeeIDs := make([]int64, 0, 10)
  985. if err = e.Table("follow").Cols("follow.follow_id").
  986. Where("follow.user_id = ?", u.ID).Find(&followeeIDs); err != nil {
  987. return fmt.Errorf("get all followees: %v", err)
  988. } else if _, err = e.Decr("num_followers").In("id", followeeIDs).Update(new(User)); err != nil {
  989. return fmt.Errorf("decrease user num_followers: %v", err)
  990. }
  991. followerIDs := make([]int64, 0, 10)
  992. if err = e.Table("follow").Cols("follow.user_id").
  993. Where("follow.follow_id = ?", u.ID).Find(&followerIDs); err != nil {
  994. return fmt.Errorf("get all followers: %v", err)
  995. } else if _, err = e.Decr("num_following").In("id", followerIDs).Update(new(User)); err != nil {
  996. return fmt.Errorf("decrease user num_following: %v", err)
  997. }
  998. // ***** END: Follow *****
  999. if err = deleteBeans(e,
  1000. &AccessToken{UID: u.ID},
  1001. &Collaboration{UserID: u.ID},
  1002. &Access{UserID: u.ID},
  1003. &Watch{UserID: u.ID},
  1004. &Star{UID: u.ID},
  1005. &user_model.Follow{UserID: u.ID},
  1006. &user_model.Follow{FollowID: u.ID},
  1007. &Action{UserID: u.ID},
  1008. &IssueUser{UID: u.ID},
  1009. &user_model.EmailAddress{UID: u.ID},
  1010. &user_model.UserOpenID{UID: u.ID},
  1011. &Reaction{UserID: u.ID},
  1012. &TeamUser{UID: u.ID},
  1013. &Collaboration{UserID: u.ID},
  1014. &Stopwatch{UserID: u.ID},
  1015. ); err != nil {
  1016. return fmt.Errorf("deleteBeans: %v", err)
  1017. }
  1018. if setting.Service.UserDeleteWithCommentsMaxTime != 0 &&
  1019. u.CreatedUnix.AsTime().Add(setting.Service.UserDeleteWithCommentsMaxTime).After(time.Now()) {
  1020. // Delete Comments
  1021. const batchSize = 50
  1022. for start := 0; ; start += batchSize {
  1023. comments := make([]*Comment, 0, batchSize)
  1024. if err = e.Where("type=? AND poster_id=?", CommentTypeComment, u.ID).Limit(batchSize, start).Find(&comments); err != nil {
  1025. return err
  1026. }
  1027. if len(comments) == 0 {
  1028. break
  1029. }
  1030. for _, comment := range comments {
  1031. if err = deleteComment(e, comment); err != nil {
  1032. return err
  1033. }
  1034. }
  1035. }
  1036. // Delete Reactions
  1037. if err = deleteReaction(e, &ReactionOptions{Doer: u}); err != nil {
  1038. return err
  1039. }
  1040. }
  1041. // ***** START: PublicKey *****
  1042. if _, err = e.Delete(&PublicKey{OwnerID: u.ID}); err != nil {
  1043. return fmt.Errorf("deletePublicKeys: %v", err)
  1044. }
  1045. err = rewriteAllPublicKeys(e)
  1046. if err != nil {
  1047. return err
  1048. }
  1049. err = rewriteAllPrincipalKeys(e)
  1050. if err != nil {
  1051. return err
  1052. }
  1053. // ***** END: PublicKey *****
  1054. // ***** START: GPGPublicKey *****
  1055. keys, err := listGPGKeys(e, u.ID, db.ListOptions{})
  1056. if err != nil {
  1057. return fmt.Errorf("ListGPGKeys: %v", err)
  1058. }
  1059. // Delete GPGKeyImport(s).
  1060. for _, key := range keys {
  1061. if _, err = e.Delete(&GPGKeyImport{KeyID: key.KeyID}); err != nil {
  1062. return fmt.Errorf("deleteGPGKeyImports: %v", err)
  1063. }
  1064. }
  1065. if _, err = e.Delete(&GPGKey{OwnerID: u.ID}); err != nil {
  1066. return fmt.Errorf("deleteGPGKeys: %v", err)
  1067. }
  1068. // ***** END: GPGPublicKey *****
  1069. // Clear assignee.
  1070. if err = clearAssigneeByUserID(e, u.ID); err != nil {
  1071. return fmt.Errorf("clear assignee: %v", err)
  1072. }
  1073. // ***** START: ExternalLoginUser *****
  1074. if err = removeAllAccountLinks(e, u); err != nil {
  1075. return fmt.Errorf("ExternalLoginUser: %v", err)
  1076. }
  1077. // ***** END: ExternalLoginUser *****
  1078. if _, err = e.ID(u.ID).Delete(new(User)); err != nil {
  1079. return fmt.Errorf("Delete: %v", err)
  1080. }
  1081. return nil
  1082. }
  1083. // GetInactiveUsers gets all inactive users
  1084. func GetInactiveUsers(ctx context.Context, olderThan time.Duration) ([]*User, error) {
  1085. var cond builder.Cond = builder.Eq{"is_active": false}
  1086. if olderThan > 0 {
  1087. cond = cond.And(builder.Lt{"created_unix": time.Now().Add(-olderThan).Unix()})
  1088. }
  1089. users := make([]*User, 0, 10)
  1090. return users, db.GetEngine(ctx).
  1091. Where(cond).
  1092. Find(&users)
  1093. }
  1094. // UserPath returns the path absolute path of user repositories.
  1095. func UserPath(userName string) string {
  1096. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  1097. }
  1098. func getUserByID(e db.Engine, id int64) (*User, error) {
  1099. u := new(User)
  1100. has, err := e.ID(id).Get(u)
  1101. if err != nil {
  1102. return nil, err
  1103. } else if !has {
  1104. return nil, ErrUserNotExist{id, "", 0}
  1105. }
  1106. return u, nil
  1107. }
  1108. // GetUserByID returns the user object by given ID if exists.
  1109. func GetUserByID(id int64) (*User, error) {
  1110. return GetUserByIDCtx(db.DefaultContext, id)
  1111. }
  1112. // GetUserByIDCtx returns the user object by given ID if exists.
  1113. func GetUserByIDCtx(ctx context.Context, id int64) (*User, error) {
  1114. return getUserByID(db.GetEngine(ctx), id)
  1115. }
  1116. // GetUserByName returns user by given name.
  1117. func GetUserByName(name string) (*User, error) {
  1118. return getUserByName(db.GetEngine(db.DefaultContext), name)
  1119. }
  1120. func getUserByName(e db.Engine, name string) (*User, error) {
  1121. if len(name) == 0 {
  1122. return nil, ErrUserNotExist{0, name, 0}
  1123. }
  1124. u := &User{LowerName: strings.ToLower(name)}
  1125. has, err := e.Get(u)
  1126. if err != nil {
  1127. return nil, err
  1128. } else if !has {
  1129. return nil, ErrUserNotExist{0, name, 0}
  1130. }
  1131. return u, nil
  1132. }
  1133. // GetUserEmailsByNames returns a list of e-mails corresponds to names of users
  1134. // that have their email notifications set to enabled or onmention.
  1135. func GetUserEmailsByNames(names []string) []string {
  1136. return getUserEmailsByNames(db.GetEngine(db.DefaultContext), names)
  1137. }
  1138. func getUserEmailsByNames(e db.Engine, names []string) []string {
  1139. mails := make([]string, 0, len(names))
  1140. for _, name := range names {
  1141. u, err := getUserByName(e, name)
  1142. if err != nil {
  1143. continue
  1144. }
  1145. if u.IsMailable() && u.EmailNotifications() != EmailNotificationsDisabled {
  1146. mails = append(mails, u.Email)
  1147. }
  1148. }
  1149. return mails
  1150. }
  1151. // GetMaileableUsersByIDs gets users from ids, but only if they can receive mails
  1152. func GetMaileableUsersByIDs(ids []int64, isMention bool) ([]*User, error) {
  1153. if len(ids) == 0 {
  1154. return nil, nil
  1155. }
  1156. ous := make([]*User, 0, len(ids))
  1157. if isMention {
  1158. return ous, db.GetEngine(db.DefaultContext).In("id", ids).
  1159. Where("`type` = ?", UserTypeIndividual).
  1160. And("`prohibit_login` = ?", false).
  1161. And("`is_active` = ?", true).
  1162. And("`email_notifications_preference` IN ( ?, ?)", EmailNotificationsEnabled, EmailNotificationsOnMention).
  1163. Find(&ous)
  1164. }
  1165. return ous, db.GetEngine(db.DefaultContext).In("id", ids).
  1166. Where("`type` = ?", UserTypeIndividual).
  1167. And("`prohibit_login` = ?", false).
  1168. And("`is_active` = ?", true).
  1169. And("`email_notifications_preference` = ?", EmailNotificationsEnabled).
  1170. Find(&ous)
  1171. }
  1172. // GetUserNamesByIDs returns usernames for all resolved users from a list of Ids.
  1173. func GetUserNamesByIDs(ids []int64) ([]string, error) {
  1174. unames := make([]string, 0, len(ids))
  1175. err := db.GetEngine(db.DefaultContext).In("id", ids).
  1176. Table("user").
  1177. Asc("name").
  1178. Cols("name").
  1179. Find(&unames)
  1180. return unames, err
  1181. }
  1182. // GetUsersByIDs returns all resolved users from a list of Ids.
  1183. func GetUsersByIDs(ids []int64) (UserList, error) {
  1184. ous := make([]*User, 0, len(ids))
  1185. if len(ids) == 0 {
  1186. return ous, nil
  1187. }
  1188. err := db.GetEngine(db.DefaultContext).In("id", ids).
  1189. Asc("name").
  1190. Find(&ous)
  1191. return ous, err
  1192. }
  1193. // GetUserIDsByNames returns a slice of ids corresponds to names.
  1194. func GetUserIDsByNames(names []string, ignoreNonExistent bool) ([]int64, error) {
  1195. ids := make([]int64, 0, len(names))
  1196. for _, name := range names {
  1197. u, err := GetUserByName(name)
  1198. if err != nil {
  1199. if ignoreNonExistent {
  1200. continue
  1201. } else {
  1202. return nil, err
  1203. }
  1204. }
  1205. ids = append(ids, u.ID)
  1206. }
  1207. return ids, nil
  1208. }
  1209. // GetUsersBySource returns a list of Users for a login source
  1210. func GetUsersBySource(s *login.Source) ([]*User, error) {
  1211. var users []*User
  1212. err := db.GetEngine(db.DefaultContext).Where("login_type = ? AND login_source = ?", s.Type, s.ID).Find(&users)
  1213. return users, err
  1214. }
  1215. // UserCommit represents a commit with validation of user.
  1216. type UserCommit struct {
  1217. User *User
  1218. *git.Commit
  1219. }
  1220. // ValidateCommitWithEmail check if author's e-mail of commit is corresponding to a user.
  1221. func ValidateCommitWithEmail(c *git.Commit) *User {
  1222. if c.Author == nil {
  1223. return nil
  1224. }
  1225. u, err := GetUserByEmail(c.Author.Email)
  1226. if err != nil {
  1227. return nil
  1228. }
  1229. return u
  1230. }
  1231. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  1232. func ValidateCommitsWithEmails(oldCommits []*git.Commit) []*UserCommit {
  1233. var (
  1234. emails = make(map[string]*User)
  1235. newCommits = make([]*UserCommit, 0, len(oldCommits))
  1236. )
  1237. for _, c := range oldCommits {
  1238. var u *User
  1239. if c.Author != nil {
  1240. if v, ok := emails[c.Author.Email]; !ok {
  1241. u, _ = GetUserByEmail(c.Author.Email)
  1242. emails[c.Author.Email] = u
  1243. } else {
  1244. u = v
  1245. }
  1246. }
  1247. newCommits = append(newCommits, &UserCommit{
  1248. User: u,
  1249. Commit: c,
  1250. })
  1251. }
  1252. return newCommits
  1253. }
  1254. // GetUserByEmail returns the user object by given e-mail if exists.
  1255. func GetUserByEmail(email string) (*User, error) {
  1256. return GetUserByEmailContext(db.DefaultContext, email)
  1257. }
  1258. // GetUserByEmailContext returns the user object by given e-mail if exists with db context
  1259. func GetUserByEmailContext(ctx context.Context, email string) (*User, error) {
  1260. if len(email) == 0 {
  1261. return nil, ErrUserNotExist{0, email, 0}
  1262. }
  1263. email = strings.ToLower(email)
  1264. // First try to find the user by primary email
  1265. user := &User{Email: email}
  1266. has, err := db.GetEngine(ctx).Get(user)
  1267. if err != nil {
  1268. return nil, err
  1269. }
  1270. if has {
  1271. return user, nil
  1272. }
  1273. // Otherwise, check in alternative list for activated email addresses
  1274. emailAddress := &user_model.EmailAddress{Email: email, IsActivated: true}
  1275. has, err = db.GetEngine(ctx).Get(emailAddress)
  1276. if err != nil {
  1277. return nil, err
  1278. }
  1279. if has {
  1280. return GetUserByIDCtx(ctx, emailAddress.UID)
  1281. }
  1282. // Finally, if email address is the protected email address:
  1283. if strings.HasSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress)) {
  1284. username := strings.TrimSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress))
  1285. user := &User{}
  1286. has, err := db.GetEngine(ctx).Where("lower_name=?", username).Get(user)
  1287. if err != nil {
  1288. return nil, err
  1289. }
  1290. if has {
  1291. return user, nil
  1292. }
  1293. }
  1294. return nil, ErrUserNotExist{0, email, 0}
  1295. }
  1296. // GetUser checks if a user already exists
  1297. func GetUser(user *User) (bool, error) {
  1298. return db.GetEngine(db.DefaultContext).Get(user)
  1299. }
  1300. // SearchUserOptions contains the options for searching
  1301. type SearchUserOptions struct {
  1302. db.ListOptions
  1303. Keyword string
  1304. Type UserType
  1305. UID int64
  1306. OrderBy SearchOrderBy
  1307. Visible []structs.VisibleType
  1308. Actor *User // The user doing the search
  1309. SearchByEmail bool // Search by email as well as username/full name
  1310. IsActive util.OptionalBool
  1311. IsAdmin util.OptionalBool
  1312. IsRestricted util.OptionalBool
  1313. IsTwoFactorEnabled util.OptionalBool
  1314. IsProhibitLogin util.OptionalBool
  1315. }
  1316. func (opts *SearchUserOptions) toSearchQueryBase() *xorm.Session {
  1317. var cond builder.Cond = builder.Eq{"type": opts.Type}
  1318. if len(opts.Keyword) > 0 {
  1319. lowerKeyword := strings.ToLower(opts.Keyword)
  1320. keywordCond := builder.Or(
  1321. builder.Like{"lower_name", lowerKeyword},
  1322. builder.Like{"LOWER(full_name)", lowerKeyword},
  1323. )
  1324. if opts.SearchByEmail {
  1325. keywordCond = keywordCond.Or(builder.Like{"LOWER(email)", lowerKeyword})
  1326. }
  1327. cond = cond.And(keywordCond)
  1328. }
  1329. // If visibility filtered
  1330. if len(opts.Visible) > 0 {
  1331. cond = cond.And(builder.In("visibility", opts.Visible))
  1332. }
  1333. if opts.Actor != nil {
  1334. var exprCond builder.Cond = builder.Expr("org_user.org_id = `user`.id")
  1335. // If Admin - they see all users!
  1336. if !opts.Actor.IsAdmin {
  1337. // Force visibility for privacy
  1338. var accessCond builder.Cond
  1339. if !opts.Actor.IsRestricted {
  1340. accessCond = builder.Or(
  1341. 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}))),
  1342. builder.In("visibility", structs.VisibleTypePublic, structs.VisibleTypeLimited))
  1343. } else {
  1344. // restricted users only see orgs they are a member of
  1345. accessCond = builder.In("id", builder.Select("org_id").From("org_user").LeftJoin("`user`", exprCond).Where(builder.And(builder.Eq{"uid": opts.Actor.ID})))
  1346. }
  1347. // Don't forget about self
  1348. accessCond = accessCond.Or(builder.Eq{"id": opts.Actor.ID})
  1349. cond = cond.And(accessCond)
  1350. }
  1351. } else {
  1352. // Force visibility for privacy
  1353. // Not logged in - only public users
  1354. cond = cond.And(builder.In("visibility", structs.VisibleTypePublic))
  1355. }
  1356. if opts.UID > 0 {
  1357. cond = cond.And(builder.Eq{"id": opts.UID})
  1358. }
  1359. if !opts.IsActive.IsNone() {
  1360. cond = cond.And(builder.Eq{"is_active": opts.IsActive.IsTrue()})
  1361. }
  1362. if !opts.IsAdmin.IsNone() {
  1363. cond = cond.And(builder.Eq{"is_admin": opts.IsAdmin.IsTrue()})
  1364. }
  1365. if !opts.IsRestricted.IsNone() {
  1366. cond = cond.And(builder.Eq{"is_restricted": opts.IsRestricted.IsTrue()})
  1367. }
  1368. if !opts.IsProhibitLogin.IsNone() {
  1369. cond = cond.And(builder.Eq{"prohibit_login": opts.IsProhibitLogin.IsTrue()})
  1370. }
  1371. e := db.GetEngine(db.DefaultContext)
  1372. if opts.IsTwoFactorEnabled.IsNone() {
  1373. return e.Where(cond)
  1374. }
  1375. // 2fa filter uses LEFT JOIN to check whether a user has a 2fa record
  1376. // TODO: bad performance here, maybe there will be a column "is_2fa_enabled" in the future
  1377. if opts.IsTwoFactorEnabled.IsTrue() {
  1378. cond = cond.And(builder.Expr("two_factor.uid IS NOT NULL"))
  1379. } else {
  1380. cond = cond.And(builder.Expr("two_factor.uid IS NULL"))
  1381. }
  1382. return e.Join("LEFT OUTER", "two_factor", "two_factor.uid = `user`.id").
  1383. Where(cond)
  1384. }
  1385. // SearchUsers takes options i.e. keyword and part of user name to search,
  1386. // it returns results in given range and number of total results.
  1387. func SearchUsers(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  1388. sessCount := opts.toSearchQueryBase()
  1389. defer sessCount.Close()
  1390. count, err := sessCount.Count(new(User))
  1391. if err != nil {
  1392. return nil, 0, fmt.Errorf("Count: %v", err)
  1393. }
  1394. if len(opts.OrderBy) == 0 {
  1395. opts.OrderBy = SearchOrderByAlphabetically
  1396. }
  1397. sessQuery := opts.toSearchQueryBase().OrderBy(opts.OrderBy.String())
  1398. defer sessQuery.Close()
  1399. if opts.Page != 0 {
  1400. sessQuery = db.SetSessionPagination(sessQuery, opts)
  1401. }
  1402. // the sql may contain JOIN, so we must only select User related columns
  1403. sessQuery = sessQuery.Select("`user`.*")
  1404. users = make([]*User, 0, opts.PageSize)
  1405. return users, count, sessQuery.Find(&users)
  1406. }
  1407. // GetStarredRepos returns the repos starred by a particular user
  1408. func GetStarredRepos(userID int64, private bool, listOptions db.ListOptions) ([]*Repository, error) {
  1409. sess := db.GetEngine(db.DefaultContext).Where("star.uid=?", userID).
  1410. Join("LEFT", "star", "`repository`.id=`star`.repo_id")
  1411. if !private {
  1412. sess = sess.And("is_private=?", false)
  1413. }
  1414. if listOptions.Page != 0 {
  1415. sess = db.SetSessionPagination(sess, &listOptions)
  1416. repos := make([]*Repository, 0, listOptions.PageSize)
  1417. return repos, sess.Find(&repos)
  1418. }
  1419. repos := make([]*Repository, 0, 10)
  1420. return repos, sess.Find(&repos)
  1421. }
  1422. // GetWatchedRepos returns the repos watched by a particular user
  1423. func GetWatchedRepos(userID int64, private bool, listOptions db.ListOptions) ([]*Repository, int64, error) {
  1424. sess := db.GetEngine(db.DefaultContext).Where("watch.user_id=?", userID).
  1425. And("`watch`.mode<>?", RepoWatchModeDont).
  1426. Join("LEFT", "watch", "`repository`.id=`watch`.repo_id")
  1427. if !private {
  1428. sess = sess.And("is_private=?", false)
  1429. }
  1430. if listOptions.Page != 0 {
  1431. sess = db.SetSessionPagination(sess, &listOptions)
  1432. repos := make([]*Repository, 0, listOptions.PageSize)
  1433. total, err := sess.FindAndCount(&repos)
  1434. return repos, total, err
  1435. }
  1436. repos := make([]*Repository, 0, 10)
  1437. total, err := sess.FindAndCount(&repos)
  1438. return repos, total, err
  1439. }
  1440. // IterateUser iterate users
  1441. func IterateUser(f func(user *User) error) error {
  1442. var start int
  1443. batchSize := setting.Database.IterateBufferSize
  1444. for {
  1445. users := make([]*User, 0, batchSize)
  1446. if err := db.GetEngine(db.DefaultContext).Limit(batchSize, start).Find(&users); err != nil {
  1447. return err
  1448. }
  1449. if len(users) == 0 {
  1450. return nil
  1451. }
  1452. start += len(users)
  1453. for _, user := range users {
  1454. if err := f(user); err != nil {
  1455. return err
  1456. }
  1457. }
  1458. }
  1459. }
  1460. // GetUserByOpenID returns the user object by given OpenID if exists.
  1461. func GetUserByOpenID(uri string) (*User, error) {
  1462. if len(uri) == 0 {
  1463. return nil, ErrUserNotExist{0, uri, 0}
  1464. }
  1465. uri, err := openid.Normalize(uri)
  1466. if err != nil {
  1467. return nil, err
  1468. }
  1469. log.Trace("Normalized OpenID URI: " + uri)
  1470. // Otherwise, check in openid table
  1471. oid := &user_model.UserOpenID{}
  1472. has, err := db.GetEngine(db.DefaultContext).Where("uri=?", uri).Get(oid)
  1473. if err != nil {
  1474. return nil, err
  1475. }
  1476. if has {
  1477. return GetUserByID(oid.UID)
  1478. }
  1479. return nil, ErrUserNotExist{0, uri, 0}
  1480. }
  1481. // GetAdminUser returns the first administrator
  1482. func GetAdminUser() (*User, error) {
  1483. var admin User
  1484. has, err := db.GetEngine(db.DefaultContext).Where("is_admin=?", true).Get(&admin)
  1485. if err != nil {
  1486. return nil, err
  1487. } else if !has {
  1488. return nil, ErrUserNotExist{}
  1489. }
  1490. return &admin, nil
  1491. }