user.go 30 KB

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