user.go 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111
  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. "encoding/hex"
  10. "errors"
  11. "fmt"
  12. "image"
  13. _ "image/jpeg"
  14. "image/png"
  15. "os"
  16. "path/filepath"
  17. "strings"
  18. "time"
  19. "unicode/utf8"
  20. "github.com/Unknwon/com"
  21. "github.com/go-xorm/xorm"
  22. "github.com/nfnt/resize"
  23. "github.com/gogits/git-module"
  24. "github.com/gogits/gogs/modules/avatar"
  25. "github.com/gogits/gogs/modules/base"
  26. "github.com/gogits/gogs/modules/log"
  27. "github.com/gogits/gogs/modules/markdown"
  28. "github.com/gogits/gogs/modules/setting"
  29. )
  30. type UserType int
  31. const (
  32. USER_TYPE_INDIVIDUAL UserType = iota // Historic reason to make it starts at 0.
  33. USER_TYPE_ORGANIZATION
  34. )
  35. var (
  36. ErrUserNotKeyOwner = errors.New("User does not the owner of public key")
  37. ErrEmailNotExist = errors.New("E-mail does not exist")
  38. ErrEmailNotActivated = errors.New("E-mail address has not been activated")
  39. ErrUserNameIllegal = errors.New("User name contains illegal characters")
  40. ErrLoginSourceNotExist = errors.New("Login source does not exist")
  41. ErrLoginSourceNotActived = errors.New("Login source is not actived")
  42. ErrUnsupportedLoginType = errors.New("Login source is unknown")
  43. )
  44. // User represents the object of individual and member of organization.
  45. type User struct {
  46. ID int64 `xorm:"pk autoincr"`
  47. LowerName string `xorm:"UNIQUE NOT NULL"`
  48. Name string `xorm:"UNIQUE NOT NULL"`
  49. FullName string
  50. // Email is the primary email address (to be used for communication)
  51. Email string `xorm:"NOT NULL"`
  52. Passwd string `xorm:"NOT NULL"`
  53. LoginType LoginType
  54. LoginSource int64 `xorm:"NOT NULL DEFAULT 0"`
  55. LoginName string
  56. Type UserType
  57. OwnedOrgs []*User `xorm:"-"`
  58. Orgs []*User `xorm:"-"`
  59. Repos []*Repository `xorm:"-"`
  60. Location string
  61. Website string
  62. Rands string `xorm:"VARCHAR(10)"`
  63. Salt string `xorm:"VARCHAR(10)"`
  64. Created time.Time `xorm:"-"`
  65. CreatedUnix int64
  66. Updated time.Time `xorm:"-"`
  67. UpdatedUnix int64
  68. // Remember visibility choice for convenience, true for private
  69. LastRepoVisibility bool
  70. // Maximum repository creation limit, -1 means use gloabl default
  71. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1"`
  72. // Permissions
  73. IsActive bool // Activate primary email
  74. IsAdmin bool
  75. AllowGitHook bool
  76. AllowImportLocal bool // Allow migrate repository by local path
  77. ProhibitLogin bool
  78. // Avatar
  79. Avatar string `xorm:"VARCHAR(2048) NOT NULL"`
  80. AvatarEmail string `xorm:"NOT NULL"`
  81. UseCustomAvatar bool
  82. // Counters
  83. NumFollowers int
  84. NumFollowing int `xorm:"NOT NULL DEFAULT 0"`
  85. NumStars int
  86. NumRepos int
  87. // For organization
  88. Description string
  89. NumTeams int
  90. NumMembers int
  91. Teams []*Team `xorm:"-"`
  92. Members []*User `xorm:"-"`
  93. }
  94. func (u *User) BeforeInsert() {
  95. u.CreatedUnix = time.Now().Unix()
  96. u.UpdatedUnix = u.CreatedUnix
  97. }
  98. func (u *User) BeforeUpdate() {
  99. if u.MaxRepoCreation < -1 {
  100. u.MaxRepoCreation = -1
  101. }
  102. u.UpdatedUnix = time.Now().Unix()
  103. }
  104. func (u *User) AfterSet(colName string, _ xorm.Cell) {
  105. switch colName {
  106. case "full_name":
  107. u.FullName = markdown.Sanitizer.Sanitize(u.FullName)
  108. case "created_unix":
  109. u.Created = time.Unix(u.CreatedUnix, 0).Local()
  110. case "updated_unix":
  111. u.Updated = time.Unix(u.UpdatedUnix, 0).Local()
  112. }
  113. }
  114. // returns true if user login type is LOGIN_PLAIN.
  115. func (u *User) IsLocal() bool {
  116. return u.LoginType <= LOGIN_PLAIN
  117. }
  118. // HasForkedRepo checks if user has already forked a repository with given ID.
  119. func (u *User) HasForkedRepo(repoID int64) bool {
  120. _, has := HasForkedRepo(u.ID, repoID)
  121. return has
  122. }
  123. func (u *User) RepoCreationNum() int {
  124. if u.MaxRepoCreation <= -1 {
  125. return setting.Repository.MaxCreationLimit
  126. }
  127. return u.MaxRepoCreation
  128. }
  129. func (u *User) CanCreateRepo() bool {
  130. if u.MaxRepoCreation <= -1 {
  131. if setting.Repository.MaxCreationLimit <= -1 {
  132. return true
  133. }
  134. return u.NumRepos < setting.Repository.MaxCreationLimit
  135. }
  136. return u.NumRepos < u.MaxRepoCreation
  137. }
  138. // CanEditGitHook returns true if user can edit Git hooks.
  139. func (u *User) CanEditGitHook() bool {
  140. return u.IsAdmin || u.AllowGitHook
  141. }
  142. // CanImportLocal returns true if user can migrate repository by local path.
  143. func (u *User) CanImportLocal() bool {
  144. return u.IsAdmin || u.AllowImportLocal
  145. }
  146. // DashboardLink returns the user dashboard page link.
  147. func (u *User) DashboardLink() string {
  148. if u.IsOrganization() {
  149. return setting.AppSubUrl + "/org/" + u.Name + "/dashboard/"
  150. }
  151. return setting.AppSubUrl + "/"
  152. }
  153. // HomeLink returns the user or organization home page link.
  154. func (u *User) HomeLink() string {
  155. return setting.AppSubUrl + "/" + u.Name
  156. }
  157. // GenerateEmailActivateCode generates an activate code based on user information and given e-mail.
  158. func (u *User) GenerateEmailActivateCode(email string) string {
  159. code := base.CreateTimeLimitCode(
  160. com.ToStr(u.ID)+email+u.LowerName+u.Passwd+u.Rands,
  161. setting.Service.ActiveCodeLives, nil)
  162. // Add tail hex username
  163. code += hex.EncodeToString([]byte(u.LowerName))
  164. return code
  165. }
  166. // GenerateActivateCode generates an activate code based on user information.
  167. func (u *User) GenerateActivateCode() string {
  168. return u.GenerateEmailActivateCode(u.Email)
  169. }
  170. // CustomAvatarPath returns user custom avatar file path.
  171. func (u *User) CustomAvatarPath() string {
  172. return filepath.Join(setting.AvatarUploadPath, com.ToStr(u.ID))
  173. }
  174. // GenerateRandomAvatar generates a random avatar for user.
  175. func (u *User) GenerateRandomAvatar() error {
  176. seed := u.Email
  177. if len(seed) == 0 {
  178. seed = u.Name
  179. }
  180. img, err := avatar.RandomImage([]byte(seed))
  181. if err != nil {
  182. return fmt.Errorf("RandomImage: %v", err)
  183. }
  184. if err = os.MkdirAll(filepath.Dir(u.CustomAvatarPath()), os.ModePerm); err != nil {
  185. return fmt.Errorf("MkdirAll: %v", err)
  186. }
  187. fw, err := os.Create(u.CustomAvatarPath())
  188. if err != nil {
  189. return fmt.Errorf("Create: %v", err)
  190. }
  191. defer fw.Close()
  192. if err = png.Encode(fw, img); err != nil {
  193. return fmt.Errorf("Encode: %v", err)
  194. }
  195. log.Info("New random avatar created: %d", u.ID)
  196. return nil
  197. }
  198. func (u *User) RelAvatarLink() string {
  199. defaultImgUrl := "/img/avatar_default.png"
  200. if u.ID == -1 {
  201. return defaultImgUrl
  202. }
  203. switch {
  204. case u.UseCustomAvatar:
  205. if !com.IsExist(u.CustomAvatarPath()) {
  206. return defaultImgUrl
  207. }
  208. return "/avatars/" + com.ToStr(u.ID)
  209. case setting.DisableGravatar, setting.OfflineMode:
  210. if !com.IsExist(u.CustomAvatarPath()) {
  211. if err := u.GenerateRandomAvatar(); err != nil {
  212. log.Error(3, "GenerateRandomAvatar: %v", err)
  213. }
  214. }
  215. return "/avatars/" + com.ToStr(u.ID)
  216. }
  217. return setting.GravatarSource + u.Avatar
  218. }
  219. // AvatarLink returns user avatar link.
  220. func (u *User) AvatarLink() string {
  221. link := u.RelAvatarLink()
  222. if link[0] == '/' && link[1] != '/' {
  223. return strings.TrimSuffix(setting.AppUrl, "/") + link
  224. }
  225. return link
  226. }
  227. // User.GetFollwoers returns range of user's followers.
  228. func (u *User) GetFollowers(page int) ([]*User, error) {
  229. users := make([]*User, 0, ItemsPerPage)
  230. sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("follow.follow_id=?", u.ID)
  231. if setting.UsePostgreSQL {
  232. sess = sess.Join("LEFT", "follow", `"user".id=follow.user_id`)
  233. } else {
  234. sess = sess.Join("LEFT", "follow", "user.id=follow.user_id")
  235. }
  236. return users, sess.Find(&users)
  237. }
  238. func (u *User) IsFollowing(followID int64) bool {
  239. return IsFollowing(u.ID, followID)
  240. }
  241. // GetFollowing returns range of user's following.
  242. func (u *User) GetFollowing(page int) ([]*User, error) {
  243. users := make([]*User, 0, ItemsPerPage)
  244. sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("follow.user_id=?", u.ID)
  245. if setting.UsePostgreSQL {
  246. sess = sess.Join("LEFT", "follow", `"user".id=follow.follow_id`)
  247. } else {
  248. sess = sess.Join("LEFT", "follow", "user.id=follow.follow_id")
  249. }
  250. return users, sess.Find(&users)
  251. }
  252. // NewGitSig generates and returns the signature of given user.
  253. func (u *User) NewGitSig() *git.Signature {
  254. return &git.Signature{
  255. Name: u.Name,
  256. Email: u.Email,
  257. When: time.Now(),
  258. }
  259. }
  260. // EncodePasswd encodes password to safe format.
  261. func (u *User) EncodePasswd() {
  262. newPasswd := base.PBKDF2([]byte(u.Passwd), []byte(u.Salt), 10000, 50, sha256.New)
  263. u.Passwd = fmt.Sprintf("%x", newPasswd)
  264. }
  265. // ValidatePassword checks if given password matches the one belongs to the user.
  266. func (u *User) ValidatePassword(passwd string) bool {
  267. newUser := &User{Passwd: passwd, Salt: u.Salt}
  268. newUser.EncodePasswd()
  269. return u.Passwd == newUser.Passwd
  270. }
  271. // UploadAvatar saves custom avatar for user.
  272. // FIXME: split uploads to different subdirs in case we have massive users.
  273. func (u *User) UploadAvatar(data []byte) error {
  274. img, _, err := image.Decode(bytes.NewReader(data))
  275. if err != nil {
  276. return fmt.Errorf("Decode: %v", err)
  277. }
  278. m := resize.Resize(avatar.AVATAR_SIZE, avatar.AVATAR_SIZE, img, resize.NearestNeighbor)
  279. sess := x.NewSession()
  280. defer sessionRelease(sess)
  281. if err = sess.Begin(); err != nil {
  282. return err
  283. }
  284. u.UseCustomAvatar = true
  285. if err = updateUser(sess, u); err != nil {
  286. return fmt.Errorf("updateUser: %v", err)
  287. }
  288. os.MkdirAll(setting.AvatarUploadPath, os.ModePerm)
  289. fw, err := os.Create(u.CustomAvatarPath())
  290. if err != nil {
  291. return fmt.Errorf("Create: %v", err)
  292. }
  293. defer fw.Close()
  294. if err = png.Encode(fw, m); err != nil {
  295. return fmt.Errorf("Encode: %v", err)
  296. }
  297. return sess.Commit()
  298. }
  299. // DeleteAvatar deletes the user's custom avatar.
  300. func (u *User) DeleteAvatar() error {
  301. log.Trace("DeleteAvatar[%d]: %s", u.ID, u.CustomAvatarPath())
  302. os.Remove(u.CustomAvatarPath())
  303. u.UseCustomAvatar = false
  304. if err := UpdateUser(u); err != nil {
  305. return fmt.Errorf("UpdateUser: %v", err)
  306. }
  307. return nil
  308. }
  309. // IsAdminOfRepo returns true if user has admin or higher access of repository.
  310. func (u *User) IsAdminOfRepo(repo *Repository) bool {
  311. has, err := HasAccess(u, repo, ACCESS_MODE_ADMIN)
  312. if err != nil {
  313. log.Error(3, "HasAccess: %v", err)
  314. }
  315. return has
  316. }
  317. // IsWriterOfRepo returns true if user has write access to given repository.
  318. func (u *User) IsWriterOfRepo(repo *Repository) bool {
  319. has, err := HasAccess(u, repo, ACCESS_MODE_WRITE)
  320. if err != nil {
  321. log.Error(3, "HasAccess: %v", err)
  322. }
  323. return has
  324. }
  325. // IsOrganization returns true if user is actually a organization.
  326. func (u *User) IsOrganization() bool {
  327. return u.Type == USER_TYPE_ORGANIZATION
  328. }
  329. // IsUserOrgOwner returns true if user is in the owner team of given organization.
  330. func (u *User) IsUserOrgOwner(orgId int64) bool {
  331. return IsOrganizationOwner(orgId, u.ID)
  332. }
  333. // IsPublicMember returns true if user public his/her membership in give organization.
  334. func (u *User) IsPublicMember(orgId int64) bool {
  335. return IsPublicMembership(orgId, u.ID)
  336. }
  337. func (u *User) getOrganizationCount(e Engine) (int64, error) {
  338. return e.Where("uid=?", u.ID).Count(new(OrgUser))
  339. }
  340. // GetOrganizationCount returns count of membership of organization of user.
  341. func (u *User) GetOrganizationCount() (int64, error) {
  342. return u.getOrganizationCount(x)
  343. }
  344. // GetRepositories returns repositories that user owns, including private repositories.
  345. func (u *User) GetRepositories(page, pageSize int) (err error) {
  346. u.Repos, err = GetUserRepositories(u.ID, true, page, pageSize)
  347. return err
  348. }
  349. // GetRepositories returns mirror repositories that user owns, including private repositories.
  350. func (u *User) GetMirrorRepositories() ([]*Repository, error) {
  351. return GetUserMirrorRepositories(u.ID)
  352. }
  353. // GetOwnedOrganizations returns all organizations that user owns.
  354. func (u *User) GetOwnedOrganizations() (err error) {
  355. u.OwnedOrgs, err = GetOwnedOrgsByUserID(u.ID)
  356. return err
  357. }
  358. // GetOrganizations returns all organizations that user belongs to.
  359. func (u *User) GetOrganizations(all bool) error {
  360. ous, err := GetOrgUsersByUserID(u.ID, all)
  361. if err != nil {
  362. return err
  363. }
  364. u.Orgs = make([]*User, len(ous))
  365. for i, ou := range ous {
  366. u.Orgs[i], err = GetUserByID(ou.OrgID)
  367. if err != nil {
  368. return err
  369. }
  370. }
  371. return nil
  372. }
  373. // DisplayName returns full name if it's not empty,
  374. // returns username otherwise.
  375. func (u *User) DisplayName() string {
  376. if len(u.FullName) > 0 {
  377. return u.FullName
  378. }
  379. return u.Name
  380. }
  381. func (u *User) ShortName(length int) string {
  382. return base.EllipsisString(u.Name, length)
  383. }
  384. // IsUserExist checks if given user name exist,
  385. // the user name should be noncased unique.
  386. // If uid is presented, then check will rule out that one,
  387. // it is used when update a user name in settings page.
  388. func IsUserExist(uid int64, name string) (bool, error) {
  389. if len(name) == 0 {
  390. return false, nil
  391. }
  392. return x.Where("id!=?", uid).Get(&User{LowerName: strings.ToLower(name)})
  393. }
  394. // GetUserSalt returns a ramdom user salt token.
  395. func GetUserSalt() string {
  396. return base.GetRandomString(10)
  397. }
  398. // NewFakeUser creates and returns a fake user for someone has deleted his/her account.
  399. func NewFakeUser() *User {
  400. return &User{
  401. ID: -1,
  402. Name: "Someone",
  403. LowerName: "someone",
  404. }
  405. }
  406. var (
  407. reversedUsernames = []string{"debug", "raw", "install", "api", "avatar", "user", "org", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin", "new", ".", ".."}
  408. reversedUserPatterns = []string{"*.keys"}
  409. )
  410. // isUsableName checks if name is reserved or pattern of name is not allowed
  411. // based on given reversed names and patterns.
  412. // Names are exact match, patterns can be prefix or suffix match with placeholder '*'.
  413. func isUsableName(names, patterns []string, name string) error {
  414. name = strings.TrimSpace(strings.ToLower(name))
  415. if utf8.RuneCountInString(name) == 0 {
  416. return ErrNameEmpty
  417. }
  418. for i := range names {
  419. if name == names[i] {
  420. return ErrNameReserved{name}
  421. }
  422. }
  423. for _, pat := range patterns {
  424. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  425. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  426. return ErrNamePatternNotAllowed{pat}
  427. }
  428. }
  429. return nil
  430. }
  431. func IsUsableUsername(name string) error {
  432. return isUsableName(reversedUsernames, reversedUserPatterns, name)
  433. }
  434. // CreateUser creates record of a new user.
  435. func CreateUser(u *User) (err error) {
  436. if err = IsUsableUsername(u.Name); err != nil {
  437. return err
  438. }
  439. isExist, err := IsUserExist(0, u.Name)
  440. if err != nil {
  441. return err
  442. } else if isExist {
  443. return ErrUserAlreadyExist{u.Name}
  444. }
  445. u.Email = strings.ToLower(u.Email)
  446. isExist, err = IsEmailUsed(u.Email)
  447. if err != nil {
  448. return err
  449. } else if isExist {
  450. return ErrEmailAlreadyUsed{u.Email}
  451. }
  452. u.LowerName = strings.ToLower(u.Name)
  453. u.AvatarEmail = u.Email
  454. u.Avatar = base.HashEmail(u.AvatarEmail)
  455. u.Rands = GetUserSalt()
  456. u.Salt = GetUserSalt()
  457. u.EncodePasswd()
  458. u.MaxRepoCreation = -1
  459. sess := x.NewSession()
  460. defer sessionRelease(sess)
  461. if err = sess.Begin(); err != nil {
  462. return err
  463. }
  464. if _, err = sess.Insert(u); err != nil {
  465. return err
  466. } else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
  467. return err
  468. }
  469. return sess.Commit()
  470. }
  471. func countUsers(e Engine) int64 {
  472. count, _ := e.Where("type=0").Count(new(User))
  473. return count
  474. }
  475. // CountUsers returns number of users.
  476. func CountUsers() int64 {
  477. return countUsers(x)
  478. }
  479. // Users returns number of users in given page.
  480. func Users(page, pageSize int) ([]*User, error) {
  481. users := make([]*User, 0, pageSize)
  482. return users, x.Limit(pageSize, (page-1)*pageSize).Where("type=0").Asc("id").Find(&users)
  483. }
  484. // get user by erify code
  485. func getVerifyUser(code string) (user *User) {
  486. if len(code) <= base.TimeLimitCodeLength {
  487. return nil
  488. }
  489. // use tail hex username query user
  490. hexStr := code[base.TimeLimitCodeLength:]
  491. if b, err := hex.DecodeString(hexStr); err == nil {
  492. if user, err = GetUserByName(string(b)); user != nil {
  493. return user
  494. }
  495. log.Error(4, "user.getVerifyUser: %v", err)
  496. }
  497. return nil
  498. }
  499. // verify active code when active account
  500. func VerifyUserActiveCode(code string) (user *User) {
  501. minutes := setting.Service.ActiveCodeLives
  502. if user = getVerifyUser(code); user != nil {
  503. // time limit code
  504. prefix := code[:base.TimeLimitCodeLength]
  505. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands
  506. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  507. return user
  508. }
  509. }
  510. return nil
  511. }
  512. // verify active code when active account
  513. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  514. minutes := setting.Service.ActiveCodeLives
  515. if user := getVerifyUser(code); user != nil {
  516. // time limit code
  517. prefix := code[:base.TimeLimitCodeLength]
  518. data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands
  519. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  520. emailAddress := &EmailAddress{Email: email}
  521. if has, _ := x.Get(emailAddress); has {
  522. return emailAddress
  523. }
  524. }
  525. }
  526. return nil
  527. }
  528. // ChangeUserName changes all corresponding setting from old user name to new one.
  529. func ChangeUserName(u *User, newUserName string) (err error) {
  530. if err = IsUsableUsername(newUserName); err != nil {
  531. return err
  532. }
  533. isExist, err := IsUserExist(0, newUserName)
  534. if err != nil {
  535. return err
  536. } else if isExist {
  537. return ErrUserAlreadyExist{newUserName}
  538. }
  539. if err = ChangeUsernameInPullRequests(u.Name, newUserName); err != nil {
  540. return fmt.Errorf("ChangeUsernameInPullRequests: %v", err)
  541. }
  542. // Delete all local copies of repository wiki that user owns.
  543. if err = x.Where("owner_id=?", u.ID).Iterate(new(Repository), func(idx int, bean interface{}) error {
  544. repo := bean.(*Repository)
  545. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  546. return nil
  547. }); err != nil {
  548. return fmt.Errorf("Delete repository wiki local copy: %v", err)
  549. }
  550. return os.Rename(UserPath(u.Name), UserPath(newUserName))
  551. }
  552. func updateUser(e Engine, u *User) error {
  553. // Organization does not need email
  554. if !u.IsOrganization() {
  555. u.Email = strings.ToLower(u.Email)
  556. has, err := e.Where("id!=?", u.ID).And("type=?", u.Type).And("email=?", u.Email).Get(new(User))
  557. if err != nil {
  558. return err
  559. } else if has {
  560. return ErrEmailAlreadyUsed{u.Email}
  561. }
  562. if len(u.AvatarEmail) == 0 {
  563. u.AvatarEmail = u.Email
  564. }
  565. u.Avatar = base.HashEmail(u.AvatarEmail)
  566. }
  567. u.LowerName = strings.ToLower(u.Name)
  568. u.Location = base.TruncateString(u.Location, 255)
  569. u.Website = base.TruncateString(u.Website, 255)
  570. u.Description = base.TruncateString(u.Description, 255)
  571. u.FullName = markdown.Sanitizer.Sanitize(u.FullName)
  572. _, err := e.Id(u.ID).AllCols().Update(u)
  573. return err
  574. }
  575. // UpdateUser updates user's information.
  576. func UpdateUser(u *User) error {
  577. return updateUser(x, u)
  578. }
  579. // deleteBeans deletes all given beans, beans should contain delete conditions.
  580. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  581. for i := range beans {
  582. if _, err = e.Delete(beans[i]); err != nil {
  583. return err
  584. }
  585. }
  586. return nil
  587. }
  588. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  589. func deleteUser(e *xorm.Session, u *User) error {
  590. // Note: A user owns any repository or belongs to any organization
  591. // cannot perform delete operation.
  592. // Check ownership of repository.
  593. count, err := getRepositoryCount(e, u)
  594. if err != nil {
  595. return fmt.Errorf("GetRepositoryCount: %v", err)
  596. } else if count > 0 {
  597. return ErrUserOwnRepos{UID: u.ID}
  598. }
  599. // Check membership of organization.
  600. count, err = u.getOrganizationCount(e)
  601. if err != nil {
  602. return fmt.Errorf("GetOrganizationCount: %v", err)
  603. } else if count > 0 {
  604. return ErrUserHasOrgs{UID: u.ID}
  605. }
  606. // ***** START: Watch *****
  607. watches := make([]*Watch, 0, 10)
  608. if err = e.Find(&watches, &Watch{UserID: u.ID}); err != nil {
  609. return fmt.Errorf("get all watches: %v", err)
  610. }
  611. for i := range watches {
  612. if _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", watches[i].RepoID); err != nil {
  613. return fmt.Errorf("decrease repository watch number[%d]: %v", watches[i].RepoID, err)
  614. }
  615. }
  616. // ***** END: Watch *****
  617. // ***** START: Star *****
  618. stars := make([]*Star, 0, 10)
  619. if err = e.Find(&stars, &Star{UID: u.ID}); err != nil {
  620. return fmt.Errorf("get all stars: %v", err)
  621. }
  622. for i := range stars {
  623. if _, err = e.Exec("UPDATE `repository` SET num_stars=num_stars-1 WHERE id=?", stars[i].RepoID); err != nil {
  624. return fmt.Errorf("decrease repository star number[%d]: %v", stars[i].RepoID, err)
  625. }
  626. }
  627. // ***** END: Star *****
  628. // ***** START: Follow *****
  629. followers := make([]*Follow, 0, 10)
  630. if err = e.Find(&followers, &Follow{UserID: u.ID}); err != nil {
  631. return fmt.Errorf("get all followers: %v", err)
  632. }
  633. for i := range followers {
  634. if _, err = e.Exec("UPDATE `user` SET num_followers=num_followers-1 WHERE id=?", followers[i].UserID); err != nil {
  635. return fmt.Errorf("decrease user follower number[%d]: %v", followers[i].UserID, err)
  636. }
  637. }
  638. // ***** END: Follow *****
  639. if err = deleteBeans(e,
  640. &AccessToken{UID: u.ID},
  641. &Collaboration{UserID: u.ID},
  642. &Access{UserID: u.ID},
  643. &Watch{UserID: u.ID},
  644. &Star{UID: u.ID},
  645. &Follow{FollowID: u.ID},
  646. &Action{UserID: u.ID},
  647. &IssueUser{UID: u.ID},
  648. &EmailAddress{UID: u.ID},
  649. ); err != nil {
  650. return fmt.Errorf("deleteBeans: %v", err)
  651. }
  652. // ***** START: PublicKey *****
  653. keys := make([]*PublicKey, 0, 10)
  654. if err = e.Find(&keys, &PublicKey{OwnerID: u.ID}); err != nil {
  655. return fmt.Errorf("get all public keys: %v", err)
  656. }
  657. keyIDs := make([]int64, len(keys))
  658. for i := range keys {
  659. keyIDs[i] = keys[i].ID
  660. }
  661. if err = deletePublicKeys(e, keyIDs...); err != nil {
  662. return fmt.Errorf("deletePublicKeys: %v", err)
  663. }
  664. // ***** END: PublicKey *****
  665. // Clear assignee.
  666. if _, err = e.Exec("UPDATE `issue` SET assignee_id=0 WHERE assignee_id=?", u.ID); err != nil {
  667. return fmt.Errorf("clear assignee: %v", err)
  668. }
  669. if _, err = e.Id(u.ID).Delete(new(User)); err != nil {
  670. return fmt.Errorf("Delete: %v", err)
  671. }
  672. // FIXME: system notice
  673. // Note: There are something just cannot be roll back,
  674. // so just keep error logs of those operations.
  675. os.RemoveAll(UserPath(u.Name))
  676. os.Remove(u.CustomAvatarPath())
  677. return nil
  678. }
  679. // DeleteUser completely and permanently deletes everything of a user,
  680. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  681. func DeleteUser(u *User) (err error) {
  682. sess := x.NewSession()
  683. defer sessionRelease(sess)
  684. if err = sess.Begin(); err != nil {
  685. return err
  686. }
  687. if err = deleteUser(sess, u); err != nil {
  688. // Note: don't wrapper error here.
  689. return err
  690. }
  691. if err = sess.Commit(); err != nil {
  692. return err
  693. }
  694. return RewriteAllPublicKeys()
  695. }
  696. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  697. func DeleteInactivateUsers() (err error) {
  698. users := make([]*User, 0, 10)
  699. if err = x.Where("is_active = ?", false).Find(&users); err != nil {
  700. return fmt.Errorf("get all inactive users: %v", err)
  701. }
  702. // FIXME: should only update authorized_keys file once after all deletions.
  703. for _, u := range users {
  704. if err = DeleteUser(u); err != nil {
  705. // Ignore users that were set inactive by admin.
  706. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  707. continue
  708. }
  709. return err
  710. }
  711. }
  712. _, err = x.Where("is_activated = ?", false).Delete(new(EmailAddress))
  713. return err
  714. }
  715. // UserPath returns the path absolute path of user repositories.
  716. func UserPath(userName string) string {
  717. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  718. }
  719. func GetUserByKeyID(keyID int64) (*User, error) {
  720. user := new(User)
  721. has, err := x.Sql("SELECT a.* FROM `user` AS a, public_key AS b WHERE a.id = b.owner_id AND b.id=?", keyID).Get(user)
  722. if err != nil {
  723. return nil, err
  724. } else if !has {
  725. return nil, ErrUserNotKeyOwner
  726. }
  727. return user, nil
  728. }
  729. func getUserByID(e Engine, id int64) (*User, error) {
  730. u := new(User)
  731. has, err := e.Id(id).Get(u)
  732. if err != nil {
  733. return nil, err
  734. } else if !has {
  735. return nil, ErrUserNotExist{id, ""}
  736. }
  737. return u, nil
  738. }
  739. // GetUserByID returns the user object by given ID if exists.
  740. func GetUserByID(id int64) (*User, error) {
  741. return getUserByID(x, id)
  742. }
  743. // GetAssigneeByID returns the user with write access of repository by given ID.
  744. func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
  745. has, err := HasAccess(&User{ID: userID}, repo, ACCESS_MODE_WRITE)
  746. if err != nil {
  747. return nil, err
  748. } else if !has {
  749. return nil, ErrUserNotExist{userID, ""}
  750. }
  751. return GetUserByID(userID)
  752. }
  753. // GetUserByName returns user by given name.
  754. func GetUserByName(name string) (*User, error) {
  755. if len(name) == 0 {
  756. return nil, ErrUserNotExist{0, name}
  757. }
  758. u := &User{LowerName: strings.ToLower(name)}
  759. has, err := x.Get(u)
  760. if err != nil {
  761. return nil, err
  762. } else if !has {
  763. return nil, ErrUserNotExist{0, name}
  764. }
  765. return u, nil
  766. }
  767. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  768. func GetUserEmailsByNames(names []string) []string {
  769. mails := make([]string, 0, len(names))
  770. for _, name := range names {
  771. u, err := GetUserByName(name)
  772. if err != nil {
  773. continue
  774. }
  775. mails = append(mails, u.Email)
  776. }
  777. return mails
  778. }
  779. // GetUserIDsByNames returns a slice of ids corresponds to names.
  780. func GetUserIDsByNames(names []string) []int64 {
  781. ids := make([]int64, 0, len(names))
  782. for _, name := range names {
  783. u, err := GetUserByName(name)
  784. if err != nil {
  785. continue
  786. }
  787. ids = append(ids, u.ID)
  788. }
  789. return ids
  790. }
  791. // UserCommit represents a commit with validation of user.
  792. type UserCommit struct {
  793. User *User
  794. *git.Commit
  795. }
  796. // ValidateCommitWithEmail chceck if author's e-mail of commit is corresponsind to a user.
  797. func ValidateCommitWithEmail(c *git.Commit) *User {
  798. u, err := GetUserByEmail(c.Author.Email)
  799. if err != nil {
  800. return nil
  801. }
  802. return u
  803. }
  804. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  805. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  806. var (
  807. u *User
  808. emails = map[string]*User{}
  809. newCommits = list.New()
  810. e = oldCommits.Front()
  811. )
  812. for e != nil {
  813. c := e.Value.(*git.Commit)
  814. if v, ok := emails[c.Author.Email]; !ok {
  815. u, _ = GetUserByEmail(c.Author.Email)
  816. emails[c.Author.Email] = u
  817. } else {
  818. u = v
  819. }
  820. newCommits.PushBack(UserCommit{
  821. User: u,
  822. Commit: c,
  823. })
  824. e = e.Next()
  825. }
  826. return newCommits
  827. }
  828. // GetUserByEmail returns the user object by given e-mail if exists.
  829. func GetUserByEmail(email string) (*User, error) {
  830. if len(email) == 0 {
  831. return nil, ErrUserNotExist{0, "email"}
  832. }
  833. email = strings.ToLower(email)
  834. // First try to find the user by primary email
  835. user := &User{Email: email}
  836. has, err := x.Get(user)
  837. if err != nil {
  838. return nil, err
  839. }
  840. if has {
  841. return user, nil
  842. }
  843. // Otherwise, check in alternative list for activated email addresses
  844. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  845. has, err = x.Get(emailAddress)
  846. if err != nil {
  847. return nil, err
  848. }
  849. if has {
  850. return GetUserByID(emailAddress.UID)
  851. }
  852. return nil, ErrUserNotExist{0, email}
  853. }
  854. type SearchUserOptions struct {
  855. Keyword string
  856. Type UserType
  857. OrderBy string
  858. Page int
  859. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  860. }
  861. // SearchUserByName takes keyword and part of user name to search,
  862. // it returns results in given range and number of total results.
  863. func SearchUserByName(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  864. if len(opts.Keyword) == 0 {
  865. return users, 0, nil
  866. }
  867. opts.Keyword = strings.ToLower(opts.Keyword)
  868. if opts.PageSize <= 0 || opts.PageSize > setting.UI.ExplorePagingNum {
  869. opts.PageSize = setting.UI.ExplorePagingNum
  870. }
  871. if opts.Page <= 0 {
  872. opts.Page = 1
  873. }
  874. searchQuery := "%" + opts.Keyword + "%"
  875. users = make([]*User, 0, opts.PageSize)
  876. // Append conditions
  877. sess := x.Where("LOWER(lower_name) LIKE ?", searchQuery).
  878. Or("LOWER(full_name) LIKE ?", searchQuery).
  879. And("type = ?", opts.Type)
  880. var countSess xorm.Session
  881. countSess = *sess
  882. count, err := countSess.Count(new(User))
  883. if err != nil {
  884. return nil, 0, fmt.Errorf("Count: %v", err)
  885. }
  886. if len(opts.OrderBy) > 0 {
  887. sess.OrderBy(opts.OrderBy)
  888. }
  889. return users, count, sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).Find(&users)
  890. }
  891. // ___________ .__ .__
  892. // \_ _____/___ | | | | ______ _ __
  893. // | __)/ _ \| | | | / _ \ \/ \/ /
  894. // | \( <_> ) |_| |_( <_> ) /
  895. // \___ / \____/|____/____/\____/ \/\_/
  896. // \/
  897. // Follow represents relations of user and his/her followers.
  898. type Follow struct {
  899. ID int64 `xorm:"pk autoincr"`
  900. UserID int64 `xorm:"UNIQUE(follow)"`
  901. FollowID int64 `xorm:"UNIQUE(follow)"`
  902. }
  903. func IsFollowing(userID, followID int64) bool {
  904. has, _ := x.Get(&Follow{UserID: userID, FollowID: followID})
  905. return has
  906. }
  907. // FollowUser marks someone be another's follower.
  908. func FollowUser(userID, followID int64) (err error) {
  909. if userID == followID || IsFollowing(userID, followID) {
  910. return nil
  911. }
  912. sess := x.NewSession()
  913. defer sessionRelease(sess)
  914. if err = sess.Begin(); err != nil {
  915. return err
  916. }
  917. if _, err = sess.Insert(&Follow{UserID: userID, FollowID: followID}); err != nil {
  918. return err
  919. }
  920. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?", followID); err != nil {
  921. return err
  922. }
  923. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following + 1 WHERE id = ?", userID); err != nil {
  924. return err
  925. }
  926. return sess.Commit()
  927. }
  928. // UnfollowUser unmarks someone be another's follower.
  929. func UnfollowUser(userID, followID int64) (err error) {
  930. if userID == followID || !IsFollowing(userID, followID) {
  931. return nil
  932. }
  933. sess := x.NewSession()
  934. defer sessionRelease(sess)
  935. if err = sess.Begin(); err != nil {
  936. return err
  937. }
  938. if _, err = sess.Delete(&Follow{UserID: userID, FollowID: followID}); err != nil {
  939. return err
  940. }
  941. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?", followID); err != nil {
  942. return err
  943. }
  944. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following - 1 WHERE id = ?", userID); err != nil {
  945. return err
  946. }
  947. return sess.Commit()
  948. }