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

user.go 23 kB

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