user.go 25 KB

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