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

12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
11 years ago
11 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
11 years ago
11 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
11 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
11 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
11 years ago
12 years ago
11 years ago
12 years ago
12 years ago
12 years ago
11 years ago
11 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  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. func IsUserExist(name string) (bool, error) {
  218. if len(name) == 0 {
  219. return false, nil
  220. }
  221. return x.Get(&User{LowerName: strings.ToLower(name)})
  222. }
  223. // IsEmailUsed returns true if the e-mail has been used.
  224. func IsEmailUsed(email string) (bool, error) {
  225. if len(email) == 0 {
  226. return false, nil
  227. }
  228. if has, err := x.Get(&EmailAddress{Email: email}); has || err != nil {
  229. return has, err
  230. }
  231. return x.Get(&User{Email: email})
  232. }
  233. // GetUserSalt returns a ramdom user salt token.
  234. func GetUserSalt() string {
  235. return base.GetRandomString(10)
  236. }
  237. // CreateUser creates record of a new user.
  238. func CreateUser(u *User) error {
  239. if !IsLegalName(u.Name) {
  240. return ErrUserNameIllegal
  241. }
  242. isExist, err := IsUserExist(u.Name)
  243. if err != nil {
  244. return err
  245. } else if isExist {
  246. return ErrUserAlreadyExist
  247. }
  248. isExist, err = IsEmailUsed(u.Email)
  249. if err != nil {
  250. return err
  251. } else if isExist {
  252. return ErrEmailAlreadyUsed
  253. }
  254. u.LowerName = strings.ToLower(u.Name)
  255. u.AvatarEmail = u.Email
  256. u.Avatar = avatar.HashEmail(u.AvatarEmail)
  257. u.Rands = GetUserSalt()
  258. u.Salt = GetUserSalt()
  259. u.EncodePasswd()
  260. sess := x.NewSession()
  261. defer sess.Close()
  262. if err = sess.Begin(); err != nil {
  263. return err
  264. }
  265. if _, err = sess.Insert(u); err != nil {
  266. sess.Rollback()
  267. return err
  268. } else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
  269. sess.Rollback()
  270. return err
  271. } else if err = sess.Commit(); err != nil {
  272. return err
  273. }
  274. // Auto-set admin for user whose ID is 1.
  275. if u.Id == 1 {
  276. u.IsAdmin = true
  277. u.IsActive = true
  278. _, err = x.Id(u.Id).UseBool().Update(u)
  279. }
  280. return err
  281. }
  282. // CountUsers returns number of users.
  283. func CountUsers() int64 {
  284. count, _ := x.Where("type=0").Count(new(User))
  285. return count
  286. }
  287. // GetUsers returns given number of user objects with offset.
  288. func GetUsers(num, offset int) ([]*User, error) {
  289. users := make([]*User, 0, num)
  290. err := x.Limit(num, offset).Where("type=0").Asc("id").Find(&users)
  291. return users, err
  292. }
  293. // get user by erify code
  294. func getVerifyUser(code string) (user *User) {
  295. if len(code) <= base.TimeLimitCodeLength {
  296. return nil
  297. }
  298. // use tail hex username query user
  299. hexStr := code[base.TimeLimitCodeLength:]
  300. if b, err := hex.DecodeString(hexStr); err == nil {
  301. if user, err = GetUserByName(string(b)); user != nil {
  302. return user
  303. }
  304. log.Error(4, "user.getVerifyUser: %v", err)
  305. }
  306. return nil
  307. }
  308. // verify active code when active account
  309. func VerifyUserActiveCode(code string) (user *User) {
  310. minutes := setting.Service.ActiveCodeLives
  311. if user = getVerifyUser(code); user != nil {
  312. // time limit code
  313. prefix := code[:base.TimeLimitCodeLength]
  314. data := com.ToStr(user.Id) + user.Email + user.LowerName + user.Passwd + user.Rands
  315. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  316. return user
  317. }
  318. }
  319. return nil
  320. }
  321. // verify active code when active account
  322. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  323. minutes := setting.Service.ActiveCodeLives
  324. if user := getVerifyUser(code); user != nil {
  325. // time limit code
  326. prefix := code[:base.TimeLimitCodeLength]
  327. data := com.ToStr(user.Id) + email + user.LowerName + user.Passwd + user.Rands
  328. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  329. emailAddress := &EmailAddress{Email: email}
  330. if has, _ := x.Get(emailAddress); has {
  331. return emailAddress
  332. }
  333. }
  334. }
  335. return nil
  336. }
  337. // ChangeUserName changes all corresponding setting from old user name to new one.
  338. func ChangeUserName(u *User, newUserName string) (err error) {
  339. if !IsLegalName(newUserName) {
  340. return ErrUserNameIllegal
  341. }
  342. newUserName = strings.ToLower(newUserName)
  343. // Update accesses of user.
  344. accesses := make([]Access, 0, 10)
  345. if err = x.Find(&accesses, &Access{UserName: u.LowerName}); err != nil {
  346. return err
  347. }
  348. sess := x.NewSession()
  349. defer sess.Close()
  350. if err = sess.Begin(); err != nil {
  351. return err
  352. }
  353. for i := range accesses {
  354. accesses[i].UserName = newUserName
  355. if strings.HasPrefix(accesses[i].RepoName, u.LowerName+"/") {
  356. accesses[i].RepoName = strings.Replace(accesses[i].RepoName, u.LowerName, newUserName, 1)
  357. }
  358. if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil {
  359. return err
  360. }
  361. }
  362. repos, err := GetRepositories(u.Id, true)
  363. if err != nil {
  364. return err
  365. }
  366. for i := range repos {
  367. accesses = make([]Access, 0, 10)
  368. // Update accesses of user repository.
  369. if err = x.Find(&accesses, &Access{RepoName: u.LowerName + "/" + repos[i].LowerName}); err != nil {
  370. return err
  371. }
  372. for j := range accesses {
  373. // if the access is not the user's access (already updated above)
  374. if accesses[j].UserName != u.LowerName {
  375. accesses[j].RepoName = newUserName + "/" + repos[i].LowerName
  376. if err = UpdateAccessWithSession(sess, &accesses[j]); err != nil {
  377. return err
  378. }
  379. }
  380. }
  381. }
  382. // Change user directory name.
  383. if err = os.Rename(UserPath(u.LowerName), UserPath(newUserName)); err != nil {
  384. sess.Rollback()
  385. return err
  386. }
  387. return sess.Commit()
  388. }
  389. // UpdateUser updates user's information.
  390. func UpdateUser(u *User) error {
  391. has, err := x.Where("id!=?", u.Id).And("type=?", INDIVIDUAL).And("email=?", u.Email).Get(new(User))
  392. if err != nil {
  393. return err
  394. } else if has {
  395. return ErrEmailAlreadyUsed
  396. }
  397. u.LowerName = strings.ToLower(u.Name)
  398. if len(u.Location) > 255 {
  399. u.Location = u.Location[:255]
  400. }
  401. if len(u.Website) > 255 {
  402. u.Website = u.Website[:255]
  403. }
  404. if len(u.Description) > 255 {
  405. u.Description = u.Description[:255]
  406. }
  407. if u.AvatarEmail == "" {
  408. u.AvatarEmail = u.Email
  409. }
  410. u.Avatar = avatar.HashEmail(u.AvatarEmail)
  411. u.FullName = base.Sanitizer.Sanitize(u.FullName)
  412. _, err = x.Id(u.Id).AllCols().Update(u)
  413. return err
  414. }
  415. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  416. // DeleteUser completely and permanently deletes everything of user.
  417. func DeleteUser(u *User) error {
  418. // Check ownership of repository.
  419. count, err := GetRepositoryCount(u)
  420. if err != nil {
  421. return errors.New("GetRepositoryCount: " + err.Error())
  422. } else if count > 0 {
  423. return ErrUserOwnRepos
  424. }
  425. // Check membership of organization.
  426. count, err = u.GetOrganizationCount()
  427. if err != nil {
  428. return errors.New("GetOrganizationCount: " + err.Error())
  429. } else if count > 0 {
  430. return ErrUserHasOrgs
  431. }
  432. // FIXME: check issues, other repos' commits
  433. // FIXME: roll backable in some point.
  434. // Delete all followers.
  435. if _, err = x.Delete(&Follow{FollowId: u.Id}); err != nil {
  436. return err
  437. }
  438. // Delete oauth2.
  439. if _, err = x.Delete(&Oauth2{Uid: u.Id}); err != nil {
  440. return err
  441. }
  442. // Delete all feeds.
  443. if _, err = x.Delete(&Action{UserId: u.Id}); err != nil {
  444. return err
  445. }
  446. // Delete all watches.
  447. if _, err = x.Delete(&Watch{UserId: u.Id}); err != nil {
  448. return err
  449. }
  450. // Delete all accesses.
  451. if _, err = x.Delete(&Access{UserName: u.LowerName}); err != nil {
  452. return err
  453. }
  454. // Delete all alternative email addresses
  455. if _, err = x.Delete(&EmailAddress{Uid: u.Id}); err != nil {
  456. return err
  457. }
  458. // Delete all SSH keys.
  459. keys := make([]*PublicKey, 0, 10)
  460. if err = x.Find(&keys, &PublicKey{OwnerId: u.Id}); err != nil {
  461. return err
  462. }
  463. for _, key := range keys {
  464. if err = DeletePublicKey(key); err != nil {
  465. return err
  466. }
  467. }
  468. // Delete user directory.
  469. if err = os.RemoveAll(UserPath(u.Name)); err != nil {
  470. return err
  471. }
  472. _, err = x.Delete(u)
  473. return err
  474. }
  475. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  476. func DeleteInactivateUsers() error {
  477. _, err := x.Where("is_active=?", false).Delete(new(User))
  478. if err == nil {
  479. _, err = x.Where("is_activated=?", false).Delete(new(EmailAddress))
  480. }
  481. return err
  482. }
  483. // UserPath returns the path absolute path of user repositories.
  484. func UserPath(userName string) string {
  485. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  486. }
  487. func GetUserByKeyId(keyId int64) (*User, error) {
  488. user := new(User)
  489. rawSql := "SELECT a.* FROM `user` AS a, public_key AS b WHERE a.id = b.owner_id AND b.id=?"
  490. has, err := x.Sql(rawSql, keyId).Get(user)
  491. if err != nil {
  492. return nil, err
  493. } else if !has {
  494. return nil, ErrUserNotKeyOwner
  495. }
  496. return user, nil
  497. }
  498. // GetUserById returns the user object by given ID if exists.
  499. func GetUserById(id int64) (*User, error) {
  500. u := new(User)
  501. has, err := x.Id(id).Get(u)
  502. if err != nil {
  503. return nil, err
  504. } else if !has {
  505. return nil, ErrUserNotExist
  506. }
  507. return u, nil
  508. }
  509. // GetUserByName returns user by given name.
  510. func GetUserByName(name string) (*User, error) {
  511. if len(name) == 0 {
  512. return nil, ErrUserNotExist
  513. }
  514. u := &User{LowerName: strings.ToLower(name)}
  515. has, err := x.Get(u)
  516. if err != nil {
  517. return nil, err
  518. } else if !has {
  519. return nil, ErrUserNotExist
  520. }
  521. return u, nil
  522. }
  523. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  524. func GetUserEmailsByNames(names []string) []string {
  525. mails := make([]string, 0, len(names))
  526. for _, name := range names {
  527. u, err := GetUserByName(name)
  528. if err != nil {
  529. continue
  530. }
  531. mails = append(mails, u.Email)
  532. }
  533. return mails
  534. }
  535. // GetUserIdsByNames returns a slice of ids corresponds to names.
  536. func GetUserIdsByNames(names []string) []int64 {
  537. ids := make([]int64, 0, len(names))
  538. for _, name := range names {
  539. u, err := GetUserByName(name)
  540. if err != nil {
  541. continue
  542. }
  543. ids = append(ids, u.Id)
  544. }
  545. return ids
  546. }
  547. // GetEmailAddresses returns all e-mail addresses belongs to given user.
  548. func GetEmailAddresses(uid int64) ([]*EmailAddress, error) {
  549. emails := make([]*EmailAddress, 0, 5)
  550. err := x.Where("uid=?", uid).Find(&emails)
  551. if err != nil {
  552. return nil, err
  553. }
  554. u, err := GetUserById(uid)
  555. if err != nil {
  556. return nil, err
  557. }
  558. isPrimaryFound := false
  559. for _, email := range emails {
  560. if email.Email == u.Email {
  561. isPrimaryFound = true
  562. email.IsPrimary = true
  563. } else {
  564. email.IsPrimary = false
  565. }
  566. }
  567. // We alway want the primary email address displayed, even if it's not in
  568. // the emailaddress table (yet)
  569. if !isPrimaryFound {
  570. emails = append(emails, &EmailAddress{
  571. Email: u.Email,
  572. IsActivated: true,
  573. IsPrimary: true,
  574. })
  575. }
  576. return emails, nil
  577. }
  578. func AddEmailAddress(email *EmailAddress) error {
  579. used, err := IsEmailUsed(email.Email)
  580. if err != nil {
  581. return err
  582. } else if used {
  583. return ErrEmailAlreadyUsed
  584. }
  585. _, err = x.Insert(email)
  586. return err
  587. }
  588. func (email *EmailAddress) Activate() error {
  589. email.IsActivated = true
  590. if _, err := x.Id(email.Id).AllCols().Update(email); err != nil {
  591. return err
  592. }
  593. if user, err := GetUserById(email.Uid); err != nil {
  594. return err
  595. } else {
  596. user.Rands = GetUserSalt()
  597. return UpdateUser(user)
  598. }
  599. }
  600. func DeleteEmailAddress(email *EmailAddress) error {
  601. has, err := x.Get(email)
  602. if err != nil {
  603. return err
  604. } else if !has {
  605. return ErrEmailNotExist
  606. }
  607. if _, err = x.Delete(email); err != nil {
  608. return err
  609. }
  610. return nil
  611. }
  612. func MakeEmailPrimary(email *EmailAddress) error {
  613. has, err := x.Get(email)
  614. if err != nil {
  615. return err
  616. } else if !has {
  617. return ErrEmailNotExist
  618. }
  619. if !email.IsActivated {
  620. return ErrEmailNotActivated
  621. }
  622. user := &User{Id: email.Uid}
  623. has, err = x.Get(user)
  624. if err != nil {
  625. return err
  626. } else if !has {
  627. return ErrUserNotExist
  628. }
  629. // Make sure the former primary email doesn't disappear
  630. former_primary_email := &EmailAddress{Email: user.Email}
  631. has, err = x.Get(former_primary_email)
  632. if err != nil {
  633. return err
  634. } else if !has {
  635. former_primary_email.Uid = user.Id
  636. former_primary_email.IsActivated = user.IsActive
  637. x.Insert(former_primary_email)
  638. }
  639. user.Email = email.Email
  640. _, err = x.Id(user.Id).AllCols().Update(user)
  641. return err
  642. }
  643. // UserCommit represents a commit with validation of user.
  644. type UserCommit struct {
  645. User *User
  646. *git.Commit
  647. }
  648. // ValidateCommitWithEmail chceck if author's e-mail of commit is corresponsind to a user.
  649. func ValidateCommitWithEmail(c *git.Commit) *User {
  650. u, err := GetUserByEmail(c.Author.Email)
  651. if err != nil {
  652. return nil
  653. }
  654. return u
  655. }
  656. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  657. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  658. emails := map[string]*User{}
  659. newCommits := list.New()
  660. e := oldCommits.Front()
  661. for e != nil {
  662. c := e.Value.(*git.Commit)
  663. var u *User
  664. if v, ok := emails[c.Author.Email]; !ok {
  665. u, _ = GetUserByEmail(c.Author.Email)
  666. emails[c.Author.Email] = u
  667. } else {
  668. u = v
  669. }
  670. newCommits.PushBack(UserCommit{
  671. User: u,
  672. Commit: c,
  673. })
  674. e = e.Next()
  675. }
  676. return newCommits
  677. }
  678. // GetUserByEmail returns the user object by given e-mail if exists.
  679. func GetUserByEmail(email string) (*User, error) {
  680. if len(email) == 0 {
  681. return nil, ErrUserNotExist
  682. }
  683. // First try to find the user by primary email
  684. user := &User{Email: strings.ToLower(email)}
  685. has, err := x.Get(user)
  686. if err != nil {
  687. return nil, err
  688. }
  689. if has {
  690. return user, nil
  691. }
  692. // Otherwise, check in alternative list for activated email addresses
  693. emailAddress := &EmailAddress{Email: strings.ToLower(email), IsActivated: true}
  694. has, err = x.Get(emailAddress)
  695. if err != nil {
  696. return nil, err
  697. }
  698. if has {
  699. return GetUserById(emailAddress.Uid)
  700. }
  701. return nil, ErrUserNotExist
  702. }
  703. // SearchUserByName returns given number of users whose name contains keyword.
  704. func SearchUserByName(opt SearchOption) (us []*User, err error) {
  705. if len(opt.Keyword) == 0 {
  706. return us, nil
  707. }
  708. opt.Keyword = strings.ToLower(opt.Keyword)
  709. us = make([]*User, 0, opt.Limit)
  710. err = x.Limit(opt.Limit).Where("type=0").And("lower_name like ?", "%"+opt.Keyword+"%").Find(&us)
  711. return us, err
  712. }
  713. // Follow is connection request for receiving user notification.
  714. type Follow struct {
  715. Id int64
  716. UserId int64 `xorm:"unique(follow)"`
  717. FollowId int64 `xorm:"unique(follow)"`
  718. }
  719. // FollowUser marks someone be another's follower.
  720. func FollowUser(userId int64, followId int64) (err error) {
  721. sess := x.NewSession()
  722. defer sess.Close()
  723. sess.Begin()
  724. if _, err = sess.Insert(&Follow{UserId: userId, FollowId: followId}); err != nil {
  725. sess.Rollback()
  726. return err
  727. }
  728. rawSql := "UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?"
  729. if _, err = sess.Exec(rawSql, followId); err != nil {
  730. sess.Rollback()
  731. return err
  732. }
  733. rawSql = "UPDATE `user` SET num_followings = num_followings + 1 WHERE id = ?"
  734. if _, err = sess.Exec(rawSql, userId); err != nil {
  735. sess.Rollback()
  736. return err
  737. }
  738. return sess.Commit()
  739. }
  740. // UnFollowUser unmarks someone be another's follower.
  741. func UnFollowUser(userId int64, unFollowId int64) (err error) {
  742. session := x.NewSession()
  743. defer session.Close()
  744. session.Begin()
  745. if _, err = session.Delete(&Follow{UserId: userId, FollowId: unFollowId}); err != nil {
  746. session.Rollback()
  747. return err
  748. }
  749. rawSql := "UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?"
  750. if _, err = session.Exec(rawSql, unFollowId); err != nil {
  751. session.Rollback()
  752. return err
  753. }
  754. rawSql = "UPDATE `user` SET num_followings = num_followings - 1 WHERE id = ?"
  755. if _, err = session.Exec(rawSql, userId); err != nil {
  756. session.Rollback()
  757. return err
  758. }
  759. return session.Commit()
  760. }
  761. func UpdateMentions(userNames []string, issueId int64) error {
  762. users := make([]*User, 0, len(userNames))
  763. if err := x.Where("name IN (?)", strings.Join(userNames, "\",\"")).OrderBy("name ASC").Find(&users); err != nil {
  764. return err
  765. }
  766. ids := make([]int64, 0, len(userNames))
  767. for _, user := range users {
  768. ids = append(ids, user.Id)
  769. if user.Type == INDIVIDUAL {
  770. continue
  771. }
  772. if user.NumMembers == 0 {
  773. continue
  774. }
  775. tempIds := make([]int64, 0, user.NumMembers)
  776. orgUsers, err := GetOrgUsersByOrgId(user.Id)
  777. if err != nil {
  778. return err
  779. }
  780. for _, orgUser := range orgUsers {
  781. tempIds = append(tempIds, orgUser.Id)
  782. }
  783. ids = append(ids, tempIds...)
  784. }
  785. if err := UpdateIssueUserPairsByMentions(ids, issueId); err != nil {
  786. return err
  787. }
  788. return nil
  789. }