user.go 28 KB

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