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