user.go 30 KB

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