user.go 26 KB

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