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.

1266 lines
33 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
8 years ago
8 years ago
10 years ago
10 years ago
8 years ago
10 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
8 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
8 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
9 years ago
9 years ago
9 years ago
10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "bytes"
  7. "container/list"
  8. "crypto/sha256"
  9. "crypto/subtle"
  10. "encoding/hex"
  11. "errors"
  12. "fmt"
  13. "image"
  14. // Needed for jpeg support
  15. _ "image/jpeg"
  16. "image/png"
  17. "os"
  18. "path/filepath"
  19. "strings"
  20. "time"
  21. "unicode/utf8"
  22. "github.com/Unknwon/com"
  23. "github.com/go-xorm/xorm"
  24. "github.com/nfnt/resize"
  25. "golang.org/x/crypto/pbkdf2"
  26. "code.gitea.io/git"
  27. api "code.gitea.io/sdk/gitea"
  28. "code.gitea.io/gitea/modules/avatar"
  29. "code.gitea.io/gitea/modules/base"
  30. "code.gitea.io/gitea/modules/log"
  31. "code.gitea.io/gitea/modules/markdown"
  32. "code.gitea.io/gitea/modules/setting"
  33. )
  34. // UserType defines the user type
  35. type UserType int
  36. const (
  37. // UserTypeIndividual defines an individual user
  38. UserTypeIndividual UserType = iota // Historic reason to make it starts at 0.
  39. // UserTypeOrganization defines an organization
  40. UserTypeOrganization
  41. )
  42. var (
  43. // ErrUserNotKeyOwner user does not own this key error
  44. ErrUserNotKeyOwner = errors.New("User does not own this public key")
  45. // ErrEmailNotExist e-mail does not exist error
  46. ErrEmailNotExist = errors.New("E-mail does not exist")
  47. // ErrEmailNotActivated e-mail address has not been activated error
  48. ErrEmailNotActivated = errors.New("E-mail address has not been activated")
  49. // ErrUserNameIllegal user name contains illegal characters error
  50. ErrUserNameIllegal = errors.New("User name contains illegal characters")
  51. // ErrLoginSourceNotActived login source is not actived error
  52. ErrLoginSourceNotActived = errors.New("Login source is not actived")
  53. // ErrUnsupportedLoginType login source is unknown error
  54. ErrUnsupportedLoginType = errors.New("Login source is unknown")
  55. )
  56. // User represents the object of individual and member of organization.
  57. type User struct {
  58. ID int64 `xorm:"pk autoincr"`
  59. LowerName string `xorm:"UNIQUE NOT NULL"`
  60. Name string `xorm:"UNIQUE NOT NULL"`
  61. FullName string
  62. // Email is the primary email address (to be used for communication)
  63. Email string `xorm:"NOT NULL"`
  64. Passwd string `xorm:"NOT NULL"`
  65. LoginType LoginType
  66. LoginSource int64 `xorm:"NOT NULL DEFAULT 0"`
  67. LoginName string
  68. Type UserType
  69. OwnedOrgs []*User `xorm:"-"`
  70. Orgs []*User `xorm:"-"`
  71. Repos []*Repository `xorm:"-"`
  72. Location string
  73. Website string
  74. Rands string `xorm:"VARCHAR(10)"`
  75. Salt string `xorm:"VARCHAR(10)"`
  76. Created time.Time `xorm:"-"`
  77. CreatedUnix int64
  78. Updated time.Time `xorm:"-"`
  79. UpdatedUnix int64
  80. LastLogin time.Time `xorm:"-"`
  81. LastLoginUnix int64
  82. // Remember visibility choice for convenience, true for private
  83. LastRepoVisibility bool
  84. // Maximum repository creation limit, -1 means use global default
  85. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1"`
  86. // Permissions
  87. IsActive bool // Activate primary email
  88. IsAdmin bool
  89. AllowGitHook bool
  90. AllowImportLocal bool // Allow migrate repository by local path
  91. ProhibitLogin bool
  92. // Avatar
  93. Avatar string `xorm:"VARCHAR(2048) NOT NULL"`
  94. AvatarEmail string `xorm:"NOT NULL"`
  95. UseCustomAvatar bool
  96. // Counters
  97. NumFollowers int
  98. NumFollowing int `xorm:"NOT NULL DEFAULT 0"`
  99. NumStars int
  100. NumRepos int
  101. // For organization
  102. Description string
  103. NumTeams int
  104. NumMembers int
  105. Teams []*Team `xorm:"-"`
  106. Members []*User `xorm:"-"`
  107. // Preferences
  108. DiffViewStyle string `xorm:"NOT NULL DEFAULT ''"`
  109. }
  110. // BeforeInsert is invoked from XORM before inserting an object of this type.
  111. func (u *User) BeforeInsert() {
  112. u.CreatedUnix = time.Now().Unix()
  113. u.UpdatedUnix = u.CreatedUnix
  114. }
  115. // BeforeUpdate is invoked from XORM before updating this object.
  116. func (u *User) BeforeUpdate() {
  117. if u.MaxRepoCreation < -1 {
  118. u.MaxRepoCreation = -1
  119. }
  120. u.UpdatedUnix = time.Now().Unix()
  121. }
  122. // SetLastLogin set time to last login
  123. func (u *User) SetLastLogin() {
  124. u.LastLoginUnix = time.Now().Unix()
  125. }
  126. // UpdateDiffViewStyle updates the users diff view style
  127. func (u *User) UpdateDiffViewStyle(style string) error {
  128. u.DiffViewStyle = style
  129. return UpdateUser(u)
  130. }
  131. // AfterSet is invoked from XORM after setting the value of a field of this object.
  132. func (u *User) AfterSet(colName string, _ xorm.Cell) {
  133. switch colName {
  134. case "full_name":
  135. u.FullName = markdown.Sanitizer.Sanitize(u.FullName)
  136. case "created_unix":
  137. u.Created = time.Unix(u.CreatedUnix, 0).Local()
  138. case "updated_unix":
  139. u.Updated = time.Unix(u.UpdatedUnix, 0).Local()
  140. case "last_login_unix":
  141. u.LastLogin = time.Unix(u.LastLoginUnix, 0).Local()
  142. }
  143. }
  144. // APIFormat converts a User to api.User
  145. func (u *User) APIFormat() *api.User {
  146. return &api.User{
  147. ID: u.ID,
  148. UserName: u.Name,
  149. FullName: u.FullName,
  150. Email: u.Email,
  151. AvatarURL: u.AvatarLink(),
  152. }
  153. }
  154. // IsLocal returns true if user login type is LoginPlain.
  155. func (u *User) IsLocal() bool {
  156. return u.LoginType <= LoginPlain
  157. }
  158. // HasForkedRepo checks if user has already forked a repository with given ID.
  159. func (u *User) HasForkedRepo(repoID int64) bool {
  160. _, has := HasForkedRepo(u.ID, repoID)
  161. return has
  162. }
  163. // RepoCreationNum returns the number of repositories created by the user
  164. func (u *User) RepoCreationNum() int {
  165. if u.MaxRepoCreation <= -1 {
  166. return setting.Repository.MaxCreationLimit
  167. }
  168. return u.MaxRepoCreation
  169. }
  170. // CanCreateRepo returns if user login can create a repository
  171. func (u *User) CanCreateRepo() bool {
  172. if u.MaxRepoCreation <= -1 {
  173. if setting.Repository.MaxCreationLimit <= -1 {
  174. return true
  175. }
  176. return u.NumRepos < setting.Repository.MaxCreationLimit
  177. }
  178. return u.NumRepos < u.MaxRepoCreation
  179. }
  180. // CanEditGitHook returns true if user can edit Git hooks.
  181. func (u *User) CanEditGitHook() bool {
  182. return u.IsAdmin || u.AllowGitHook
  183. }
  184. // CanImportLocal returns true if user can migrate repository by local path.
  185. func (u *User) CanImportLocal() bool {
  186. return u.IsAdmin || u.AllowImportLocal
  187. }
  188. // DashboardLink returns the user dashboard page link.
  189. func (u *User) DashboardLink() string {
  190. if u.IsOrganization() {
  191. return setting.AppSubURL + "/org/" + u.Name + "/dashboard/"
  192. }
  193. return setting.AppSubURL + "/"
  194. }
  195. // HomeLink returns the user or organization home page link.
  196. func (u *User) HomeLink() string {
  197. return setting.AppSubURL + "/" + u.Name
  198. }
  199. // GenerateEmailActivateCode generates an activate code based on user information and given e-mail.
  200. func (u *User) GenerateEmailActivateCode(email string) string {
  201. code := base.CreateTimeLimitCode(
  202. com.ToStr(u.ID)+email+u.LowerName+u.Passwd+u.Rands,
  203. setting.Service.ActiveCodeLives, nil)
  204. // Add tail hex username
  205. code += hex.EncodeToString([]byte(u.LowerName))
  206. return code
  207. }
  208. // GenerateActivateCode generates an activate code based on user information.
  209. func (u *User) GenerateActivateCode() string {
  210. return u.GenerateEmailActivateCode(u.Email)
  211. }
  212. // CustomAvatarPath returns user custom avatar file path.
  213. func (u *User) CustomAvatarPath() string {
  214. return filepath.Join(setting.AvatarUploadPath, com.ToStr(u.ID))
  215. }
  216. // GenerateRandomAvatar generates a random avatar for user.
  217. func (u *User) GenerateRandomAvatar() error {
  218. seed := u.Email
  219. if len(seed) == 0 {
  220. seed = u.Name
  221. }
  222. img, err := avatar.RandomImage([]byte(seed))
  223. if err != nil {
  224. return fmt.Errorf("RandomImage: %v", err)
  225. }
  226. if err = os.MkdirAll(filepath.Dir(u.CustomAvatarPath()), os.ModePerm); err != nil {
  227. return fmt.Errorf("MkdirAll: %v", err)
  228. }
  229. fw, err := os.Create(u.CustomAvatarPath())
  230. if err != nil {
  231. return fmt.Errorf("Create: %v", err)
  232. }
  233. defer fw.Close()
  234. if err = png.Encode(fw, img); err != nil {
  235. return fmt.Errorf("Encode: %v", err)
  236. }
  237. log.Info("New random avatar created: %d", u.ID)
  238. return nil
  239. }
  240. // RelAvatarLink returns relative avatar link to the site domain,
  241. // which includes app sub-url as prefix. However, it is possible
  242. // to return full URL if user enables Gravatar-like service.
  243. func (u *User) RelAvatarLink() string {
  244. defaultImgURL := setting.AppSubURL + "/img/avatar_default.png"
  245. if u.ID == -1 {
  246. return defaultImgURL
  247. }
  248. switch {
  249. case u.UseCustomAvatar:
  250. if !com.IsExist(u.CustomAvatarPath()) {
  251. return defaultImgURL
  252. }
  253. return setting.AppSubURL + "/avatars/" + com.ToStr(u.ID)
  254. case setting.DisableGravatar, setting.OfflineMode:
  255. if !com.IsExist(u.CustomAvatarPath()) {
  256. if err := u.GenerateRandomAvatar(); err != nil {
  257. log.Error(3, "GenerateRandomAvatar: %v", err)
  258. }
  259. }
  260. return setting.AppSubURL + "/avatars/" + com.ToStr(u.ID)
  261. }
  262. return base.AvatarLink(u.AvatarEmail)
  263. }
  264. // AvatarLink returns user avatar absolute link.
  265. func (u *User) AvatarLink() string {
  266. link := u.RelAvatarLink()
  267. if link[0] == '/' && link[1] != '/' {
  268. return setting.AppURL + strings.TrimPrefix(link, setting.AppSubURL)[1:]
  269. }
  270. return link
  271. }
  272. // GetFollowers returns range of user's followers.
  273. func (u *User) GetFollowers(page int) ([]*User, error) {
  274. users := make([]*User, 0, ItemsPerPage)
  275. sess := x.
  276. Limit(ItemsPerPage, (page-1)*ItemsPerPage).
  277. Where("follow.follow_id=?", u.ID)
  278. if setting.UsePostgreSQL {
  279. sess = sess.Join("LEFT", "follow", `"user".id=follow.user_id`)
  280. } else {
  281. sess = sess.Join("LEFT", "follow", "user.id=follow.user_id")
  282. }
  283. return users, sess.Find(&users)
  284. }
  285. // IsFollowing returns true if user is following followID.
  286. func (u *User) IsFollowing(followID int64) bool {
  287. return IsFollowing(u.ID, followID)
  288. }
  289. // GetFollowing returns range of user's following.
  290. func (u *User) GetFollowing(page int) ([]*User, error) {
  291. users := make([]*User, 0, ItemsPerPage)
  292. sess := x.
  293. Limit(ItemsPerPage, (page-1)*ItemsPerPage).
  294. Where("follow.user_id=?", u.ID)
  295. if setting.UsePostgreSQL {
  296. sess = sess.Join("LEFT", "follow", `"user".id=follow.follow_id`)
  297. } else {
  298. sess = sess.Join("LEFT", "follow", "user.id=follow.follow_id")
  299. }
  300. return users, sess.Find(&users)
  301. }
  302. // NewGitSig generates and returns the signature of given user.
  303. func (u *User) NewGitSig() *git.Signature {
  304. return &git.Signature{
  305. Name: u.DisplayName(),
  306. Email: u.Email,
  307. When: time.Now(),
  308. }
  309. }
  310. // EncodePasswd encodes password to safe format.
  311. func (u *User) EncodePasswd() {
  312. newPasswd := pbkdf2.Key([]byte(u.Passwd), []byte(u.Salt), 10000, 50, sha256.New)
  313. u.Passwd = fmt.Sprintf("%x", newPasswd)
  314. }
  315. // ValidatePassword checks if given password matches the one belongs to the user.
  316. func (u *User) ValidatePassword(passwd string) bool {
  317. newUser := &User{Passwd: passwd, Salt: u.Salt}
  318. newUser.EncodePasswd()
  319. return subtle.ConstantTimeCompare([]byte(u.Passwd), []byte(newUser.Passwd)) == 1
  320. }
  321. // UploadAvatar saves custom avatar for user.
  322. // FIXME: split uploads to different subdirs in case we have massive users.
  323. func (u *User) UploadAvatar(data []byte) error {
  324. img, _, err := image.Decode(bytes.NewReader(data))
  325. if err != nil {
  326. return fmt.Errorf("Decode: %v", err)
  327. }
  328. m := resize.Resize(avatar.AvatarSize, avatar.AvatarSize, img, resize.NearestNeighbor)
  329. sess := x.NewSession()
  330. defer sessionRelease(sess)
  331. if err = sess.Begin(); err != nil {
  332. return err
  333. }
  334. u.UseCustomAvatar = true
  335. if err = updateUser(sess, u); err != nil {
  336. return fmt.Errorf("updateUser: %v", err)
  337. }
  338. if err := os.MkdirAll(setting.AvatarUploadPath, os.ModePerm); err != nil {
  339. return fmt.Errorf("Fail to create dir %s: %v", setting.AvatarUploadPath, err)
  340. }
  341. fw, err := os.Create(u.CustomAvatarPath())
  342. if err != nil {
  343. return fmt.Errorf("Create: %v", err)
  344. }
  345. defer fw.Close()
  346. if err = png.Encode(fw, m); err != nil {
  347. return fmt.Errorf("Encode: %v", err)
  348. }
  349. return sess.Commit()
  350. }
  351. // DeleteAvatar deletes the user's custom avatar.
  352. func (u *User) DeleteAvatar() error {
  353. log.Trace("DeleteAvatar[%d]: %s", u.ID, u.CustomAvatarPath())
  354. if err := os.Remove(u.CustomAvatarPath()); err != nil {
  355. return fmt.Errorf("Fail to remove %s: %v", u.CustomAvatarPath(), err)
  356. }
  357. u.UseCustomAvatar = false
  358. if err := UpdateUser(u); err != nil {
  359. return fmt.Errorf("UpdateUser: %v", err)
  360. }
  361. return nil
  362. }
  363. // IsAdminOfRepo returns true if user has admin or higher access of repository.
  364. func (u *User) IsAdminOfRepo(repo *Repository) bool {
  365. has, err := HasAccess(u, repo, AccessModeAdmin)
  366. if err != nil {
  367. log.Error(3, "HasAccess: %v", err)
  368. }
  369. return has
  370. }
  371. // IsWriterOfRepo returns true if user has write access to given repository.
  372. func (u *User) IsWriterOfRepo(repo *Repository) bool {
  373. has, err := HasAccess(u, repo, AccessModeWrite)
  374. if err != nil {
  375. log.Error(3, "HasAccess: %v", err)
  376. }
  377. return has
  378. }
  379. // IsOrganization returns true if user is actually a organization.
  380. func (u *User) IsOrganization() bool {
  381. return u.Type == UserTypeOrganization
  382. }
  383. // IsUserOrgOwner returns true if user is in the owner team of given organization.
  384. func (u *User) IsUserOrgOwner(orgID int64) bool {
  385. return IsOrganizationOwner(orgID, u.ID)
  386. }
  387. // IsPublicMember returns true if user public his/her membership in give organization.
  388. func (u *User) IsPublicMember(orgID int64) bool {
  389. return IsPublicMembership(orgID, u.ID)
  390. }
  391. func (u *User) getOrganizationCount(e Engine) (int64, error) {
  392. return e.
  393. Where("uid=?", u.ID).
  394. Count(new(OrgUser))
  395. }
  396. // GetOrganizationCount returns count of membership of organization of user.
  397. func (u *User) GetOrganizationCount() (int64, error) {
  398. return u.getOrganizationCount(x)
  399. }
  400. // GetRepositories returns repositories that user owns, including private repositories.
  401. func (u *User) GetRepositories(page, pageSize int) (err error) {
  402. u.Repos, err = GetUserRepositories(u.ID, true, page, pageSize)
  403. return err
  404. }
  405. // GetMirrorRepositories returns mirror repositories that user owns, including private repositories.
  406. func (u *User) GetMirrorRepositories() ([]*Repository, error) {
  407. return GetUserMirrorRepositories(u.ID)
  408. }
  409. // GetOwnedOrganizations returns all organizations that user owns.
  410. func (u *User) GetOwnedOrganizations() (err error) {
  411. u.OwnedOrgs, err = GetOwnedOrgsByUserID(u.ID)
  412. return err
  413. }
  414. // GetOrganizations returns all organizations that user belongs to.
  415. func (u *User) GetOrganizations(all bool) error {
  416. ous, err := GetOrgUsersByUserID(u.ID, all)
  417. if err != nil {
  418. return err
  419. }
  420. u.Orgs = make([]*User, len(ous))
  421. for i, ou := range ous {
  422. u.Orgs[i], err = GetUserByID(ou.OrgID)
  423. if err != nil {
  424. return err
  425. }
  426. }
  427. return nil
  428. }
  429. // DisplayName returns full name if it's not empty,
  430. // returns username otherwise.
  431. func (u *User) DisplayName() string {
  432. if len(u.FullName) > 0 {
  433. return u.FullName
  434. }
  435. return u.Name
  436. }
  437. // ShortName ellipses username to length
  438. func (u *User) ShortName(length int) string {
  439. return base.EllipsisString(u.Name, length)
  440. }
  441. // IsUserExist checks if given user name exist,
  442. // the user name should be noncased unique.
  443. // If uid is presented, then check will rule out that one,
  444. // it is used when update a user name in settings page.
  445. func IsUserExist(uid int64, name string) (bool, error) {
  446. if len(name) == 0 {
  447. return false, nil
  448. }
  449. return x.
  450. Where("id!=?", uid).
  451. Get(&User{LowerName: strings.ToLower(name)})
  452. }
  453. // GetUserSalt returns a ramdom user salt token.
  454. func GetUserSalt() (string, error) {
  455. return base.GetRandomString(10)
  456. }
  457. // NewGhostUser creates and returns a fake user for someone has deleted his/her account.
  458. func NewGhostUser() *User {
  459. return &User{
  460. ID: -1,
  461. Name: "Ghost",
  462. LowerName: "ghost",
  463. }
  464. }
  465. var (
  466. reservedUsernames = []string{"assets", "css", "img", "js", "less", "plugins", "debug", "raw", "install", "api", "avatar", "user", "org", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin", "new", ".", ".."}
  467. reservedUserPatterns = []string{"*.keys"}
  468. )
  469. // isUsableName checks if name is reserved or pattern of name is not allowed
  470. // based on given reserved names and patterns.
  471. // Names are exact match, patterns can be prefix or suffix match with placeholder '*'.
  472. func isUsableName(names, patterns []string, name string) error {
  473. name = strings.TrimSpace(strings.ToLower(name))
  474. if utf8.RuneCountInString(name) == 0 {
  475. return ErrNameEmpty
  476. }
  477. for i := range names {
  478. if name == names[i] {
  479. return ErrNameReserved{name}
  480. }
  481. }
  482. for _, pat := range patterns {
  483. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  484. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  485. return ErrNamePatternNotAllowed{pat}
  486. }
  487. }
  488. return nil
  489. }
  490. // IsUsableUsername returns an error when a username is reserved
  491. func IsUsableUsername(name string) error {
  492. return isUsableName(reservedUsernames, reservedUserPatterns, name)
  493. }
  494. // CreateUser creates record of a new user.
  495. func CreateUser(u *User) (err error) {
  496. if err = IsUsableUsername(u.Name); err != nil {
  497. return err
  498. }
  499. isExist, err := IsUserExist(0, u.Name)
  500. if err != nil {
  501. return err
  502. } else if isExist {
  503. return ErrUserAlreadyExist{u.Name}
  504. }
  505. u.Email = strings.ToLower(u.Email)
  506. isExist, err = IsEmailUsed(u.Email)
  507. if err != nil {
  508. return err
  509. } else if isExist {
  510. return ErrEmailAlreadyUsed{u.Email}
  511. }
  512. u.LowerName = strings.ToLower(u.Name)
  513. u.AvatarEmail = u.Email
  514. u.Avatar = base.HashEmail(u.AvatarEmail)
  515. if u.Rands, err = GetUserSalt(); err != nil {
  516. return err
  517. }
  518. if u.Salt, err = GetUserSalt(); err != nil {
  519. return err
  520. }
  521. u.EncodePasswd()
  522. u.MaxRepoCreation = -1
  523. sess := x.NewSession()
  524. defer sessionRelease(sess)
  525. if err = sess.Begin(); err != nil {
  526. return err
  527. }
  528. if _, err = sess.Insert(u); err != nil {
  529. return err
  530. } else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
  531. return err
  532. }
  533. return sess.Commit()
  534. }
  535. func countUsers(e Engine) int64 {
  536. count, _ := e.
  537. Where("type=0").
  538. Count(new(User))
  539. return count
  540. }
  541. // CountUsers returns number of users.
  542. func CountUsers() int64 {
  543. return countUsers(x)
  544. }
  545. // Users returns number of users in given page.
  546. func Users(opts *SearchUserOptions) ([]*User, error) {
  547. if len(opts.OrderBy) == 0 {
  548. opts.OrderBy = "name ASC"
  549. }
  550. users := make([]*User, 0, opts.PageSize)
  551. sess := x.
  552. Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).
  553. Where("type=0")
  554. return users, sess.
  555. OrderBy(opts.OrderBy).
  556. Find(&users)
  557. }
  558. // get user by erify code
  559. func getVerifyUser(code string) (user *User) {
  560. if len(code) <= base.TimeLimitCodeLength {
  561. return nil
  562. }
  563. // use tail hex username query user
  564. hexStr := code[base.TimeLimitCodeLength:]
  565. if b, err := hex.DecodeString(hexStr); err == nil {
  566. if user, err = GetUserByName(string(b)); user != nil {
  567. return user
  568. }
  569. log.Error(4, "user.getVerifyUser: %v", err)
  570. }
  571. return nil
  572. }
  573. // VerifyUserActiveCode verifies active code when active account
  574. func VerifyUserActiveCode(code string) (user *User) {
  575. minutes := setting.Service.ActiveCodeLives
  576. if user = getVerifyUser(code); user != nil {
  577. // time limit code
  578. prefix := code[:base.TimeLimitCodeLength]
  579. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands
  580. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  581. return user
  582. }
  583. }
  584. return nil
  585. }
  586. // VerifyActiveEmailCode verifies active email code when active account
  587. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  588. minutes := setting.Service.ActiveCodeLives
  589. if user := getVerifyUser(code); user != nil {
  590. // time limit code
  591. prefix := code[:base.TimeLimitCodeLength]
  592. data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands
  593. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  594. emailAddress := &EmailAddress{Email: email}
  595. if has, _ := x.Get(emailAddress); has {
  596. return emailAddress
  597. }
  598. }
  599. }
  600. return nil
  601. }
  602. // ChangeUserName changes all corresponding setting from old user name to new one.
  603. func ChangeUserName(u *User, newUserName string) (err error) {
  604. if err = IsUsableUsername(newUserName); err != nil {
  605. return err
  606. }
  607. isExist, err := IsUserExist(0, newUserName)
  608. if err != nil {
  609. return err
  610. } else if isExist {
  611. return ErrUserAlreadyExist{newUserName}
  612. }
  613. if err = ChangeUsernameInPullRequests(u.Name, newUserName); err != nil {
  614. return fmt.Errorf("ChangeUsernameInPullRequests: %v", err)
  615. }
  616. // Delete all local copies of repository wiki that user owns.
  617. if err = x.
  618. Where("owner_id=?", u.ID).
  619. Iterate(new(Repository), func(idx int, bean interface{}) error {
  620. repo := bean.(*Repository)
  621. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  622. return nil
  623. }); err != nil {
  624. return fmt.Errorf("Delete repository wiki local copy: %v", err)
  625. }
  626. return os.Rename(UserPath(u.Name), UserPath(newUserName))
  627. }
  628. func updateUser(e Engine, u *User) error {
  629. // Organization does not need email
  630. if !u.IsOrganization() {
  631. u.Email = strings.ToLower(u.Email)
  632. has, err := e.
  633. Where("id!=?", u.ID).
  634. And("type=?", u.Type).
  635. And("email=?", u.Email).
  636. Get(new(User))
  637. if err != nil {
  638. return err
  639. } else if has {
  640. return ErrEmailAlreadyUsed{u.Email}
  641. }
  642. if len(u.AvatarEmail) == 0 {
  643. u.AvatarEmail = u.Email
  644. }
  645. u.Avatar = base.HashEmail(u.AvatarEmail)
  646. }
  647. u.LowerName = strings.ToLower(u.Name)
  648. u.Location = base.TruncateString(u.Location, 255)
  649. u.Website = base.TruncateString(u.Website, 255)
  650. u.Description = base.TruncateString(u.Description, 255)
  651. u.FullName = markdown.Sanitizer.Sanitize(u.FullName)
  652. _, err := e.Id(u.ID).AllCols().Update(u)
  653. return err
  654. }
  655. // UpdateUser updates user's information.
  656. func UpdateUser(u *User) error {
  657. return updateUser(x, u)
  658. }
  659. // deleteBeans deletes all given beans, beans should contain delete conditions.
  660. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  661. for i := range beans {
  662. if _, err = e.Delete(beans[i]); err != nil {
  663. return err
  664. }
  665. }
  666. return nil
  667. }
  668. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  669. func deleteUser(e *xorm.Session, u *User) error {
  670. // Note: A user owns any repository or belongs to any organization
  671. // cannot perform delete operation.
  672. // Check ownership of repository.
  673. count, err := getRepositoryCount(e, u)
  674. if err != nil {
  675. return fmt.Errorf("GetRepositoryCount: %v", err)
  676. } else if count > 0 {
  677. return ErrUserOwnRepos{UID: u.ID}
  678. }
  679. // Check membership of organization.
  680. count, err = u.getOrganizationCount(e)
  681. if err != nil {
  682. return fmt.Errorf("GetOrganizationCount: %v", err)
  683. } else if count > 0 {
  684. return ErrUserHasOrgs{UID: u.ID}
  685. }
  686. // ***** START: Watch *****
  687. watches := make([]*Watch, 0, 10)
  688. if err = e.Find(&watches, &Watch{UserID: u.ID}); err != nil {
  689. return fmt.Errorf("get all watches: %v", err)
  690. }
  691. for i := range watches {
  692. if _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", watches[i].RepoID); err != nil {
  693. return fmt.Errorf("decrease repository watch number[%d]: %v", watches[i].RepoID, err)
  694. }
  695. }
  696. // ***** END: Watch *****
  697. // ***** START: Star *****
  698. stars := make([]*Star, 0, 10)
  699. if err = e.Find(&stars, &Star{UID: u.ID}); err != nil {
  700. return fmt.Errorf("get all stars: %v", err)
  701. }
  702. for i := range stars {
  703. if _, err = e.Exec("UPDATE `repository` SET num_stars=num_stars-1 WHERE id=?", stars[i].RepoID); err != nil {
  704. return fmt.Errorf("decrease repository star number[%d]: %v", stars[i].RepoID, err)
  705. }
  706. }
  707. // ***** END: Star *****
  708. // ***** START: Follow *****
  709. followers := make([]*Follow, 0, 10)
  710. if err = e.Find(&followers, &Follow{UserID: u.ID}); err != nil {
  711. return fmt.Errorf("get all followers: %v", err)
  712. }
  713. for i := range followers {
  714. if _, err = e.Exec("UPDATE `user` SET num_followers=num_followers-1 WHERE id=?", followers[i].UserID); err != nil {
  715. return fmt.Errorf("decrease user follower number[%d]: %v", followers[i].UserID, err)
  716. }
  717. }
  718. // ***** END: Follow *****
  719. if err = deleteBeans(e,
  720. &AccessToken{UID: u.ID},
  721. &Collaboration{UserID: u.ID},
  722. &Access{UserID: u.ID},
  723. &Watch{UserID: u.ID},
  724. &Star{UID: u.ID},
  725. &Follow{FollowID: u.ID},
  726. &Action{UserID: u.ID},
  727. &IssueUser{UID: u.ID},
  728. &EmailAddress{UID: u.ID},
  729. ); err != nil {
  730. return fmt.Errorf("deleteBeans: %v", err)
  731. }
  732. // ***** START: PublicKey *****
  733. keys := make([]*PublicKey, 0, 10)
  734. if err = e.Find(&keys, &PublicKey{OwnerID: u.ID}); err != nil {
  735. return fmt.Errorf("get all public keys: %v", err)
  736. }
  737. keyIDs := make([]int64, len(keys))
  738. for i := range keys {
  739. keyIDs[i] = keys[i].ID
  740. }
  741. if err = deletePublicKeys(e, keyIDs...); err != nil {
  742. return fmt.Errorf("deletePublicKeys: %v", err)
  743. }
  744. // ***** END: PublicKey *****
  745. // Clear assignee.
  746. if _, err = e.Exec("UPDATE `issue` SET assignee_id=0 WHERE assignee_id=?", u.ID); err != nil {
  747. return fmt.Errorf("clear assignee: %v", err)
  748. }
  749. if _, err = e.Id(u.ID).Delete(new(User)); err != nil {
  750. return fmt.Errorf("Delete: %v", err)
  751. }
  752. // FIXME: system notice
  753. // Note: There are something just cannot be roll back,
  754. // so just keep error logs of those operations.
  755. path := UserPath(u.Name)
  756. if err := os.RemoveAll(path); err != nil {
  757. return fmt.Errorf("Fail to RemoveAll %s: %v", path, err)
  758. }
  759. avatarPath := u.CustomAvatarPath()
  760. if com.IsExist(avatarPath) {
  761. if err := os.Remove(avatarPath); err != nil {
  762. return fmt.Errorf("Fail to remove %s: %v", avatarPath, err)
  763. }
  764. }
  765. return nil
  766. }
  767. // DeleteUser completely and permanently deletes everything of a user,
  768. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  769. func DeleteUser(u *User) (err error) {
  770. sess := x.NewSession()
  771. defer sessionRelease(sess)
  772. if err = sess.Begin(); err != nil {
  773. return err
  774. }
  775. if err = deleteUser(sess, u); err != nil {
  776. // Note: don't wrapper error here.
  777. return err
  778. }
  779. if err = sess.Commit(); err != nil {
  780. return err
  781. }
  782. return RewriteAllPublicKeys()
  783. }
  784. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  785. func DeleteInactivateUsers() (err error) {
  786. users := make([]*User, 0, 10)
  787. if err = x.
  788. Where("is_active = ?", false).
  789. Find(&users); err != nil {
  790. return fmt.Errorf("get all inactive users: %v", err)
  791. }
  792. // FIXME: should only update authorized_keys file once after all deletions.
  793. for _, u := range users {
  794. if err = DeleteUser(u); err != nil {
  795. // Ignore users that were set inactive by admin.
  796. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  797. continue
  798. }
  799. return err
  800. }
  801. }
  802. _, err = x.
  803. Where("is_activated = ?", false).
  804. Delete(new(EmailAddress))
  805. return err
  806. }
  807. // UserPath returns the path absolute path of user repositories.
  808. func UserPath(userName string) string {
  809. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  810. }
  811. // GetUserByKeyID get user information by user's public key id
  812. func GetUserByKeyID(keyID int64) (*User, error) {
  813. var user User
  814. has, err := x.Join("INNER", "public_key", "`public_key`.owner_id = `user`.id").
  815. Where("`public_key`.id=?", keyID).
  816. Get(&user)
  817. if err != nil {
  818. return nil, err
  819. }
  820. if !has {
  821. return nil, ErrUserNotExist{0, "", keyID}
  822. }
  823. return &user, nil
  824. }
  825. func getUserByID(e Engine, id int64) (*User, error) {
  826. u := new(User)
  827. has, err := e.Id(id).Get(u)
  828. if err != nil {
  829. return nil, err
  830. } else if !has {
  831. return nil, ErrUserNotExist{id, "", 0}
  832. }
  833. return u, nil
  834. }
  835. // GetUserByID returns the user object by given ID if exists.
  836. func GetUserByID(id int64) (*User, error) {
  837. return getUserByID(x, id)
  838. }
  839. // GetAssigneeByID returns the user with write access of repository by given ID.
  840. func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
  841. has, err := HasAccess(&User{ID: userID}, repo, AccessModeWrite)
  842. if err != nil {
  843. return nil, err
  844. } else if !has {
  845. return nil, ErrUserNotExist{userID, "", 0}
  846. }
  847. return GetUserByID(userID)
  848. }
  849. // GetUserByName returns user by given name.
  850. func GetUserByName(name string) (*User, error) {
  851. if len(name) == 0 {
  852. return nil, ErrUserNotExist{0, name, 0}
  853. }
  854. u := &User{LowerName: strings.ToLower(name)}
  855. has, err := x.Get(u)
  856. if err != nil {
  857. return nil, err
  858. } else if !has {
  859. return nil, ErrUserNotExist{0, name, 0}
  860. }
  861. return u, nil
  862. }
  863. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  864. func GetUserEmailsByNames(names []string) []string {
  865. mails := make([]string, 0, len(names))
  866. for _, name := range names {
  867. u, err := GetUserByName(name)
  868. if err != nil {
  869. continue
  870. }
  871. mails = append(mails, u.Email)
  872. }
  873. return mails
  874. }
  875. // GetUsersByIDs returns all resolved users from a list of Ids.
  876. func GetUsersByIDs(ids []int64) ([]*User, error) {
  877. ous := make([]*User, 0, len(ids))
  878. err := x.
  879. In("id", ids).
  880. Asc("name").
  881. Find(&ous)
  882. return ous, err
  883. }
  884. // GetUserIDsByNames returns a slice of ids corresponds to names.
  885. func GetUserIDsByNames(names []string) []int64 {
  886. ids := make([]int64, 0, len(names))
  887. for _, name := range names {
  888. u, err := GetUserByName(name)
  889. if err != nil {
  890. continue
  891. }
  892. ids = append(ids, u.ID)
  893. }
  894. return ids
  895. }
  896. // UserCommit represents a commit with validation of user.
  897. type UserCommit struct {
  898. User *User
  899. *git.Commit
  900. }
  901. // ValidateCommitWithEmail chceck if author's e-mail of commit is corresponsind to a user.
  902. func ValidateCommitWithEmail(c *git.Commit) *User {
  903. u, err := GetUserByEmail(c.Author.Email)
  904. if err != nil {
  905. return nil
  906. }
  907. return u
  908. }
  909. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  910. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  911. var (
  912. u *User
  913. emails = map[string]*User{}
  914. newCommits = list.New()
  915. e = oldCommits.Front()
  916. )
  917. for e != nil {
  918. c := e.Value.(*git.Commit)
  919. if v, ok := emails[c.Author.Email]; !ok {
  920. u, _ = GetUserByEmail(c.Author.Email)
  921. emails[c.Author.Email] = u
  922. } else {
  923. u = v
  924. }
  925. newCommits.PushBack(UserCommit{
  926. User: u,
  927. Commit: c,
  928. })
  929. e = e.Next()
  930. }
  931. return newCommits
  932. }
  933. // GetUserByEmail returns the user object by given e-mail if exists.
  934. func GetUserByEmail(email string) (*User, error) {
  935. if len(email) == 0 {
  936. return nil, ErrUserNotExist{0, email, 0}
  937. }
  938. email = strings.ToLower(email)
  939. // First try to find the user by primary email
  940. user := &User{Email: email}
  941. has, err := x.Get(user)
  942. if err != nil {
  943. return nil, err
  944. }
  945. if has {
  946. return user, nil
  947. }
  948. // Otherwise, check in alternative list for activated email addresses
  949. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  950. has, err = x.Get(emailAddress)
  951. if err != nil {
  952. return nil, err
  953. }
  954. if has {
  955. return GetUserByID(emailAddress.UID)
  956. }
  957. return nil, ErrUserNotExist{0, email, 0}
  958. }
  959. // SearchUserOptions contains the options for searching
  960. type SearchUserOptions struct {
  961. Keyword string
  962. Type UserType
  963. OrderBy string
  964. Page int
  965. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  966. }
  967. // SearchUserByName takes keyword and part of user name to search,
  968. // it returns results in given range and number of total results.
  969. func SearchUserByName(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  970. if len(opts.Keyword) == 0 {
  971. return users, 0, nil
  972. }
  973. opts.Keyword = strings.ToLower(opts.Keyword)
  974. if opts.PageSize <= 0 || opts.PageSize > setting.UI.ExplorePagingNum {
  975. opts.PageSize = setting.UI.ExplorePagingNum
  976. }
  977. if opts.Page <= 0 {
  978. opts.Page = 1
  979. }
  980. searchQuery := "%" + opts.Keyword + "%"
  981. users = make([]*User, 0, opts.PageSize)
  982. // Append conditions
  983. sess := x.
  984. Where("LOWER(lower_name) LIKE ?", searchQuery).
  985. Or("LOWER(full_name) LIKE ?", searchQuery).
  986. And("type = ?", opts.Type)
  987. var countSess xorm.Session
  988. countSess = *sess
  989. count, err := countSess.Count(new(User))
  990. if err != nil {
  991. return nil, 0, fmt.Errorf("Count: %v", err)
  992. }
  993. if len(opts.OrderBy) > 0 {
  994. sess.OrderBy(opts.OrderBy)
  995. }
  996. return users, count, sess.
  997. Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).
  998. Find(&users)
  999. }
  1000. // ___________ .__ .__
  1001. // \_ _____/___ | | | | ______ _ __
  1002. // | __)/ _ \| | | | / _ \ \/ \/ /
  1003. // | \( <_> ) |_| |_( <_> ) /
  1004. // \___ / \____/|____/____/\____/ \/\_/
  1005. // \/
  1006. // Follow represents relations of user and his/her followers.
  1007. type Follow struct {
  1008. ID int64 `xorm:"pk autoincr"`
  1009. UserID int64 `xorm:"UNIQUE(follow)"`
  1010. FollowID int64 `xorm:"UNIQUE(follow)"`
  1011. }
  1012. // IsFollowing returns true if user is following followID.
  1013. func IsFollowing(userID, followID int64) bool {
  1014. has, _ := x.Get(&Follow{UserID: userID, FollowID: followID})
  1015. return has
  1016. }
  1017. // FollowUser marks someone be another's follower.
  1018. func FollowUser(userID, followID int64) (err error) {
  1019. if userID == followID || IsFollowing(userID, followID) {
  1020. return nil
  1021. }
  1022. sess := x.NewSession()
  1023. defer sessionRelease(sess)
  1024. if err = sess.Begin(); err != nil {
  1025. return err
  1026. }
  1027. if _, err = sess.Insert(&Follow{UserID: userID, FollowID: followID}); err != nil {
  1028. return err
  1029. }
  1030. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?", followID); err != nil {
  1031. return err
  1032. }
  1033. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following + 1 WHERE id = ?", userID); err != nil {
  1034. return err
  1035. }
  1036. return sess.Commit()
  1037. }
  1038. // UnfollowUser unmarks someone be another's follower.
  1039. func UnfollowUser(userID, followID int64) (err error) {
  1040. if userID == followID || !IsFollowing(userID, followID) {
  1041. return nil
  1042. }
  1043. sess := x.NewSession()
  1044. defer sessionRelease(sess)
  1045. if err = sess.Begin(); err != nil {
  1046. return err
  1047. }
  1048. if _, err = sess.Delete(&Follow{UserID: userID, FollowID: followID}); err != nil {
  1049. return err
  1050. }
  1051. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?", followID); err != nil {
  1052. return err
  1053. }
  1054. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following - 1 WHERE id = ?", userID); err != nil {
  1055. return err
  1056. }
  1057. return sess.Commit()
  1058. }
  1059. // GetStarredRepos returns the repos starred by a particular user
  1060. func GetStarredRepos(userID int64, private bool) ([]*Repository, error) {
  1061. sess := x.Where("star.uid=?", userID).
  1062. Join("LEFT", "star", "`repository`.id=`star`.repo_id")
  1063. if !private {
  1064. sess = sess.And("is_private=?", false)
  1065. }
  1066. repos := make([]*Repository, 0, 10)
  1067. err := sess.Find(&repos)
  1068. if err != nil {
  1069. return nil, err
  1070. }
  1071. return repos, nil
  1072. }
  1073. // GetWatchedRepos returns the repos watched by a particular user
  1074. func GetWatchedRepos(userID int64, private bool) ([]*Repository, error) {
  1075. sess := x.Where("watch.user_id=?", userID).
  1076. Join("LEFT", "watch", "`repository`.id=`watch`.repo_id")
  1077. if !private {
  1078. sess = sess.And("is_private=?", false)
  1079. }
  1080. repos := make([]*Repository, 0, 10)
  1081. err := sess.Find(&repos)
  1082. if err != nil {
  1083. return nil, err
  1084. }
  1085. return repos, nil
  1086. }