You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

user.go 31KB

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