user.go 26 KB

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