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