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 30KB

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