user.go 27 KB

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