user.go 28 KB

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