user.go 27 KB

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