user.go 30 KB

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