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