Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

user.go 31KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154
  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 user
  6. import (
  7. "context"
  8. "crypto/sha256"
  9. "crypto/subtle"
  10. "encoding/hex"
  11. "fmt"
  12. "net/url"
  13. "os"
  14. "path/filepath"
  15. "strings"
  16. "time"
  17. _ "image/jpeg" // Needed for jpeg support
  18. "code.gitea.io/gitea/models/auth"
  19. "code.gitea.io/gitea/models/db"
  20. "code.gitea.io/gitea/modules/auth/openid"
  21. "code.gitea.io/gitea/modules/base"
  22. "code.gitea.io/gitea/modules/git"
  23. "code.gitea.io/gitea/modules/log"
  24. "code.gitea.io/gitea/modules/setting"
  25. "code.gitea.io/gitea/modules/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 //revive:disable-line:exported
  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. // User represents the object of individual and member of organization.
  64. type User struct {
  65. ID int64 `xorm:"pk autoincr"`
  66. LowerName string `xorm:"UNIQUE NOT NULL"`
  67. Name string `xorm:"UNIQUE NOT NULL"`
  68. FullName string
  69. // Email is the primary email address (to be used for communication)
  70. Email string `xorm:"NOT NULL"`
  71. KeepEmailPrivate bool
  72. EmailNotificationsPreference string `xorm:"VARCHAR(20) NOT NULL DEFAULT 'enabled'"`
  73. Passwd string `xorm:"NOT NULL"`
  74. PasswdHashAlgo string `xorm:"NOT NULL DEFAULT 'argon2'"`
  75. // MustChangePassword is an attribute that determines if a user
  76. // is to change his/her password after registration.
  77. MustChangePassword bool `xorm:"NOT NULL DEFAULT false"`
  78. LoginType auth.Type
  79. LoginSource int64 `xorm:"NOT NULL DEFAULT 0"`
  80. LoginName string
  81. Type UserType
  82. Location string
  83. Website string
  84. Rands string `xorm:"VARCHAR(10)"`
  85. Salt string `xorm:"VARCHAR(10)"`
  86. Language string `xorm:"VARCHAR(5)"`
  87. Description string
  88. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  89. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  90. LastLoginUnix timeutil.TimeStamp `xorm:"INDEX"`
  91. // Remember visibility choice for convenience, true for private
  92. LastRepoVisibility bool
  93. // Maximum repository creation limit, -1 means use global default
  94. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1"`
  95. // IsActive true: primary email is activated, user can access Web UI and Git SSH.
  96. // false: an inactive user can only log in Web UI for account operations (ex: activate the account by email), no other access.
  97. IsActive bool `xorm:"INDEX"`
  98. // the user is a Gitea admin, who can access all repositories and the admin pages.
  99. IsAdmin bool
  100. // true: the user is only allowed to see organizations/repositories that they has explicit rights to.
  101. // (ex: in private Gitea instances user won't be allowed to see even organizations/repositories that are set as public)
  102. IsRestricted bool `xorm:"NOT NULL DEFAULT false"`
  103. AllowGitHook bool
  104. AllowImportLocal bool // Allow migrate repository by local path
  105. AllowCreateOrganization bool `xorm:"DEFAULT true"`
  106. // 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)
  107. ProhibitLogin bool `xorm:"NOT NULL DEFAULT false"`
  108. // Avatar
  109. Avatar string `xorm:"VARCHAR(2048) NOT NULL"`
  110. AvatarEmail string `xorm:"NOT NULL"`
  111. UseCustomAvatar bool
  112. // Counters
  113. NumFollowers int
  114. NumFollowing int `xorm:"NOT NULL DEFAULT 0"`
  115. NumStars int
  116. NumRepos int
  117. // For organization
  118. NumTeams int
  119. NumMembers int
  120. Visibility structs.VisibleType `xorm:"NOT NULL DEFAULT 0"`
  121. RepoAdminChangeTeamAccess bool `xorm:"NOT NULL DEFAULT false"`
  122. // Preferences
  123. DiffViewStyle string `xorm:"NOT NULL DEFAULT ''"`
  124. Theme string `xorm:"NOT NULL DEFAULT ''"`
  125. KeepActivityPrivate bool `xorm:"NOT NULL DEFAULT false"`
  126. }
  127. func init() {
  128. db.RegisterModel(new(User))
  129. }
  130. // SearchOrganizationsOptions options to filter organizations
  131. type SearchOrganizationsOptions struct {
  132. db.ListOptions
  133. All bool
  134. }
  135. // ColorFormat writes a colored string to identify this struct
  136. func (u *User) ColorFormat(s fmt.State) {
  137. if u == nil {
  138. log.ColorFprintf(s, "%d:%s",
  139. log.NewColoredIDValue(0),
  140. log.NewColoredValue("<nil>"))
  141. return
  142. }
  143. log.ColorFprintf(s, "%d:%s",
  144. log.NewColoredIDValue(u.ID),
  145. log.NewColoredValue(u.Name))
  146. }
  147. // BeforeUpdate is invoked from XORM before updating this object.
  148. func (u *User) BeforeUpdate() {
  149. if u.MaxRepoCreation < -1 {
  150. u.MaxRepoCreation = -1
  151. }
  152. // Organization does not need email
  153. u.Email = strings.ToLower(u.Email)
  154. if !u.IsOrganization() {
  155. if len(u.AvatarEmail) == 0 {
  156. u.AvatarEmail = u.Email
  157. }
  158. }
  159. u.LowerName = strings.ToLower(u.Name)
  160. u.Location = base.TruncateString(u.Location, 255)
  161. u.Website = base.TruncateString(u.Website, 255)
  162. u.Description = base.TruncateString(u.Description, 255)
  163. }
  164. // AfterLoad is invoked from XORM after filling all the fields of this object.
  165. func (u *User) AfterLoad() {
  166. if u.Theme == "" {
  167. u.Theme = setting.UI.DefaultTheme
  168. }
  169. }
  170. // SetLastLogin set time to last login
  171. func (u *User) SetLastLogin() {
  172. u.LastLoginUnix = timeutil.TimeStampNow()
  173. }
  174. // UpdateUserDiffViewStyle updates the users diff view style
  175. func UpdateUserDiffViewStyle(u *User, style string) error {
  176. u.DiffViewStyle = style
  177. return UpdateUserCols(db.DefaultContext, u, "diff_view_style")
  178. }
  179. // UpdateUserTheme updates a users' theme irrespective of the site wide theme
  180. func UpdateUserTheme(u *User, themeName string) error {
  181. u.Theme = themeName
  182. return UpdateUserCols(db.DefaultContext, u, "theme")
  183. }
  184. // GetEmail returns an noreply email, if the user has set to keep his
  185. // email address private, otherwise the primary email address.
  186. func (u *User) GetEmail() string {
  187. if u.KeepEmailPrivate {
  188. return fmt.Sprintf("%s@%s", u.LowerName, setting.Service.NoReplyAddress)
  189. }
  190. return u.Email
  191. }
  192. // GetAllUsers returns a slice of all individual users found in DB.
  193. func GetAllUsers() ([]*User, error) {
  194. users := make([]*User, 0)
  195. return users, db.GetEngine(db.DefaultContext).OrderBy("id").Where("type = ?", UserTypeIndividual).Find(&users)
  196. }
  197. // IsLocal returns true if user login type is LoginPlain.
  198. func (u *User) IsLocal() bool {
  199. return u.LoginType <= auth.Plain
  200. }
  201. // IsOAuth2 returns true if user login type is LoginOAuth2.
  202. func (u *User) IsOAuth2() bool {
  203. return u.LoginType == auth.OAuth2
  204. }
  205. // MaxCreationLimit returns the number of repositories a user is allowed to create
  206. func (u *User) MaxCreationLimit() int {
  207. if u.MaxRepoCreation <= -1 {
  208. return setting.Repository.MaxCreationLimit
  209. }
  210. return u.MaxRepoCreation
  211. }
  212. // CanCreateRepo returns if user login can create a repository
  213. // NOTE: functions calling this assume a failure due to repository count limit; if new checks are added, those functions should be revised
  214. func (u *User) CanCreateRepo() bool {
  215. if u.IsAdmin {
  216. return true
  217. }
  218. if u.MaxRepoCreation <= -1 {
  219. if setting.Repository.MaxCreationLimit <= -1 {
  220. return true
  221. }
  222. return u.NumRepos < setting.Repository.MaxCreationLimit
  223. }
  224. return u.NumRepos < u.MaxRepoCreation
  225. }
  226. // CanCreateOrganization returns true if user can create organisation.
  227. func (u *User) CanCreateOrganization() bool {
  228. return u.IsAdmin || (u.AllowCreateOrganization && !setting.Admin.DisableRegularOrgCreation)
  229. }
  230. // CanEditGitHook returns true if user can edit Git hooks.
  231. func (u *User) CanEditGitHook() bool {
  232. return !setting.DisableGitHooks && (u.IsAdmin || u.AllowGitHook)
  233. }
  234. // CanImportLocal returns true if user can migrate repository by local path.
  235. func (u *User) CanImportLocal() bool {
  236. if !setting.ImportLocalPaths || u == nil {
  237. return false
  238. }
  239. return u.IsAdmin || u.AllowImportLocal
  240. }
  241. // DashboardLink returns the user dashboard page link.
  242. func (u *User) DashboardLink() string {
  243. if u.IsOrganization() {
  244. return u.OrganisationLink() + "/dashboard"
  245. }
  246. return setting.AppSubURL + "/"
  247. }
  248. // HomeLink returns the user or organization home page link.
  249. func (u *User) HomeLink() string {
  250. return setting.AppSubURL + "/" + url.PathEscape(u.Name)
  251. }
  252. // HTMLURL returns the user or organization's full link.
  253. func (u *User) HTMLURL() string {
  254. return setting.AppURL + url.PathEscape(u.Name)
  255. }
  256. // OrganisationLink returns the organization sub page link.
  257. func (u *User) OrganisationLink() string {
  258. return setting.AppSubURL + "/org/" + url.PathEscape(u.Name)
  259. }
  260. // GenerateEmailActivateCode generates an activate code based on user information and given e-mail.
  261. func (u *User) GenerateEmailActivateCode(email string) string {
  262. code := base.CreateTimeLimitCode(
  263. fmt.Sprintf("%d%s%s%s%s", u.ID, email, u.LowerName, u.Passwd, u.Rands),
  264. setting.Service.ActiveCodeLives, nil)
  265. // Add tail hex username
  266. code += hex.EncodeToString([]byte(u.LowerName))
  267. return code
  268. }
  269. // GetUserFollowers returns range of user's followers.
  270. func GetUserFollowers(u *User, listOptions db.ListOptions) ([]*User, error) {
  271. sess := db.GetEngine(db.DefaultContext).
  272. Where("follow.follow_id=?", u.ID).
  273. Join("LEFT", "follow", "`user`.id=follow.user_id")
  274. if listOptions.Page != 0 {
  275. sess = db.SetSessionPagination(sess, &listOptions)
  276. users := make([]*User, 0, listOptions.PageSize)
  277. return users, sess.Find(&users)
  278. }
  279. users := make([]*User, 0, 8)
  280. return users, sess.Find(&users)
  281. }
  282. // GetUserFollowing returns range of user's following.
  283. func GetUserFollowing(u *User, listOptions db.ListOptions) ([]*User, error) {
  284. sess := db.GetEngine(db.DefaultContext).
  285. Where("follow.user_id=?", u.ID).
  286. Join("LEFT", "follow", "`user`.id=follow.follow_id")
  287. if listOptions.Page != 0 {
  288. sess = db.SetSessionPagination(sess, &listOptions)
  289. users := make([]*User, 0, listOptions.PageSize)
  290. return users, sess.Find(&users)
  291. }
  292. users := make([]*User, 0, 8)
  293. return users, sess.Find(&users)
  294. }
  295. // NewGitSig generates and returns the signature of given user.
  296. func (u *User) NewGitSig() *git.Signature {
  297. return &git.Signature{
  298. Name: u.GitName(),
  299. Email: u.GetEmail(),
  300. When: time.Now(),
  301. }
  302. }
  303. func hashPassword(passwd, salt, algo string) string {
  304. var tempPasswd []byte
  305. switch algo {
  306. case algoBcrypt:
  307. tempPasswd, _ = bcrypt.GenerateFromPassword([]byte(passwd), bcrypt.DefaultCost)
  308. return string(tempPasswd)
  309. case algoScrypt:
  310. tempPasswd, _ = scrypt.Key([]byte(passwd), []byte(salt), 65536, 16, 2, 50)
  311. case algoArgon2:
  312. tempPasswd = argon2.IDKey([]byte(passwd), []byte(salt), 2, 65536, 8, 50)
  313. case algoPbkdf2:
  314. fallthrough
  315. default:
  316. tempPasswd = pbkdf2.Key([]byte(passwd), []byte(salt), 10000, 50, sha256.New)
  317. }
  318. return fmt.Sprintf("%x", tempPasswd)
  319. }
  320. // SetPassword hashes a password using the algorithm defined in the config value of PASSWORD_HASH_ALGO
  321. // change passwd, salt and passwd_hash_algo fields
  322. func (u *User) SetPassword(passwd string) (err error) {
  323. if len(passwd) == 0 {
  324. u.Passwd = ""
  325. u.Salt = ""
  326. u.PasswdHashAlgo = ""
  327. return nil
  328. }
  329. if u.Salt, err = GetUserSalt(); err != nil {
  330. return err
  331. }
  332. u.PasswdHashAlgo = setting.PasswordHashAlgo
  333. u.Passwd = hashPassword(passwd, u.Salt, setting.PasswordHashAlgo)
  334. return nil
  335. }
  336. // ValidatePassword checks if given password matches the one belongs to the user.
  337. func (u *User) ValidatePassword(passwd string) bool {
  338. tempHash := hashPassword(passwd, u.Salt, u.PasswdHashAlgo)
  339. if u.PasswdHashAlgo != algoBcrypt && subtle.ConstantTimeCompare([]byte(u.Passwd), []byte(tempHash)) == 1 {
  340. return true
  341. }
  342. if u.PasswdHashAlgo == algoBcrypt && bcrypt.CompareHashAndPassword([]byte(u.Passwd), []byte(passwd)) == nil {
  343. return true
  344. }
  345. return false
  346. }
  347. // IsPasswordSet checks if the password is set or left empty
  348. func (u *User) IsPasswordSet() bool {
  349. return len(u.Passwd) != 0
  350. }
  351. // IsOrganization returns true if user is actually a organization.
  352. func (u *User) IsOrganization() bool {
  353. return u.Type == UserTypeOrganization
  354. }
  355. // DisplayName returns full name if it's not empty,
  356. // returns username otherwise.
  357. func (u *User) DisplayName() string {
  358. trimmed := strings.TrimSpace(u.FullName)
  359. if len(trimmed) > 0 {
  360. return trimmed
  361. }
  362. return u.Name
  363. }
  364. // GetDisplayName returns full name if it's not empty and DEFAULT_SHOW_FULL_NAME is set,
  365. // returns username otherwise.
  366. func (u *User) GetDisplayName() string {
  367. if setting.UI.DefaultShowFullName {
  368. trimmed := strings.TrimSpace(u.FullName)
  369. if len(trimmed) > 0 {
  370. return trimmed
  371. }
  372. }
  373. return u.Name
  374. }
  375. func gitSafeName(name string) string {
  376. return strings.TrimSpace(strings.NewReplacer("\n", "", "<", "", ">", "").Replace(name))
  377. }
  378. // GitName returns a git safe name
  379. func (u *User) GitName() string {
  380. gitName := gitSafeName(u.FullName)
  381. if len(gitName) > 0 {
  382. return gitName
  383. }
  384. // Although u.Name should be safe if created in our system
  385. // LDAP users may have bad names
  386. gitName = gitSafeName(u.Name)
  387. if len(gitName) > 0 {
  388. return gitName
  389. }
  390. // Totally pathological name so it's got to be:
  391. return fmt.Sprintf("user-%d", u.ID)
  392. }
  393. // ShortName ellipses username to length
  394. func (u *User) ShortName(length int) string {
  395. return base.EllipsisString(u.Name, length)
  396. }
  397. // IsMailable checks if a user is eligible
  398. // to receive emails.
  399. func (u *User) IsMailable() bool {
  400. return u.IsActive
  401. }
  402. // EmailNotifications returns the User's email notification preference
  403. func (u *User) EmailNotifications() string {
  404. return u.EmailNotificationsPreference
  405. }
  406. // SetEmailNotifications sets the user's email notification preference
  407. func SetEmailNotifications(u *User, set string) error {
  408. u.EmailNotificationsPreference = set
  409. if err := UpdateUserCols(db.DefaultContext, u, "email_notifications_preference"); err != nil {
  410. log.Error("SetEmailNotifications: %v", err)
  411. return err
  412. }
  413. return nil
  414. }
  415. func isUserExist(e db.Engine, uid int64, name string) (bool, error) {
  416. if len(name) == 0 {
  417. return false, nil
  418. }
  419. return e.
  420. Where("id!=?", uid).
  421. Get(&User{LowerName: strings.ToLower(name)})
  422. }
  423. // IsUserExist checks if given user name exist,
  424. // the user name should be noncased unique.
  425. // If uid is presented, then check will rule out that one,
  426. // it is used when update a user name in settings page.
  427. func IsUserExist(uid int64, name string) (bool, error) {
  428. return isUserExist(db.GetEngine(db.DefaultContext), uid, name)
  429. }
  430. // GetUserSalt returns a random user salt token.
  431. func GetUserSalt() (string, error) {
  432. return util.RandomString(10)
  433. }
  434. // NewGhostUser creates and returns a fake user for someone has deleted his/her account.
  435. func NewGhostUser() *User {
  436. return &User{
  437. ID: -1,
  438. Name: "Ghost",
  439. LowerName: "ghost",
  440. }
  441. }
  442. // NewReplaceUser creates and returns a fake user for external user
  443. func NewReplaceUser(name string) *User {
  444. return &User{
  445. ID: -1,
  446. Name: name,
  447. LowerName: strings.ToLower(name),
  448. }
  449. }
  450. // IsGhost check if user is fake user for a deleted account
  451. func (u *User) IsGhost() bool {
  452. if u == nil {
  453. return false
  454. }
  455. return u.ID == -1 && u.Name == "Ghost"
  456. }
  457. var (
  458. reservedUsernames = []string{
  459. ".",
  460. "..",
  461. ".well-known",
  462. "admin",
  463. "api",
  464. "assets",
  465. "attachments",
  466. "avatars",
  467. "captcha",
  468. "commits",
  469. "debug",
  470. "error",
  471. "explore",
  472. "favicon.ico",
  473. "ghost",
  474. "help",
  475. "install",
  476. "issues",
  477. "less",
  478. "login",
  479. "manifest.json",
  480. "metrics",
  481. "milestones",
  482. "new",
  483. "notifications",
  484. "org",
  485. "plugins",
  486. "pulls",
  487. "raw",
  488. "repo",
  489. "robots.txt",
  490. "search",
  491. "serviceworker.js",
  492. "stars",
  493. "template",
  494. "user",
  495. }
  496. reservedUserPatterns = []string{"*.keys", "*.gpg", "*.rss", "*.atom"}
  497. )
  498. // IsUsableUsername returns an error when a username is reserved
  499. func IsUsableUsername(name string) error {
  500. // Validate username make sure it satisfies requirement.
  501. if db.AlphaDashDotPattern.MatchString(name) {
  502. // Note: usually this error is normally caught up earlier in the UI
  503. return db.ErrNameCharsNotAllowed{Name: name}
  504. }
  505. return db.IsUsableName(reservedUsernames, reservedUserPatterns, name)
  506. }
  507. // CreateUserOverwriteOptions are an optional options who overwrite system defaults on user creation
  508. type CreateUserOverwriteOptions struct {
  509. Visibility structs.VisibleType
  510. }
  511. // CreateUser creates record of a new user.
  512. func CreateUser(u *User, overwriteDefault ...*CreateUserOverwriteOptions) (err error) {
  513. if err = IsUsableUsername(u.Name); err != nil {
  514. return err
  515. }
  516. // set system defaults
  517. u.KeepEmailPrivate = setting.Service.DefaultKeepEmailPrivate
  518. u.Visibility = setting.Service.DefaultUserVisibilityMode
  519. u.AllowCreateOrganization = setting.Service.DefaultAllowCreateOrganization && !setting.Admin.DisableRegularOrgCreation
  520. u.EmailNotificationsPreference = setting.Admin.DefaultEmailNotification
  521. u.MaxRepoCreation = -1
  522. u.Theme = setting.UI.DefaultTheme
  523. // overwrite defaults if set
  524. if len(overwriteDefault) != 0 && overwriteDefault[0] != nil {
  525. u.Visibility = overwriteDefault[0].Visibility
  526. }
  527. ctx, committer, err := db.TxContext()
  528. if err != nil {
  529. return err
  530. }
  531. defer committer.Close()
  532. sess := db.GetEngine(ctx)
  533. // validate data
  534. if err := validateUser(u); err != nil {
  535. return err
  536. }
  537. isExist, err := isUserExist(sess, 0, u.Name)
  538. if err != nil {
  539. return err
  540. } else if isExist {
  541. return ErrUserAlreadyExist{u.Name}
  542. }
  543. isExist, err = IsEmailUsed(ctx, u.Email)
  544. if err != nil {
  545. return err
  546. } else if isExist {
  547. return ErrEmailAlreadyUsed{
  548. Email: u.Email,
  549. }
  550. }
  551. // prepare for database
  552. u.LowerName = strings.ToLower(u.Name)
  553. u.AvatarEmail = u.Email
  554. if u.Rands, err = GetUserSalt(); err != nil {
  555. return err
  556. }
  557. if err = u.SetPassword(u.Passwd); err != nil {
  558. return err
  559. }
  560. // save changes to database
  561. if err = DeleteUserRedirect(ctx, u.Name); err != nil {
  562. return err
  563. }
  564. if err = db.Insert(ctx, u); err != nil {
  565. return err
  566. }
  567. // insert email address
  568. if err := db.Insert(ctx, &EmailAddress{
  569. UID: u.ID,
  570. Email: u.Email,
  571. LowerEmail: strings.ToLower(u.Email),
  572. IsActivated: u.IsActive,
  573. IsPrimary: true,
  574. }); err != nil {
  575. return err
  576. }
  577. return committer.Commit()
  578. }
  579. func countUsers(e db.Engine) int64 {
  580. count, _ := e.
  581. Where("type=0").
  582. Count(new(User))
  583. return count
  584. }
  585. // CountUsers returns number of users.
  586. func CountUsers() int64 {
  587. return countUsers(db.GetEngine(db.DefaultContext))
  588. }
  589. // GetVerifyUser get user by verify code
  590. func GetVerifyUser(code string) (user *User) {
  591. if len(code) <= base.TimeLimitCodeLength {
  592. return nil
  593. }
  594. // use tail hex username query user
  595. hexStr := code[base.TimeLimitCodeLength:]
  596. if b, err := hex.DecodeString(hexStr); err == nil {
  597. if user, err = GetUserByName(string(b)); user != nil {
  598. return user
  599. }
  600. log.Error("user.getVerifyUser: %v", err)
  601. }
  602. return nil
  603. }
  604. // VerifyUserActiveCode verifies active code when active account
  605. func VerifyUserActiveCode(code string) (user *User) {
  606. minutes := setting.Service.ActiveCodeLives
  607. if user = GetVerifyUser(code); user != nil {
  608. // time limit code
  609. prefix := code[:base.TimeLimitCodeLength]
  610. data := fmt.Sprintf("%d%s%s%s%s", user.ID, user.Email, user.LowerName, user.Passwd, user.Rands)
  611. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  612. return user
  613. }
  614. }
  615. return nil
  616. }
  617. // ChangeUserName changes all corresponding setting from old user name to new one.
  618. func ChangeUserName(u *User, newUserName string) (err error) {
  619. oldUserName := u.Name
  620. if err = IsUsableUsername(newUserName); err != nil {
  621. return err
  622. }
  623. ctx, committer, err := db.TxContext()
  624. if err != nil {
  625. return err
  626. }
  627. defer committer.Close()
  628. sess := db.GetEngine(ctx)
  629. isExist, err := isUserExist(sess, 0, newUserName)
  630. if err != nil {
  631. return err
  632. } else if isExist {
  633. return ErrUserAlreadyExist{newUserName}
  634. }
  635. if _, err = sess.Exec("UPDATE `repository` SET owner_name=? WHERE owner_name=?", newUserName, oldUserName); err != nil {
  636. return fmt.Errorf("Change repo owner name: %v", err)
  637. }
  638. // Do not fail if directory does not exist
  639. if err = util.Rename(UserPath(oldUserName), UserPath(newUserName)); err != nil && !os.IsNotExist(err) {
  640. return fmt.Errorf("Rename user directory: %v", err)
  641. }
  642. if err = NewUserRedirect(ctx, u.ID, oldUserName, newUserName); err != nil {
  643. return err
  644. }
  645. if err = committer.Commit(); err != nil {
  646. if err2 := util.Rename(UserPath(newUserName), UserPath(oldUserName)); err2 != nil && !os.IsNotExist(err2) {
  647. 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)
  648. 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)
  649. }
  650. return err
  651. }
  652. return nil
  653. }
  654. // checkDupEmail checks whether there are the same email with the user
  655. func checkDupEmail(e db.Engine, u *User) error {
  656. u.Email = strings.ToLower(u.Email)
  657. has, err := e.
  658. Where("id!=?", u.ID).
  659. And("type=?", u.Type).
  660. And("email=?", u.Email).
  661. Get(new(User))
  662. if err != nil {
  663. return err
  664. } else if has {
  665. return ErrEmailAlreadyUsed{
  666. Email: u.Email,
  667. }
  668. }
  669. return nil
  670. }
  671. // validateUser check if user is valid to insert / update into database
  672. func validateUser(u *User) error {
  673. if !setting.Service.AllowedUserVisibilityModesSlice.IsAllowedVisibility(u.Visibility) && !u.IsOrganization() {
  674. return fmt.Errorf("visibility Mode not allowed: %s", u.Visibility.String())
  675. }
  676. u.Email = strings.ToLower(u.Email)
  677. return ValidateEmail(u.Email)
  678. }
  679. func updateUser(ctx context.Context, u *User, changePrimaryEmail bool) error {
  680. if err := validateUser(u); err != nil {
  681. return err
  682. }
  683. e := db.GetEngine(ctx)
  684. if changePrimaryEmail {
  685. var emailAddress EmailAddress
  686. has, err := e.Where("lower_email=?", strings.ToLower(u.Email)).Get(&emailAddress)
  687. if err != nil {
  688. return err
  689. }
  690. if !has {
  691. // 1. Update old primary email
  692. if _, err = e.Where("uid=? AND is_primary=?", u.ID, true).Cols("is_primary").Update(&EmailAddress{
  693. IsPrimary: false,
  694. }); err != nil {
  695. return err
  696. }
  697. emailAddress.Email = u.Email
  698. emailAddress.UID = u.ID
  699. emailAddress.IsActivated = true
  700. emailAddress.IsPrimary = true
  701. if _, err := e.Insert(&emailAddress); err != nil {
  702. return err
  703. }
  704. } else if _, err := e.ID(emailAddress).Cols("is_primary").Update(&EmailAddress{
  705. IsPrimary: true,
  706. }); err != nil {
  707. return err
  708. }
  709. }
  710. _, err := e.ID(u.ID).AllCols().Update(u)
  711. return err
  712. }
  713. // UpdateUser updates user's information.
  714. func UpdateUser(u *User, emailChanged bool) error {
  715. return updateUser(db.DefaultContext, u, emailChanged)
  716. }
  717. // UpdateUserCols update user according special columns
  718. func UpdateUserCols(ctx context.Context, u *User, cols ...string) error {
  719. return updateUserCols(db.GetEngine(ctx), u, cols...)
  720. }
  721. // UpdateUserColsEngine update user according special columns
  722. func UpdateUserColsEngine(e db.Engine, u *User, cols ...string) error {
  723. return updateUserCols(e, u, cols...)
  724. }
  725. func updateUserCols(e db.Engine, u *User, cols ...string) error {
  726. if err := validateUser(u); err != nil {
  727. return err
  728. }
  729. _, err := e.ID(u.ID).Cols(cols...).Update(u)
  730. return err
  731. }
  732. // UpdateUserSetting updates user's settings.
  733. func UpdateUserSetting(u *User) (err error) {
  734. ctx, committer, err := db.TxContext()
  735. if err != nil {
  736. return err
  737. }
  738. defer committer.Close()
  739. if !u.IsOrganization() {
  740. if err = checkDupEmail(db.GetEngine(ctx), u); err != nil {
  741. return err
  742. }
  743. }
  744. if err = updateUser(ctx, u, false); err != nil {
  745. return err
  746. }
  747. return committer.Commit()
  748. }
  749. // GetInactiveUsers gets all inactive users
  750. func GetInactiveUsers(ctx context.Context, olderThan time.Duration) ([]*User, error) {
  751. var cond builder.Cond = builder.Eq{"is_active": false}
  752. if olderThan > 0 {
  753. cond = cond.And(builder.Lt{"created_unix": time.Now().Add(-olderThan).Unix()})
  754. }
  755. users := make([]*User, 0, 10)
  756. return users, db.GetEngine(ctx).
  757. Where(cond).
  758. Find(&users)
  759. }
  760. // UserPath returns the path absolute path of user repositories.
  761. func UserPath(userName string) string { //revive:disable-line:exported
  762. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  763. }
  764. // GetUserByIDEngine returns the user object by given ID if exists.
  765. func GetUserByIDEngine(e db.Engine, id int64) (*User, error) {
  766. u := new(User)
  767. has, err := e.ID(id).Get(u)
  768. if err != nil {
  769. return nil, err
  770. } else if !has {
  771. return nil, ErrUserNotExist{id, "", 0}
  772. }
  773. return u, nil
  774. }
  775. // GetUserByID returns the user object by given ID if exists.
  776. func GetUserByID(id int64) (*User, error) {
  777. return GetUserByIDCtx(db.DefaultContext, id)
  778. }
  779. // GetUserByIDCtx returns the user object by given ID if exists.
  780. func GetUserByIDCtx(ctx context.Context, id int64) (*User, error) {
  781. return GetUserByIDEngine(db.GetEngine(ctx), id)
  782. }
  783. // GetUserByName returns user by given name.
  784. func GetUserByName(name string) (*User, error) {
  785. return GetUserByNameCtx(db.DefaultContext, name)
  786. }
  787. // GetUserByNameCtx returns user by given name.
  788. func GetUserByNameCtx(ctx context.Context, name string) (*User, error) {
  789. if len(name) == 0 {
  790. return nil, ErrUserNotExist{0, name, 0}
  791. }
  792. u := &User{LowerName: strings.ToLower(name)}
  793. has, err := db.GetEngine(ctx).Get(u)
  794. if err != nil {
  795. return nil, err
  796. } else if !has {
  797. return nil, ErrUserNotExist{0, name, 0}
  798. }
  799. return u, nil
  800. }
  801. // GetUserEmailsByNames returns a list of e-mails corresponds to names of users
  802. // that have their email notifications set to enabled or onmention.
  803. func GetUserEmailsByNames(names []string) []string {
  804. return getUserEmailsByNames(db.DefaultContext, names)
  805. }
  806. func getUserEmailsByNames(ctx context.Context, names []string) []string {
  807. mails := make([]string, 0, len(names))
  808. for _, name := range names {
  809. u, err := GetUserByNameCtx(ctx, name)
  810. if err != nil {
  811. continue
  812. }
  813. if u.IsMailable() && u.EmailNotifications() != EmailNotificationsDisabled {
  814. mails = append(mails, u.Email)
  815. }
  816. }
  817. return mails
  818. }
  819. // GetMaileableUsersByIDs gets users from ids, but only if they can receive mails
  820. func GetMaileableUsersByIDs(ids []int64, isMention bool) ([]*User, error) {
  821. if len(ids) == 0 {
  822. return nil, nil
  823. }
  824. ous := make([]*User, 0, len(ids))
  825. if isMention {
  826. return ous, db.GetEngine(db.DefaultContext).In("id", ids).
  827. Where("`type` = ?", UserTypeIndividual).
  828. And("`prohibit_login` = ?", false).
  829. And("`is_active` = ?", true).
  830. And("`email_notifications_preference` IN ( ?, ?)", EmailNotificationsEnabled, EmailNotificationsOnMention).
  831. Find(&ous)
  832. }
  833. return ous, db.GetEngine(db.DefaultContext).In("id", ids).
  834. Where("`type` = ?", UserTypeIndividual).
  835. And("`prohibit_login` = ?", false).
  836. And("`is_active` = ?", true).
  837. And("`email_notifications_preference` = ?", EmailNotificationsEnabled).
  838. Find(&ous)
  839. }
  840. // GetUserNamesByIDs returns usernames for all resolved users from a list of Ids.
  841. func GetUserNamesByIDs(ids []int64) ([]string, error) {
  842. unames := make([]string, 0, len(ids))
  843. err := db.GetEngine(db.DefaultContext).In("id", ids).
  844. Table("user").
  845. Asc("name").
  846. Cols("name").
  847. Find(&unames)
  848. return unames, err
  849. }
  850. // GetUserIDsByNames returns a slice of ids corresponds to names.
  851. func GetUserIDsByNames(names []string, ignoreNonExistent bool) ([]int64, error) {
  852. ids := make([]int64, 0, len(names))
  853. for _, name := range names {
  854. u, err := GetUserByName(name)
  855. if err != nil {
  856. if ignoreNonExistent {
  857. continue
  858. } else {
  859. return nil, err
  860. }
  861. }
  862. ids = append(ids, u.ID)
  863. }
  864. return ids, nil
  865. }
  866. // GetUsersBySource returns a list of Users for a login source
  867. func GetUsersBySource(s *auth.Source) ([]*User, error) {
  868. var users []*User
  869. err := db.GetEngine(db.DefaultContext).Where("login_type = ? AND login_source = ?", s.Type, s.ID).Find(&users)
  870. return users, err
  871. }
  872. // UserCommit represents a commit with validation of user.
  873. type UserCommit struct { //revive:disable-line:exported
  874. User *User
  875. *git.Commit
  876. }
  877. // ValidateCommitWithEmail check if author's e-mail of commit is corresponding to a user.
  878. func ValidateCommitWithEmail(c *git.Commit) *User {
  879. if c.Author == nil {
  880. return nil
  881. }
  882. u, err := GetUserByEmail(c.Author.Email)
  883. if err != nil {
  884. return nil
  885. }
  886. return u
  887. }
  888. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  889. func ValidateCommitsWithEmails(oldCommits []*git.Commit) []*UserCommit {
  890. var (
  891. emails = make(map[string]*User)
  892. newCommits = make([]*UserCommit, 0, len(oldCommits))
  893. )
  894. for _, c := range oldCommits {
  895. var u *User
  896. if c.Author != nil {
  897. if v, ok := emails[c.Author.Email]; !ok {
  898. u, _ = GetUserByEmail(c.Author.Email)
  899. emails[c.Author.Email] = u
  900. } else {
  901. u = v
  902. }
  903. }
  904. newCommits = append(newCommits, &UserCommit{
  905. User: u,
  906. Commit: c,
  907. })
  908. }
  909. return newCommits
  910. }
  911. // GetUserByEmail returns the user object by given e-mail if exists.
  912. func GetUserByEmail(email string) (*User, error) {
  913. return GetUserByEmailContext(db.DefaultContext, email)
  914. }
  915. // GetUserByEmailContext returns the user object by given e-mail if exists with db context
  916. func GetUserByEmailContext(ctx context.Context, email string) (*User, error) {
  917. if len(email) == 0 {
  918. return nil, ErrUserNotExist{0, email, 0}
  919. }
  920. email = strings.ToLower(email)
  921. // First try to find the user by primary email
  922. user := &User{Email: email}
  923. has, err := db.GetEngine(ctx).Get(user)
  924. if err != nil {
  925. return nil, err
  926. }
  927. if has {
  928. return user, nil
  929. }
  930. // Otherwise, check in alternative list for activated email addresses
  931. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  932. has, err = db.GetEngine(ctx).Get(emailAddress)
  933. if err != nil {
  934. return nil, err
  935. }
  936. if has {
  937. return GetUserByIDCtx(ctx, emailAddress.UID)
  938. }
  939. // Finally, if email address is the protected email address:
  940. if strings.HasSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress)) {
  941. username := strings.TrimSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress))
  942. user := &User{}
  943. has, err := db.GetEngine(ctx).Where("lower_name=?", username).Get(user)
  944. if err != nil {
  945. return nil, err
  946. }
  947. if has {
  948. return user, nil
  949. }
  950. }
  951. return nil, ErrUserNotExist{0, email, 0}
  952. }
  953. // GetUser checks if a user already exists
  954. func GetUser(user *User) (bool, error) {
  955. return db.GetEngine(db.DefaultContext).Get(user)
  956. }
  957. // GetUserByOpenID returns the user object by given OpenID if exists.
  958. func GetUserByOpenID(uri string) (*User, error) {
  959. if len(uri) == 0 {
  960. return nil, ErrUserNotExist{0, uri, 0}
  961. }
  962. uri, err := openid.Normalize(uri)
  963. if err != nil {
  964. return nil, err
  965. }
  966. log.Trace("Normalized OpenID URI: " + uri)
  967. // Otherwise, check in openid table
  968. oid := &UserOpenID{}
  969. has, err := db.GetEngine(db.DefaultContext).Where("uri=?", uri).Get(oid)
  970. if err != nil {
  971. return nil, err
  972. }
  973. if has {
  974. return GetUserByID(oid.UID)
  975. }
  976. return nil, ErrUserNotExist{0, uri, 0}
  977. }
  978. // GetAdminUser returns the first administrator
  979. func GetAdminUser() (*User, error) {
  980. var admin User
  981. has, err := db.GetEngine(db.DefaultContext).Where("is_admin=?", true).Get(&admin)
  982. if err != nil {
  983. return nil, err
  984. } else if !has {
  985. return nil, ErrUserNotExist{}
  986. }
  987. return &admin, nil
  988. }