user.go 31 KB

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