You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

user.go 18KB

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