user.go 26 KB

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