本站源代码
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.

1831 lines
51KB

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