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

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