user.go 28 KB

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