user.go 27 KB

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