user.go 30 KB

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