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

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