user.go 26 KB

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