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