user.go 28 KB

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