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