user.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  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. "os"
  15. "path/filepath"
  16. "strings"
  17. "time"
  18. "github.com/Unknwon/com"
  19. "github.com/nfnt/resize"
  20. "github.com/gogits/gogs/modules/avatar"
  21. "github.com/gogits/gogs/modules/base"
  22. "github.com/gogits/gogs/modules/git"
  23. "github.com/gogits/gogs/modules/log"
  24. "github.com/gogits/gogs/modules/setting"
  25. )
  26. type UserType int
  27. const (
  28. INDIVIDUAL UserType = iota // Historic reason to make it starts at 0.
  29. ORGANIZATION
  30. )
  31. var (
  32. ErrUserOwnRepos = errors.New("User still have ownership of repositories")
  33. ErrUserHasOrgs = errors.New("User still have membership of organization")
  34. ErrUserAlreadyExist = errors.New("User already exist")
  35. ErrUserNotExist = errors.New("User does not exist")
  36. ErrUserNotKeyOwner = errors.New("User does not the owner of public key")
  37. ErrEmailAlreadyUsed = errors.New("E-mail already used")
  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:"UNIQUE(s) 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 `xorm:"UNIQUE(s)"`
  56. Orgs []*User `xorm:"-"`
  57. Repos []*Repository `xorm:"-"`
  58. Location string
  59. Website string
  60. Rands string `xorm:"VARCHAR(10)"`
  61. Salt string `xorm:"VARCHAR(10)"`
  62. Created time.Time `xorm:"CREATED"`
  63. Updated time.Time `xorm:"UPDATED"`
  64. // Permissions.
  65. IsActive bool
  66. IsAdmin bool
  67. AllowGitHook bool
  68. // Avatar.
  69. Avatar string `xorm:"VARCHAR(2048) NOT NULL"`
  70. AvatarEmail string `xorm:"NOT NULL"`
  71. UseCustomAvatar bool
  72. // Counters.
  73. NumFollowers int
  74. NumFollowings int
  75. NumStars int
  76. NumRepos int
  77. // For organization.
  78. Description string
  79. NumTeams int
  80. NumMembers int
  81. Teams []*Team `xorm:"-"`
  82. Members []*User `xorm:"-"`
  83. }
  84. // EmailAdresses is the list of all email addresses of a user. Can contain the
  85. // primary email address, but is not obligatory
  86. type EmailAddress struct {
  87. Id int64
  88. OwnerId int64 `xorm:"INDEX NOT NULL"`
  89. Email string `xorm:"UNIQUE NOT NULL"`
  90. IsActivated bool
  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 home page link.
  100. func (u *User) HomeLink() string {
  101. return setting.AppSubUrl + "/" + u.Name
  102. }
  103. // AvatarLink returns user gravatar link.
  104. func (u *User) AvatarLink() string {
  105. switch {
  106. case u.UseCustomAvatar:
  107. return setting.AppSubUrl + "/avatars/" + com.ToStr(u.Id)
  108. case setting.DisableGravatar:
  109. return setting.AppSubUrl + "/img/avatar_default.jpg"
  110. case setting.Service.EnableCacheAvatar:
  111. return setting.AppSubUrl + "/avatar/" + u.Avatar
  112. }
  113. return setting.GravatarSource + u.Avatar
  114. }
  115. // NewGitSig generates and returns the signature of given user.
  116. func (u *User) NewGitSig() *git.Signature {
  117. return &git.Signature{
  118. Name: u.Name,
  119. Email: u.Email,
  120. When: time.Now(),
  121. }
  122. }
  123. // EncodePasswd encodes password to safe format.
  124. func (u *User) EncodePasswd() {
  125. newPasswd := base.PBKDF2([]byte(u.Passwd), []byte(u.Salt), 10000, 50, sha256.New)
  126. u.Passwd = fmt.Sprintf("%x", newPasswd)
  127. }
  128. // ValidtePassword checks if given password matches the one belongs to the user.
  129. func (u *User) ValidtePassword(passwd string) bool {
  130. newUser := &User{Passwd: passwd, Salt: u.Salt}
  131. newUser.EncodePasswd()
  132. return u.Passwd == newUser.Passwd
  133. }
  134. // CustomAvatarPath returns user custom avatar file path.
  135. func (u *User) CustomAvatarPath() string {
  136. return filepath.Join(setting.AvatarUploadPath, com.ToStr(u.Id))
  137. }
  138. // UploadAvatar saves custom avatar for user.
  139. // FIXME: split uploads to different subdirs in case we have massive users.
  140. func (u *User) UploadAvatar(data []byte) error {
  141. u.UseCustomAvatar = true
  142. img, _, err := image.Decode(bytes.NewReader(data))
  143. if err != nil {
  144. return err
  145. }
  146. m := resize.Resize(200, 200, img, resize.NearestNeighbor)
  147. sess := x.NewSession()
  148. defer sess.Close()
  149. if err = sess.Begin(); err != nil {
  150. return err
  151. }
  152. if _, err = sess.Id(u.Id).AllCols().Update(u); err != nil {
  153. sess.Rollback()
  154. return err
  155. }
  156. os.MkdirAll(setting.AvatarUploadPath, os.ModePerm)
  157. fw, err := os.Create(u.CustomAvatarPath())
  158. if err != nil {
  159. sess.Rollback()
  160. return err
  161. }
  162. defer fw.Close()
  163. if err = jpeg.Encode(fw, m, nil); err != nil {
  164. sess.Rollback()
  165. return err
  166. }
  167. return sess.Commit()
  168. }
  169. // IsOrganization returns true if user is actually a organization.
  170. func (u *User) IsOrganization() bool {
  171. return u.Type == ORGANIZATION
  172. }
  173. // IsUserOrgOwner returns true if user is in the owner team of given organization.
  174. func (u *User) IsUserOrgOwner(orgId int64) bool {
  175. return IsOrganizationOwner(orgId, u.Id)
  176. }
  177. // IsPublicMember returns true if user public his/her membership in give organization.
  178. func (u *User) IsPublicMember(orgId int64) bool {
  179. return IsPublicMembership(orgId, u.Id)
  180. }
  181. // GetOrganizationCount returns count of membership of organization of user.
  182. func (u *User) GetOrganizationCount() (int64, error) {
  183. return x.Where("uid=?", u.Id).Count(new(OrgUser))
  184. }
  185. // GetRepositories returns all repositories that user owns, including private repositories.
  186. func (u *User) GetRepositories() (err error) {
  187. u.Repos, err = GetRepositories(u.Id, true)
  188. return err
  189. }
  190. // GetOrganizations returns all organizations that user belongs to.
  191. func (u *User) GetOrganizations() error {
  192. ous, err := GetOrgUsersByUserId(u.Id)
  193. if err != nil {
  194. return err
  195. }
  196. u.Orgs = make([]*User, len(ous))
  197. for i, ou := range ous {
  198. u.Orgs[i], err = GetUserById(ou.OrgId)
  199. if err != nil {
  200. return err
  201. }
  202. }
  203. return nil
  204. }
  205. // GetFullNameFallback returns Full Name if set, otherwise username
  206. func (u *User) GetFullNameFallback() string {
  207. if u.FullName == "" {
  208. return u.Name
  209. }
  210. return u.FullName
  211. }
  212. // IsUserExist checks if given user name exist,
  213. // the user name should be noncased unique.
  214. func IsUserExist(name string) (bool, error) {
  215. if len(name) == 0 {
  216. return false, nil
  217. }
  218. return x.Get(&User{LowerName: strings.ToLower(name)})
  219. }
  220. // IsEmailUsed returns true if the e-mail has been used.
  221. func IsEmailUsed(email string) (bool, error) {
  222. if len(email) == 0 {
  223. return false, nil
  224. }
  225. if used, err := x.Get(&EmailAddress{Email: email}); used || err != nil {
  226. return used, err
  227. }
  228. return x.Get(&User{Email: email})
  229. }
  230. // GetUserSalt returns a ramdom user salt token.
  231. func GetUserSalt() string {
  232. return base.GetRandomString(10)
  233. }
  234. // CreateUser creates record of a new user.
  235. func CreateUser(u *User) error {
  236. if !IsLegalName(u.Name) {
  237. return ErrUserNameIllegal
  238. }
  239. isExist, err := IsUserExist(u.Name)
  240. if err != nil {
  241. return err
  242. } else if isExist {
  243. return ErrUserAlreadyExist
  244. }
  245. isExist, err = IsEmailUsed(u.Email)
  246. if err != nil {
  247. return err
  248. } else if isExist {
  249. return ErrEmailAlreadyUsed
  250. }
  251. u.LowerName = strings.ToLower(u.Name)
  252. u.AvatarEmail = u.Email
  253. u.Avatar = avatar.HashEmail(u.AvatarEmail)
  254. u.Rands = GetUserSalt()
  255. u.Salt = GetUserSalt()
  256. u.EncodePasswd()
  257. sess := x.NewSession()
  258. defer sess.Close()
  259. if err = sess.Begin(); err != nil {
  260. return err
  261. }
  262. if _, err = sess.Insert(u); err != nil {
  263. sess.Rollback()
  264. return err
  265. } else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
  266. sess.Rollback()
  267. return err
  268. } else if err = sess.Commit(); err != nil {
  269. return err
  270. }
  271. // Auto-set admin for user whose ID is 1.
  272. if u.Id == 1 {
  273. u.IsAdmin = true
  274. u.IsActive = true
  275. _, err = x.Id(u.Id).UseBool().Update(u)
  276. }
  277. return err
  278. }
  279. // CountUsers returns number of users.
  280. func CountUsers() int64 {
  281. count, _ := x.Where("type=0").Count(new(User))
  282. return count
  283. }
  284. // GetUsers returns given number of user objects with offset.
  285. func GetUsers(num, offset int) ([]*User, error) {
  286. users := make([]*User, 0, num)
  287. err := x.Limit(num, offset).Where("type=0").Asc("id").Find(&users)
  288. return users, err
  289. }
  290. // get user by erify code
  291. func getVerifyUser(code string) (user *User) {
  292. if len(code) <= base.TimeLimitCodeLength {
  293. return nil
  294. }
  295. // use tail hex username query user
  296. hexStr := code[base.TimeLimitCodeLength:]
  297. if b, err := hex.DecodeString(hexStr); err == nil {
  298. if user, err = GetUserByName(string(b)); user != nil {
  299. return user
  300. }
  301. log.Error(4, "user.getVerifyUser: %v", err)
  302. }
  303. return nil
  304. }
  305. // verify active code when active account
  306. func VerifyUserActiveCode(code string) (user *User) {
  307. minutes := setting.Service.ActiveCodeLives
  308. if user = getVerifyUser(code); user != nil {
  309. // time limit code
  310. prefix := code[:base.TimeLimitCodeLength]
  311. data := com.ToStr(user.Id) + user.Email + user.LowerName + user.Passwd + user.Rands
  312. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  313. return user
  314. }
  315. }
  316. return nil
  317. }
  318. // ChangeUserName changes all corresponding setting from old user name to new one.
  319. func ChangeUserName(u *User, newUserName string) (err error) {
  320. if !IsLegalName(newUserName) {
  321. return ErrUserNameIllegal
  322. }
  323. newUserName = strings.ToLower(newUserName)
  324. // Update accesses of user.
  325. accesses := make([]Access, 0, 10)
  326. if err = x.Find(&accesses, &Access{UserName: u.LowerName}); err != nil {
  327. return err
  328. }
  329. sess := x.NewSession()
  330. defer sess.Close()
  331. if err = sess.Begin(); err != nil {
  332. return err
  333. }
  334. for i := range accesses {
  335. accesses[i].UserName = newUserName
  336. if strings.HasPrefix(accesses[i].RepoName, u.LowerName+"/") {
  337. accesses[i].RepoName = strings.Replace(accesses[i].RepoName, u.LowerName, newUserName, 1)
  338. }
  339. if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil {
  340. return err
  341. }
  342. }
  343. repos, err := GetRepositories(u.Id, true)
  344. if err != nil {
  345. return err
  346. }
  347. for i := range repos {
  348. accesses = make([]Access, 0, 10)
  349. // Update accesses of user repository.
  350. if err = x.Find(&accesses, &Access{RepoName: u.LowerName + "/" + repos[i].LowerName}); err != nil {
  351. return err
  352. }
  353. for j := range accesses {
  354. // if the access is not the user's access (already updated above)
  355. if accesses[j].UserName != u.LowerName {
  356. accesses[j].RepoName = newUserName + "/" + repos[i].LowerName
  357. if err = UpdateAccessWithSession(sess, &accesses[j]); err != nil {
  358. return err
  359. }
  360. }
  361. }
  362. }
  363. // Change user directory name.
  364. if err = os.Rename(UserPath(u.LowerName), UserPath(newUserName)); err != nil {
  365. sess.Rollback()
  366. return err
  367. }
  368. return sess.Commit()
  369. }
  370. // UpdateUser updates user's information.
  371. func UpdateUser(u *User) error {
  372. has, err := x.Where("id != ?", u.Id).And("email = ?", u.Email).Get(new(User))
  373. if err != nil {
  374. return err
  375. } else if has {
  376. return ErrEmailAlreadyUsed
  377. }
  378. u.LowerName = strings.ToLower(u.Name)
  379. if len(u.Location) > 255 {
  380. u.Location = u.Location[:255]
  381. }
  382. if len(u.Website) > 255 {
  383. u.Website = u.Website[:255]
  384. }
  385. if len(u.Description) > 255 {
  386. u.Description = u.Description[:255]
  387. }
  388. if u.AvatarEmail == "" {
  389. u.AvatarEmail = u.Email
  390. }
  391. u.Avatar = avatar.HashEmail(u.AvatarEmail)
  392. _, err = x.Id(u.Id).AllCols().Update(u)
  393. return err
  394. }
  395. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  396. // DeleteUser completely and permanently deletes everything of user.
  397. func DeleteUser(u *User) error {
  398. // Check ownership of repository.
  399. count, err := GetRepositoryCount(u)
  400. if err != nil {
  401. return errors.New("GetRepositoryCount: " + err.Error())
  402. } else if count > 0 {
  403. return ErrUserOwnRepos
  404. }
  405. // Check membership of organization.
  406. count, err = u.GetOrganizationCount()
  407. if err != nil {
  408. return errors.New("GetOrganizationCount: " + err.Error())
  409. } else if count > 0 {
  410. return ErrUserHasOrgs
  411. }
  412. // FIXME: check issues, other repos' commits
  413. // FIXME: roll backable in some point.
  414. // Delete all followers.
  415. if _, err = x.Delete(&Follow{FollowId: u.Id}); err != nil {
  416. return err
  417. }
  418. // Delete oauth2.
  419. if _, err = x.Delete(&Oauth2{Uid: u.Id}); err != nil {
  420. return err
  421. }
  422. // Delete all feeds.
  423. if _, err = x.Delete(&Action{UserId: u.Id}); err != nil {
  424. return err
  425. }
  426. // Delete all watches.
  427. if _, err = x.Delete(&Watch{UserId: u.Id}); err != nil {
  428. return err
  429. }
  430. // Delete all accesses.
  431. if _, err = x.Delete(&Access{UserName: u.LowerName}); err != nil {
  432. return err
  433. }
  434. // Delete all alternative email addresses
  435. if _, err = x.Delete(&EmailAddress{OwnerId: u.Id}); err != nil {
  436. return err
  437. }
  438. // Delete all SSH keys.
  439. keys := make([]*PublicKey, 0, 10)
  440. if err = x.Find(&keys, &PublicKey{OwnerId: u.Id}); err != nil {
  441. return err
  442. }
  443. for _, key := range keys {
  444. if err = DeletePublicKey(key); err != nil {
  445. return err
  446. }
  447. }
  448. // Delete user directory.
  449. if err = os.RemoveAll(UserPath(u.Name)); err != nil {
  450. return err
  451. }
  452. _, err = x.Delete(u)
  453. return err
  454. }
  455. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  456. func DeleteInactivateUsers() error {
  457. _, err := x.Where("is_active=?", false).Delete(new(User))
  458. if err == nil {
  459. _, err = x.Delete(&EmailAddress{IsActivated: false})
  460. }
  461. return err
  462. }
  463. // UserPath returns the path absolute path of user repositories.
  464. func UserPath(userName string) string {
  465. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  466. }
  467. func GetUserByKeyId(keyId int64) (*User, error) {
  468. user := new(User)
  469. rawSql := "SELECT a.* FROM `user` AS a, public_key AS b WHERE a.id = b.owner_id AND b.id=?"
  470. has, err := x.Sql(rawSql, keyId).Get(user)
  471. if err != nil {
  472. return nil, err
  473. } else if !has {
  474. return nil, ErrUserNotKeyOwner
  475. }
  476. return user, nil
  477. }
  478. // GetUserById returns the user object by given ID if exists.
  479. func GetUserById(id int64) (*User, error) {
  480. u := new(User)
  481. has, err := x.Id(id).Get(u)
  482. if err != nil {
  483. return nil, err
  484. } else if !has {
  485. return nil, ErrUserNotExist
  486. }
  487. return u, nil
  488. }
  489. // GetUserByName returns user by given name.
  490. func GetUserByName(name string) (*User, error) {
  491. if len(name) == 0 {
  492. return nil, ErrUserNotExist
  493. }
  494. u := &User{LowerName: strings.ToLower(name)}
  495. has, err := x.Get(u)
  496. if err != nil {
  497. return nil, err
  498. } else if !has {
  499. return nil, ErrUserNotExist
  500. }
  501. return u, nil
  502. }
  503. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  504. func GetUserEmailsByNames(names []string) []string {
  505. mails := make([]string, 0, len(names))
  506. for _, name := range names {
  507. u, err := GetUserByName(name)
  508. if err != nil {
  509. continue
  510. }
  511. mails = append(mails, u.Email)
  512. }
  513. return mails
  514. }
  515. // GetUserIdsByNames returns a slice of ids corresponds to names.
  516. func GetUserIdsByNames(names []string) []int64 {
  517. ids := make([]int64, 0, len(names))
  518. for _, name := range names {
  519. u, err := GetUserByName(name)
  520. if err != nil {
  521. continue
  522. }
  523. ids = append(ids, u.Id)
  524. }
  525. return ids
  526. }
  527. // UserCommit represents a commit with validation of user.
  528. type UserCommit struct {
  529. User *User
  530. *git.Commit
  531. }
  532. // ValidateCommitWithEmail chceck if author's e-mail of commit is corresponsind to a user.
  533. func ValidateCommitWithEmail(c *git.Commit) *User {
  534. u, err := GetUserByEmail(c.Author.Email)
  535. if err != nil {
  536. return nil
  537. }
  538. return u
  539. }
  540. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  541. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  542. emails := map[string]*User{}
  543. newCommits := list.New()
  544. e := oldCommits.Front()
  545. for e != nil {
  546. c := e.Value.(*git.Commit)
  547. var u *User
  548. if v, ok := emails[c.Author.Email]; !ok {
  549. u, _ = GetUserByEmail(c.Author.Email)
  550. emails[c.Author.Email] = u
  551. } else {
  552. u = v
  553. }
  554. newCommits.PushBack(UserCommit{
  555. User: u,
  556. Commit: c,
  557. })
  558. e = e.Next()
  559. }
  560. return newCommits
  561. }
  562. // GetUserByEmail returns the user object by given e-mail if exists.
  563. func GetUserByEmail(email string) (*User, error) {
  564. if len(email) == 0 {
  565. return nil, ErrUserNotExist
  566. }
  567. // First try to find the user by primary email
  568. user := &User{Email: strings.ToLower(email)}
  569. has, err := x.Get(user)
  570. if err != nil {
  571. return nil, err
  572. }
  573. if has {
  574. return user, nil
  575. }
  576. // Otherwise, check in alternative list for activated email addresses
  577. emailAddress := &EmailAddress{Email: strings.ToLower(email), IsActivated: true}
  578. has, err = x.Get(emailAddress)
  579. if err != nil {
  580. return nil, err
  581. }
  582. if has {
  583. return GetUserById(emailAddress.OwnerId)
  584. }
  585. return nil, ErrUserNotExist
  586. }
  587. // SearchUserByName returns given number of users whose name contains keyword.
  588. func SearchUserByName(opt SearchOption) (us []*User, err error) {
  589. if len(opt.Keyword) == 0 {
  590. return us, nil
  591. }
  592. opt.Keyword = strings.ToLower(opt.Keyword)
  593. us = make([]*User, 0, opt.Limit)
  594. err = x.Limit(opt.Limit).Where("type=0").And("lower_name like ?", "%"+opt.Keyword+"%").Find(&us)
  595. return us, err
  596. }
  597. // Follow is connection request for receiving user notification.
  598. type Follow struct {
  599. Id int64
  600. UserId int64 `xorm:"unique(follow)"`
  601. FollowId int64 `xorm:"unique(follow)"`
  602. }
  603. // FollowUser marks someone be another's follower.
  604. func FollowUser(userId int64, followId int64) (err error) {
  605. sess := x.NewSession()
  606. defer sess.Close()
  607. sess.Begin()
  608. if _, err = sess.Insert(&Follow{UserId: userId, FollowId: followId}); err != nil {
  609. sess.Rollback()
  610. return err
  611. }
  612. rawSql := "UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?"
  613. if _, err = sess.Exec(rawSql, followId); err != nil {
  614. sess.Rollback()
  615. return err
  616. }
  617. rawSql = "UPDATE `user` SET num_followings = num_followings + 1 WHERE id = ?"
  618. if _, err = sess.Exec(rawSql, userId); err != nil {
  619. sess.Rollback()
  620. return err
  621. }
  622. return sess.Commit()
  623. }
  624. // UnFollowUser unmarks someone be another's follower.
  625. func UnFollowUser(userId int64, unFollowId int64) (err error) {
  626. session := x.NewSession()
  627. defer session.Close()
  628. session.Begin()
  629. if _, err = session.Delete(&Follow{UserId: userId, FollowId: unFollowId}); err != nil {
  630. session.Rollback()
  631. return err
  632. }
  633. rawSql := "UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?"
  634. if _, err = session.Exec(rawSql, unFollowId); err != nil {
  635. session.Rollback()
  636. return err
  637. }
  638. rawSql = "UPDATE `user` SET num_followings = num_followings - 1 WHERE id = ?"
  639. if _, err = session.Exec(rawSql, userId); err != nil {
  640. session.Rollback()
  641. return err
  642. }
  643. return session.Commit()
  644. }
  645. func UpdateMentions(userNames []string, issueId int64) error {
  646. users := make([]*User, 0, len(userNames))
  647. if err := x.Where("name IN (?)", strings.Join(userNames, "\",\"")).OrderBy("name ASC").Find(&users); err != nil {
  648. return err
  649. }
  650. ids := make([]int64, 0, len(userNames))
  651. for _, user := range users {
  652. ids = append(ids, user.Id)
  653. if user.Type == INDIVIDUAL {
  654. continue
  655. }
  656. if user.NumMembers == 0 {
  657. continue
  658. }
  659. tempIds := make([]int64, 0, user.NumMembers)
  660. orgUsers, err := GetOrgUsersByOrgId(user.Id)
  661. if err != nil {
  662. return err
  663. }
  664. for _, orgUser := range orgUsers {
  665. tempIds = append(tempIds, orgUser.Id)
  666. }
  667. ids = append(ids, tempIds...)
  668. }
  669. if err := UpdateIssueUserPairsByMentions(ids, issueId); err != nil {
  670. return err
  671. }
  672. return nil
  673. }