user.go 18 KB

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