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

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