You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

user.go 30KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175
  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. // IsAdminOfRepo returns true if user has admin or higher access of repository.
  299. func (u *User) IsAdminOfRepo(repo *Repository) bool {
  300. has, err := HasAccess(u, repo, ACCESS_MODE_ADMIN)
  301. if err != nil {
  302. log.Error(3, "HasAccess: %v", err)
  303. }
  304. return has
  305. }
  306. // IsWriterOfRepo returns true if user has write access to given repository.
  307. func (u *User) IsWriterOfRepo(repo *Repository) bool {
  308. has, err := HasAccess(u, repo, ACCESS_MODE_WRITE)
  309. if err != nil {
  310. log.Error(3, "HasAccess: %v", err)
  311. }
  312. return has
  313. }
  314. // IsOrganization returns true if user is actually a organization.
  315. func (u *User) IsOrganization() bool {
  316. return u.Type == ORGANIZATION
  317. }
  318. // IsUserOrgOwner returns true if user is in the owner team of given organization.
  319. func (u *User) IsUserOrgOwner(orgId int64) bool {
  320. return IsOrganizationOwner(orgId, u.Id)
  321. }
  322. // IsPublicMember returns true if user public his/her membership in give organization.
  323. func (u *User) IsPublicMember(orgId int64) bool {
  324. return IsPublicMembership(orgId, u.Id)
  325. }
  326. func (u *User) getOrganizationCount(e Engine) (int64, error) {
  327. return e.Where("uid=?", u.Id).Count(new(OrgUser))
  328. }
  329. // GetOrganizationCount returns count of membership of organization of user.
  330. func (u *User) GetOrganizationCount() (int64, error) {
  331. return u.getOrganizationCount(x)
  332. }
  333. // GetRepositories returns all repositories that user owns, including private repositories.
  334. func (u *User) GetRepositories() (err error) {
  335. u.Repos, err = GetRepositories(u.Id, true)
  336. return err
  337. }
  338. // GetOwnedOrganizations returns all organizations that user owns.
  339. func (u *User) GetOwnedOrganizations() (err error) {
  340. u.OwnedOrgs, err = GetOwnedOrgsByUserID(u.Id)
  341. return err
  342. }
  343. // GetOrganizations returns all organizations that user belongs to.
  344. func (u *User) GetOrganizations(all bool) error {
  345. ous, err := GetOrgUsersByUserID(u.Id, all)
  346. if err != nil {
  347. return err
  348. }
  349. u.Orgs = make([]*User, len(ous))
  350. for i, ou := range ous {
  351. u.Orgs[i], err = GetUserByID(ou.OrgID)
  352. if err != nil {
  353. return err
  354. }
  355. }
  356. return nil
  357. }
  358. // DisplayName returns full name if it's not empty,
  359. // returns username otherwise.
  360. func (u *User) DisplayName() string {
  361. if len(u.FullName) > 0 {
  362. return u.FullName
  363. }
  364. return u.Name
  365. }
  366. func (u *User) ShortName(length int) string {
  367. return base.EllipsisString(u.Name, length)
  368. }
  369. // IsUserExist checks if given user name exist,
  370. // the user name should be noncased unique.
  371. // If uid is presented, then check will rule out that one,
  372. // it is used when update a user name in settings page.
  373. func IsUserExist(uid int64, name string) (bool, error) {
  374. if len(name) == 0 {
  375. return false, nil
  376. }
  377. return x.Where("id!=?", uid).Get(&User{LowerName: strings.ToLower(name)})
  378. }
  379. // IsEmailUsed returns true if the e-mail has been used.
  380. func IsEmailUsed(email string) (bool, error) {
  381. if len(email) == 0 {
  382. return false, nil
  383. }
  384. email = strings.ToLower(email)
  385. if has, err := x.Get(&EmailAddress{Email: email}); has || err != nil {
  386. return has, err
  387. }
  388. return x.Get(&User{Email: email})
  389. }
  390. // GetUserSalt returns a ramdom user salt token.
  391. func GetUserSalt() string {
  392. return base.GetRandomString(10)
  393. }
  394. // NewFakeUser creates and returns a fake user for someone has deleted his/her account.
  395. func NewFakeUser() *User {
  396. return &User{
  397. Id: -1,
  398. Name: "Someone",
  399. LowerName: "someone",
  400. }
  401. }
  402. // CreateUser creates record of a new user.
  403. func CreateUser(u *User) (err error) {
  404. if err = IsUsableName(u.Name); err != nil {
  405. return err
  406. }
  407. isExist, err := IsUserExist(0, u.Name)
  408. if err != nil {
  409. return err
  410. } else if isExist {
  411. return ErrUserAlreadyExist{u.Name}
  412. }
  413. u.Email = strings.ToLower(u.Email)
  414. isExist, err = IsEmailUsed(u.Email)
  415. if err != nil {
  416. return err
  417. } else if isExist {
  418. return ErrEmailAlreadyUsed{u.Email}
  419. }
  420. u.LowerName = strings.ToLower(u.Name)
  421. u.AvatarEmail = u.Email
  422. u.Avatar = base.HashEmail(u.AvatarEmail)
  423. u.Rands = GetUserSalt()
  424. u.Salt = GetUserSalt()
  425. u.EncodePasswd()
  426. u.MaxRepoCreation = -1
  427. sess := x.NewSession()
  428. defer sess.Close()
  429. if err = sess.Begin(); err != nil {
  430. return err
  431. }
  432. if _, err = sess.Insert(u); err != nil {
  433. sess.Rollback()
  434. return err
  435. } else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
  436. sess.Rollback()
  437. return err
  438. }
  439. return sess.Commit()
  440. }
  441. func countUsers(e Engine) int64 {
  442. count, _ := e.Where("type=0").Count(new(User))
  443. return count
  444. }
  445. // CountUsers returns number of users.
  446. func CountUsers() int64 {
  447. return countUsers(x)
  448. }
  449. // Users returns number of users in given page.
  450. func Users(page, pageSize int) ([]*User, error) {
  451. users := make([]*User, 0, pageSize)
  452. return users, x.Limit(pageSize, (page-1)*pageSize).Where("type=0").Asc("id").Find(&users)
  453. }
  454. // get user by erify code
  455. func getVerifyUser(code string) (user *User) {
  456. if len(code) <= base.TimeLimitCodeLength {
  457. return nil
  458. }
  459. // use tail hex username query user
  460. hexStr := code[base.TimeLimitCodeLength:]
  461. if b, err := hex.DecodeString(hexStr); err == nil {
  462. if user, err = GetUserByName(string(b)); user != nil {
  463. return user
  464. }
  465. log.Error(4, "user.getVerifyUser: %v", err)
  466. }
  467. return nil
  468. }
  469. // verify active code when active account
  470. func VerifyUserActiveCode(code string) (user *User) {
  471. minutes := setting.Service.ActiveCodeLives
  472. if user = getVerifyUser(code); user != nil {
  473. // time limit code
  474. prefix := code[:base.TimeLimitCodeLength]
  475. data := com.ToStr(user.Id) + user.Email + user.LowerName + user.Passwd + user.Rands
  476. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  477. return user
  478. }
  479. }
  480. return nil
  481. }
  482. // verify active code when active account
  483. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  484. minutes := setting.Service.ActiveCodeLives
  485. if user := getVerifyUser(code); user != nil {
  486. // time limit code
  487. prefix := code[:base.TimeLimitCodeLength]
  488. data := com.ToStr(user.Id) + email + user.LowerName + user.Passwd + user.Rands
  489. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  490. emailAddress := &EmailAddress{Email: email}
  491. if has, _ := x.Get(emailAddress); has {
  492. return emailAddress
  493. }
  494. }
  495. }
  496. return nil
  497. }
  498. // ChangeUserName changes all corresponding setting from old user name to new one.
  499. func ChangeUserName(u *User, newUserName string) (err error) {
  500. if err = IsUsableName(newUserName); err != nil {
  501. return err
  502. }
  503. isExist, err := IsUserExist(0, newUserName)
  504. if err != nil {
  505. return err
  506. } else if isExist {
  507. return ErrUserAlreadyExist{newUserName}
  508. }
  509. if err = ChangeUsernameInPullRequests(u.Name, newUserName); err != nil {
  510. return fmt.Errorf("ChangeUsernameInPullRequests: %v", err)
  511. }
  512. // Delete all local copies of repository wiki that user owns.
  513. if err = x.Where("owner_id=?", u.Id).Iterate(new(Repository), func(idx int, bean interface{}) error {
  514. repo := bean.(*Repository)
  515. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  516. return nil
  517. }); err != nil {
  518. return fmt.Errorf("Delete repository wiki local copy: %v", err)
  519. }
  520. return os.Rename(UserPath(u.Name), UserPath(newUserName))
  521. }
  522. func updateUser(e Engine, u *User) error {
  523. // Organization does not need email
  524. if !u.IsOrganization() {
  525. u.Email = strings.ToLower(u.Email)
  526. has, err := e.Where("id!=?", u.Id).And("type=?", u.Type).And("email=?", u.Email).Get(new(User))
  527. if err != nil {
  528. return err
  529. } else if has {
  530. return ErrEmailAlreadyUsed{u.Email}
  531. }
  532. if len(u.AvatarEmail) == 0 {
  533. u.AvatarEmail = u.Email
  534. }
  535. u.Avatar = base.HashEmail(u.AvatarEmail)
  536. }
  537. u.LowerName = strings.ToLower(u.Name)
  538. u.Location = base.TruncateString(u.Location, 255)
  539. u.Website = base.TruncateString(u.Website, 255)
  540. u.Description = base.TruncateString(u.Description, 255)
  541. u.FullName = markdown.Sanitizer.Sanitize(u.FullName)
  542. _, err := e.Id(u.Id).AllCols().Update(u)
  543. return err
  544. }
  545. // UpdateUser updates user's information.
  546. func UpdateUser(u *User) error {
  547. return updateUser(x, u)
  548. }
  549. // deleteBeans deletes all given beans, beans should contain delete conditions.
  550. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  551. for i := range beans {
  552. if _, err = e.Delete(beans[i]); err != nil {
  553. return err
  554. }
  555. }
  556. return nil
  557. }
  558. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  559. func deleteUser(e *xorm.Session, u *User) error {
  560. // Note: A user owns any repository or belongs to any organization
  561. // cannot perform delete operation.
  562. // Check ownership of repository.
  563. count, err := getRepositoryCount(e, u)
  564. if err != nil {
  565. return fmt.Errorf("GetRepositoryCount: %v", err)
  566. } else if count > 0 {
  567. return ErrUserOwnRepos{UID: u.Id}
  568. }
  569. // Check membership of organization.
  570. count, err = u.getOrganizationCount(e)
  571. if err != nil {
  572. return fmt.Errorf("GetOrganizationCount: %v", err)
  573. } else if count > 0 {
  574. return ErrUserHasOrgs{UID: u.Id}
  575. }
  576. // ***** START: Watch *****
  577. watches := make([]*Watch, 0, 10)
  578. if err = e.Find(&watches, &Watch{UserID: u.Id}); err != nil {
  579. return fmt.Errorf("get all watches: %v", err)
  580. }
  581. for i := range watches {
  582. if _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", watches[i].RepoID); err != nil {
  583. return fmt.Errorf("decrease repository watch number[%d]: %v", watches[i].RepoID, err)
  584. }
  585. }
  586. // ***** END: Watch *****
  587. // ***** START: Star *****
  588. stars := make([]*Star, 0, 10)
  589. if err = e.Find(&stars, &Star{UID: u.Id}); err != nil {
  590. return fmt.Errorf("get all stars: %v", err)
  591. }
  592. for i := range stars {
  593. if _, err = e.Exec("UPDATE `repository` SET num_stars=num_stars-1 WHERE id=?", stars[i].RepoID); err != nil {
  594. return fmt.Errorf("decrease repository star number[%d]: %v", stars[i].RepoID, err)
  595. }
  596. }
  597. // ***** END: Star *****
  598. // ***** START: Follow *****
  599. followers := make([]*Follow, 0, 10)
  600. if err = e.Find(&followers, &Follow{UserID: u.Id}); err != nil {
  601. return fmt.Errorf("get all followers: %v", err)
  602. }
  603. for i := range followers {
  604. if _, err = e.Exec("UPDATE `user` SET num_followers=num_followers-1 WHERE id=?", followers[i].UserID); err != nil {
  605. return fmt.Errorf("decrease user follower number[%d]: %v", followers[i].UserID, err)
  606. }
  607. }
  608. // ***** END: Follow *****
  609. if err = deleteBeans(e,
  610. &AccessToken{UID: u.Id},
  611. &Collaboration{UserID: u.Id},
  612. &Access{UserID: u.Id},
  613. &Watch{UserID: u.Id},
  614. &Star{UID: u.Id},
  615. &Follow{FollowID: u.Id},
  616. &Action{UserID: u.Id},
  617. &IssueUser{UID: u.Id},
  618. &EmailAddress{UID: u.Id},
  619. ); err != nil {
  620. return fmt.Errorf("deleteBeans: %v", err)
  621. }
  622. // ***** START: PublicKey *****
  623. keys := make([]*PublicKey, 0, 10)
  624. if err = e.Find(&keys, &PublicKey{OwnerID: u.Id}); err != nil {
  625. return fmt.Errorf("get all public keys: %v", err)
  626. }
  627. for _, key := range keys {
  628. if err = deletePublicKey(e, key.ID); err != nil {
  629. return fmt.Errorf("deletePublicKey: %v", err)
  630. }
  631. }
  632. // ***** END: PublicKey *****
  633. // Clear assignee.
  634. if _, err = e.Exec("UPDATE `issue` SET assignee_id=0 WHERE assignee_id=?", u.Id); err != nil {
  635. return fmt.Errorf("clear assignee: %v", err)
  636. }
  637. if _, err = e.Id(u.Id).Delete(new(User)); err != nil {
  638. return fmt.Errorf("Delete: %v", err)
  639. }
  640. // FIXME: system notice
  641. // Note: There are something just cannot be roll back,
  642. // so just keep error logs of those operations.
  643. RewriteAllPublicKeys()
  644. os.RemoveAll(UserPath(u.Name))
  645. os.Remove(u.CustomAvatarPath())
  646. return nil
  647. }
  648. // DeleteUser completely and permanently deletes everything of a user,
  649. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  650. func DeleteUser(u *User) (err error) {
  651. sess := x.NewSession()
  652. defer sessionRelease(sess)
  653. if err = sess.Begin(); err != nil {
  654. return err
  655. }
  656. if err = deleteUser(sess, u); err != nil {
  657. // Note: don't wrapper error here.
  658. return err
  659. }
  660. return sess.Commit()
  661. }
  662. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  663. func DeleteInactivateUsers() (err error) {
  664. users := make([]*User, 0, 10)
  665. if err = x.Where("is_active=?", false).Find(&users); err != nil {
  666. return fmt.Errorf("get all inactive users: %v", err)
  667. }
  668. for _, u := range users {
  669. if err = DeleteUser(u); err != nil {
  670. // Ignore users that were set inactive by admin.
  671. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  672. continue
  673. }
  674. return err
  675. }
  676. }
  677. _, err = x.Where("is_activated=?", false).Delete(new(EmailAddress))
  678. return err
  679. }
  680. // UserPath returns the path absolute path of user repositories.
  681. func UserPath(userName string) string {
  682. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  683. }
  684. func GetUserByKeyID(keyID int64) (*User, error) {
  685. user := new(User)
  686. 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)
  687. if err != nil {
  688. return nil, err
  689. } else if !has {
  690. return nil, ErrUserNotKeyOwner
  691. }
  692. return user, nil
  693. }
  694. func getUserByID(e Engine, id int64) (*User, error) {
  695. u := new(User)
  696. has, err := e.Id(id).Get(u)
  697. if err != nil {
  698. return nil, err
  699. } else if !has {
  700. return nil, ErrUserNotExist{id, ""}
  701. }
  702. return u, nil
  703. }
  704. // GetUserByID returns the user object by given ID if exists.
  705. func GetUserByID(id int64) (*User, error) {
  706. return getUserByID(x, id)
  707. }
  708. // GetAssigneeByID returns the user with write access of repository by given ID.
  709. func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
  710. has, err := HasAccess(&User{Id: userID}, repo, ACCESS_MODE_WRITE)
  711. if err != nil {
  712. return nil, err
  713. } else if !has {
  714. return nil, ErrUserNotExist{userID, ""}
  715. }
  716. return GetUserByID(userID)
  717. }
  718. // GetUserByName returns user by given name.
  719. func GetUserByName(name string) (*User, error) {
  720. if len(name) == 0 {
  721. return nil, ErrUserNotExist{0, name}
  722. }
  723. u := &User{LowerName: strings.ToLower(name)}
  724. has, err := x.Get(u)
  725. if err != nil {
  726. return nil, err
  727. } else if !has {
  728. return nil, ErrUserNotExist{0, name}
  729. }
  730. return u, nil
  731. }
  732. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  733. func GetUserEmailsByNames(names []string) []string {
  734. mails := make([]string, 0, len(names))
  735. for _, name := range names {
  736. u, err := GetUserByName(name)
  737. if err != nil {
  738. continue
  739. }
  740. mails = append(mails, u.Email)
  741. }
  742. return mails
  743. }
  744. // GetUserIdsByNames returns a slice of ids corresponds to names.
  745. func GetUserIdsByNames(names []string) []int64 {
  746. ids := make([]int64, 0, len(names))
  747. for _, name := range names {
  748. u, err := GetUserByName(name)
  749. if err != nil {
  750. continue
  751. }
  752. ids = append(ids, u.Id)
  753. }
  754. return ids
  755. }
  756. // GetEmailAddresses returns all e-mail addresses belongs to given user.
  757. func GetEmailAddresses(uid int64) ([]*EmailAddress, error) {
  758. emails := make([]*EmailAddress, 0, 5)
  759. err := x.Where("uid=?", uid).Find(&emails)
  760. if err != nil {
  761. return nil, err
  762. }
  763. u, err := GetUserByID(uid)
  764. if err != nil {
  765. return nil, err
  766. }
  767. isPrimaryFound := false
  768. for _, email := range emails {
  769. if email.Email == u.Email {
  770. isPrimaryFound = true
  771. email.IsPrimary = true
  772. } else {
  773. email.IsPrimary = false
  774. }
  775. }
  776. // We alway want the primary email address displayed, even if it's not in
  777. // the emailaddress table (yet)
  778. if !isPrimaryFound {
  779. emails = append(emails, &EmailAddress{
  780. Email: u.Email,
  781. IsActivated: true,
  782. IsPrimary: true,
  783. })
  784. }
  785. return emails, nil
  786. }
  787. func AddEmailAddress(email *EmailAddress) error {
  788. email.Email = strings.ToLower(strings.TrimSpace(email.Email))
  789. used, err := IsEmailUsed(email.Email)
  790. if err != nil {
  791. return err
  792. } else if used {
  793. return ErrEmailAlreadyUsed{email.Email}
  794. }
  795. _, err = x.Insert(email)
  796. return err
  797. }
  798. func AddEmailAddresses(emails []*EmailAddress) error {
  799. if len(emails) == 0 {
  800. return nil
  801. }
  802. // Check if any of them has been used
  803. for i := range emails {
  804. emails[i].Email = strings.ToLower(strings.TrimSpace(emails[i].Email))
  805. used, err := IsEmailUsed(emails[i].Email)
  806. if err != nil {
  807. return err
  808. } else if used {
  809. return ErrEmailAlreadyUsed{emails[i].Email}
  810. }
  811. }
  812. if _, err := x.Insert(emails); err != nil {
  813. return fmt.Errorf("Insert: %v", err)
  814. }
  815. return nil
  816. }
  817. func (email *EmailAddress) Activate() error {
  818. email.IsActivated = true
  819. if _, err := x.Id(email.ID).AllCols().Update(email); err != nil {
  820. return err
  821. }
  822. if user, err := GetUserByID(email.UID); err != nil {
  823. return err
  824. } else {
  825. user.Rands = GetUserSalt()
  826. return UpdateUser(user)
  827. }
  828. }
  829. func DeleteEmailAddress(email *EmailAddress) (err error) {
  830. if email.ID > 0 {
  831. _, err = x.Id(email.ID).Delete(new(EmailAddress))
  832. } else {
  833. _, err = x.Where("email=?", email.Email).Delete(new(EmailAddress))
  834. }
  835. return err
  836. }
  837. func DeleteEmailAddresses(emails []*EmailAddress) (err error) {
  838. for i := range emails {
  839. if err = DeleteEmailAddress(emails[i]); err != nil {
  840. return err
  841. }
  842. }
  843. return nil
  844. }
  845. func MakeEmailPrimary(email *EmailAddress) error {
  846. has, err := x.Get(email)
  847. if err != nil {
  848. return err
  849. } else if !has {
  850. return ErrEmailNotExist
  851. }
  852. if !email.IsActivated {
  853. return ErrEmailNotActivated
  854. }
  855. user := &User{Id: email.UID}
  856. has, err = x.Get(user)
  857. if err != nil {
  858. return err
  859. } else if !has {
  860. return ErrUserNotExist{email.UID, ""}
  861. }
  862. // Make sure the former primary email doesn't disappear
  863. former_primary_email := &EmailAddress{Email: user.Email}
  864. has, err = x.Get(former_primary_email)
  865. if err != nil {
  866. return err
  867. } else if !has {
  868. former_primary_email.UID = user.Id
  869. former_primary_email.IsActivated = user.IsActive
  870. x.Insert(former_primary_email)
  871. }
  872. user.Email = email.Email
  873. _, err = x.Id(user.Id).AllCols().Update(user)
  874. return err
  875. }
  876. // UserCommit represents a commit with validation of user.
  877. type UserCommit struct {
  878. User *User
  879. *git.Commit
  880. }
  881. // ValidateCommitWithEmail chceck if author's e-mail of commit is corresponsind to a user.
  882. func ValidateCommitWithEmail(c *git.Commit) *User {
  883. u, err := GetUserByEmail(c.Author.Email)
  884. if err != nil {
  885. return nil
  886. }
  887. return u
  888. }
  889. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  890. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  891. var (
  892. u *User
  893. emails = map[string]*User{}
  894. newCommits = list.New()
  895. e = oldCommits.Front()
  896. )
  897. for e != nil {
  898. c := e.Value.(*git.Commit)
  899. if v, ok := emails[c.Author.Email]; !ok {
  900. u, _ = GetUserByEmail(c.Author.Email)
  901. emails[c.Author.Email] = u
  902. } else {
  903. u = v
  904. }
  905. newCommits.PushBack(UserCommit{
  906. User: u,
  907. Commit: c,
  908. })
  909. e = e.Next()
  910. }
  911. return newCommits
  912. }
  913. // GetUserByEmail returns the user object by given e-mail if exists.
  914. func GetUserByEmail(email string) (*User, error) {
  915. if len(email) == 0 {
  916. return nil, ErrUserNotExist{0, "email"}
  917. }
  918. email = strings.ToLower(email)
  919. // First try to find the user by primary email
  920. user := &User{Email: email}
  921. has, err := x.Get(user)
  922. if err != nil {
  923. return nil, err
  924. }
  925. if has {
  926. return user, nil
  927. }
  928. // Otherwise, check in alternative list for activated email addresses
  929. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  930. has, err = x.Get(emailAddress)
  931. if err != nil {
  932. return nil, err
  933. }
  934. if has {
  935. return GetUserByID(emailAddress.UID)
  936. }
  937. return nil, ErrUserNotExist{0, email}
  938. }
  939. // SearchUserByName returns given number of users whose name contains keyword.
  940. func SearchUserByName(opt SearchOption) (us []*User, err error) {
  941. if len(opt.Keyword) == 0 {
  942. return us, nil
  943. }
  944. opt.Keyword = strings.ToLower(opt.Keyword)
  945. us = make([]*User, 0, opt.Limit)
  946. err = x.Limit(opt.Limit).Where("type=0").And("lower_name like ?", "%"+opt.Keyword+"%").Find(&us)
  947. return us, err
  948. }
  949. // ___________ .__ .__
  950. // \_ _____/___ | | | | ______ _ __
  951. // | __)/ _ \| | | | / _ \ \/ \/ /
  952. // | \( <_> ) |_| |_( <_> ) /
  953. // \___ / \____/|____/____/\____/ \/\_/
  954. // \/
  955. // Follow represents relations of user and his/her followers.
  956. type Follow struct {
  957. ID int64 `xorm:"pk autoincr"`
  958. UserID int64 `xorm:"UNIQUE(follow)"`
  959. FollowID int64 `xorm:"UNIQUE(follow)"`
  960. }
  961. func IsFollowing(userID, followID int64) bool {
  962. has, _ := x.Get(&Follow{UserID: userID, FollowID: followID})
  963. return has
  964. }
  965. // FollowUser marks someone be another's follower.
  966. func FollowUser(userID, followID int64) (err error) {
  967. if userID == followID || IsFollowing(userID, followID) {
  968. return nil
  969. }
  970. sess := x.NewSession()
  971. defer sessionRelease(sess)
  972. if err = sess.Begin(); err != nil {
  973. return err
  974. }
  975. if _, err = sess.Insert(&Follow{UserID: userID, FollowID: followID}); err != nil {
  976. return err
  977. }
  978. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?", followID); err != nil {
  979. return err
  980. }
  981. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following + 1 WHERE id = ?", userID); err != nil {
  982. return err
  983. }
  984. return sess.Commit()
  985. }
  986. // UnfollowUser unmarks someone be another's follower.
  987. func UnfollowUser(userID, followID int64) (err error) {
  988. if userID == followID || !IsFollowing(userID, followID) {
  989. return nil
  990. }
  991. sess := x.NewSession()
  992. defer sessionRelease(sess)
  993. if err = sess.Begin(); err != nil {
  994. return err
  995. }
  996. if _, err = sess.Delete(&Follow{UserID: userID, FollowID: followID}); err != nil {
  997. return err
  998. }
  999. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?", followID); err != nil {
  1000. return err
  1001. }
  1002. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following - 1 WHERE id = ?", userID); err != nil {
  1003. return err
  1004. }
  1005. return sess.Commit()
  1006. }