user.go 30 KB

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