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

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