user.go 29 KB

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