user.go 30 KB

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