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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266
  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, error) {
  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. if u.Rands, err = GetUserSalt(); err != nil {
  516. return err
  517. }
  518. if u.Salt, err = GetUserSalt(); err != nil {
  519. return err
  520. }
  521. u.EncodePasswd()
  522. u.MaxRepoCreation = -1
  523. sess := x.NewSession()
  524. defer sessionRelease(sess)
  525. if err = sess.Begin(); err != nil {
  526. return err
  527. }
  528. if _, err = sess.Insert(u); err != nil {
  529. return err
  530. } else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
  531. return err
  532. }
  533. return sess.Commit()
  534. }
  535. func countUsers(e Engine) int64 {
  536. count, _ := e.
  537. Where("type=0").
  538. Count(new(User))
  539. return count
  540. }
  541. // CountUsers returns number of users.
  542. func CountUsers() int64 {
  543. return countUsers(x)
  544. }
  545. // Users returns number of users in given page.
  546. func Users(opts *SearchUserOptions) ([]*User, error) {
  547. if len(opts.OrderBy) == 0 {
  548. opts.OrderBy = "name ASC"
  549. }
  550. users := make([]*User, 0, opts.PageSize)
  551. sess := x.
  552. Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).
  553. Where("type=0")
  554. return users, sess.
  555. OrderBy(opts.OrderBy).
  556. Find(&users)
  557. }
  558. // get user by erify code
  559. func getVerifyUser(code string) (user *User) {
  560. if len(code) <= base.TimeLimitCodeLength {
  561. return nil
  562. }
  563. // use tail hex username query user
  564. hexStr := code[base.TimeLimitCodeLength:]
  565. if b, err := hex.DecodeString(hexStr); err == nil {
  566. if user, err = GetUserByName(string(b)); user != nil {
  567. return user
  568. }
  569. log.Error(4, "user.getVerifyUser: %v", err)
  570. }
  571. return nil
  572. }
  573. // VerifyUserActiveCode verifies active code when active account
  574. func VerifyUserActiveCode(code string) (user *User) {
  575. minutes := setting.Service.ActiveCodeLives
  576. if user = getVerifyUser(code); user != nil {
  577. // time limit code
  578. prefix := code[:base.TimeLimitCodeLength]
  579. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands
  580. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  581. return user
  582. }
  583. }
  584. return nil
  585. }
  586. // VerifyActiveEmailCode verifies active email code when active account
  587. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  588. minutes := setting.Service.ActiveCodeLives
  589. if user := getVerifyUser(code); user != nil {
  590. // time limit code
  591. prefix := code[:base.TimeLimitCodeLength]
  592. data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands
  593. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  594. emailAddress := &EmailAddress{Email: email}
  595. if has, _ := x.Get(emailAddress); has {
  596. return emailAddress
  597. }
  598. }
  599. }
  600. return nil
  601. }
  602. // ChangeUserName changes all corresponding setting from old user name to new one.
  603. func ChangeUserName(u *User, newUserName string) (err error) {
  604. if err = IsUsableUsername(newUserName); err != nil {
  605. return err
  606. }
  607. isExist, err := IsUserExist(0, newUserName)
  608. if err != nil {
  609. return err
  610. } else if isExist {
  611. return ErrUserAlreadyExist{newUserName}
  612. }
  613. if err = ChangeUsernameInPullRequests(u.Name, newUserName); err != nil {
  614. return fmt.Errorf("ChangeUsernameInPullRequests: %v", err)
  615. }
  616. // Delete all local copies of repository wiki that user owns.
  617. if err = x.
  618. Where("owner_id=?", u.ID).
  619. Iterate(new(Repository), func(idx int, bean interface{}) error {
  620. repo := bean.(*Repository)
  621. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  622. return nil
  623. }); err != nil {
  624. return fmt.Errorf("Delete repository wiki local copy: %v", err)
  625. }
  626. return os.Rename(UserPath(u.Name), UserPath(newUserName))
  627. }
  628. func updateUser(e Engine, u *User) error {
  629. // Organization does not need email
  630. if !u.IsOrganization() {
  631. u.Email = strings.ToLower(u.Email)
  632. has, err := e.
  633. Where("id!=?", u.ID).
  634. And("type=?", u.Type).
  635. And("email=?", u.Email).
  636. Get(new(User))
  637. if err != nil {
  638. return err
  639. } else if has {
  640. return ErrEmailAlreadyUsed{u.Email}
  641. }
  642. if len(u.AvatarEmail) == 0 {
  643. u.AvatarEmail = u.Email
  644. }
  645. u.Avatar = base.HashEmail(u.AvatarEmail)
  646. }
  647. u.LowerName = strings.ToLower(u.Name)
  648. u.Location = base.TruncateString(u.Location, 255)
  649. u.Website = base.TruncateString(u.Website, 255)
  650. u.Description = base.TruncateString(u.Description, 255)
  651. u.FullName = markdown.Sanitizer.Sanitize(u.FullName)
  652. _, err := e.Id(u.ID).AllCols().Update(u)
  653. return err
  654. }
  655. // UpdateUser updates user's information.
  656. func UpdateUser(u *User) error {
  657. return updateUser(x, u)
  658. }
  659. // deleteBeans deletes all given beans, beans should contain delete conditions.
  660. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  661. for i := range beans {
  662. if _, err = e.Delete(beans[i]); err != nil {
  663. return err
  664. }
  665. }
  666. return nil
  667. }
  668. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  669. func deleteUser(e *xorm.Session, u *User) error {
  670. // Note: A user owns any repository or belongs to any organization
  671. // cannot perform delete operation.
  672. // Check ownership of repository.
  673. count, err := getRepositoryCount(e, u)
  674. if err != nil {
  675. return fmt.Errorf("GetRepositoryCount: %v", err)
  676. } else if count > 0 {
  677. return ErrUserOwnRepos{UID: u.ID}
  678. }
  679. // Check membership of organization.
  680. count, err = u.getOrganizationCount(e)
  681. if err != nil {
  682. return fmt.Errorf("GetOrganizationCount: %v", err)
  683. } else if count > 0 {
  684. return ErrUserHasOrgs{UID: u.ID}
  685. }
  686. // ***** START: Watch *****
  687. watches := make([]*Watch, 0, 10)
  688. if err = e.Find(&watches, &Watch{UserID: u.ID}); err != nil {
  689. return fmt.Errorf("get all watches: %v", err)
  690. }
  691. for i := range watches {
  692. if _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", watches[i].RepoID); err != nil {
  693. return fmt.Errorf("decrease repository watch number[%d]: %v", watches[i].RepoID, err)
  694. }
  695. }
  696. // ***** END: Watch *****
  697. // ***** START: Star *****
  698. stars := make([]*Star, 0, 10)
  699. if err = e.Find(&stars, &Star{UID: u.ID}); err != nil {
  700. return fmt.Errorf("get all stars: %v", err)
  701. }
  702. for i := range stars {
  703. if _, err = e.Exec("UPDATE `repository` SET num_stars=num_stars-1 WHERE id=?", stars[i].RepoID); err != nil {
  704. return fmt.Errorf("decrease repository star number[%d]: %v", stars[i].RepoID, err)
  705. }
  706. }
  707. // ***** END: Star *****
  708. // ***** START: Follow *****
  709. followers := make([]*Follow, 0, 10)
  710. if err = e.Find(&followers, &Follow{UserID: u.ID}); err != nil {
  711. return fmt.Errorf("get all followers: %v", err)
  712. }
  713. for i := range followers {
  714. if _, err = e.Exec("UPDATE `user` SET num_followers=num_followers-1 WHERE id=?", followers[i].UserID); err != nil {
  715. return fmt.Errorf("decrease user follower number[%d]: %v", followers[i].UserID, err)
  716. }
  717. }
  718. // ***** END: Follow *****
  719. if err = deleteBeans(e,
  720. &AccessToken{UID: u.ID},
  721. &Collaboration{UserID: u.ID},
  722. &Access{UserID: u.ID},
  723. &Watch{UserID: u.ID},
  724. &Star{UID: u.ID},
  725. &Follow{FollowID: u.ID},
  726. &Action{UserID: u.ID},
  727. &IssueUser{UID: u.ID},
  728. &EmailAddress{UID: u.ID},
  729. ); err != nil {
  730. return fmt.Errorf("deleteBeans: %v", err)
  731. }
  732. // ***** START: PublicKey *****
  733. keys := make([]*PublicKey, 0, 10)
  734. if err = e.Find(&keys, &PublicKey{OwnerID: u.ID}); err != nil {
  735. return fmt.Errorf("get all public keys: %v", err)
  736. }
  737. keyIDs := make([]int64, len(keys))
  738. for i := range keys {
  739. keyIDs[i] = keys[i].ID
  740. }
  741. if err = deletePublicKeys(e, keyIDs...); err != nil {
  742. return fmt.Errorf("deletePublicKeys: %v", err)
  743. }
  744. // ***** END: PublicKey *****
  745. // Clear assignee.
  746. if _, err = e.Exec("UPDATE `issue` SET assignee_id=0 WHERE assignee_id=?", u.ID); err != nil {
  747. return fmt.Errorf("clear assignee: %v", err)
  748. }
  749. if _, err = e.Id(u.ID).Delete(new(User)); err != nil {
  750. return fmt.Errorf("Delete: %v", err)
  751. }
  752. // FIXME: system notice
  753. // Note: There are something just cannot be roll back,
  754. // so just keep error logs of those operations.
  755. path := UserPath(u.Name)
  756. if err := os.RemoveAll(path); err != nil {
  757. return fmt.Errorf("Fail to RemoveAll %s: %v", path, err)
  758. }
  759. avatarPath := u.CustomAvatarPath()
  760. if com.IsExist(avatarPath) {
  761. if err := os.Remove(avatarPath); err != nil {
  762. return fmt.Errorf("Fail to remove %s: %v", avatarPath, err)
  763. }
  764. }
  765. return nil
  766. }
  767. // DeleteUser completely and permanently deletes everything of a user,
  768. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  769. func DeleteUser(u *User) (err error) {
  770. sess := x.NewSession()
  771. defer sessionRelease(sess)
  772. if err = sess.Begin(); err != nil {
  773. return err
  774. }
  775. if err = deleteUser(sess, u); err != nil {
  776. // Note: don't wrapper error here.
  777. return err
  778. }
  779. if err = sess.Commit(); err != nil {
  780. return err
  781. }
  782. return RewriteAllPublicKeys()
  783. }
  784. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  785. func DeleteInactivateUsers() (err error) {
  786. users := make([]*User, 0, 10)
  787. if err = x.
  788. Where("is_active = ?", false).
  789. Find(&users); err != nil {
  790. return fmt.Errorf("get all inactive users: %v", err)
  791. }
  792. // FIXME: should only update authorized_keys file once after all deletions.
  793. for _, u := range users {
  794. if err = DeleteUser(u); err != nil {
  795. // Ignore users that were set inactive by admin.
  796. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  797. continue
  798. }
  799. return err
  800. }
  801. }
  802. _, err = x.
  803. Where("is_activated = ?", false).
  804. Delete(new(EmailAddress))
  805. return err
  806. }
  807. // UserPath returns the path absolute path of user repositories.
  808. func UserPath(userName string) string {
  809. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  810. }
  811. // GetUserByKeyID get user information by user's public key id
  812. func GetUserByKeyID(keyID int64) (*User, error) {
  813. var user User
  814. has, err := x.Join("INNER", "public_key", "`public_key`.owner_id = `user`.id").
  815. Where("`public_key`.id=?", keyID).
  816. Get(&user)
  817. if err != nil {
  818. return nil, err
  819. }
  820. if !has {
  821. return nil, ErrUserNotExist{0, "", keyID}
  822. }
  823. return &user, nil
  824. }
  825. func getUserByID(e Engine, id int64) (*User, error) {
  826. u := new(User)
  827. has, err := e.Id(id).Get(u)
  828. if err != nil {
  829. return nil, err
  830. } else if !has {
  831. return nil, ErrUserNotExist{id, "", 0}
  832. }
  833. return u, nil
  834. }
  835. // GetUserByID returns the user object by given ID if exists.
  836. func GetUserByID(id int64) (*User, error) {
  837. return getUserByID(x, id)
  838. }
  839. // GetAssigneeByID returns the user with write access of repository by given ID.
  840. func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
  841. has, err := HasAccess(&User{ID: userID}, repo, AccessModeWrite)
  842. if err != nil {
  843. return nil, err
  844. } else if !has {
  845. return nil, ErrUserNotExist{userID, "", 0}
  846. }
  847. return GetUserByID(userID)
  848. }
  849. // GetUserByName returns user by given name.
  850. func GetUserByName(name string) (*User, error) {
  851. if len(name) == 0 {
  852. return nil, ErrUserNotExist{0, name, 0}
  853. }
  854. u := &User{LowerName: strings.ToLower(name)}
  855. has, err := x.Get(u)
  856. if err != nil {
  857. return nil, err
  858. } else if !has {
  859. return nil, ErrUserNotExist{0, name, 0}
  860. }
  861. return u, nil
  862. }
  863. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  864. func GetUserEmailsByNames(names []string) []string {
  865. mails := make([]string, 0, len(names))
  866. for _, name := range names {
  867. u, err := GetUserByName(name)
  868. if err != nil {
  869. continue
  870. }
  871. mails = append(mails, u.Email)
  872. }
  873. return mails
  874. }
  875. // GetUsersByIDs returns all resolved users from a list of Ids.
  876. func GetUsersByIDs(ids []int64) ([]*User, error) {
  877. ous := make([]*User, 0, len(ids))
  878. err := x.
  879. In("id", ids).
  880. Asc("name").
  881. Find(&ous)
  882. return ous, err
  883. }
  884. // GetUserIDsByNames returns a slice of ids corresponds to names.
  885. func GetUserIDsByNames(names []string) []int64 {
  886. ids := make([]int64, 0, len(names))
  887. for _, name := range names {
  888. u, err := GetUserByName(name)
  889. if err != nil {
  890. continue
  891. }
  892. ids = append(ids, u.ID)
  893. }
  894. return ids
  895. }
  896. // UserCommit represents a commit with validation of user.
  897. type UserCommit struct {
  898. User *User
  899. *git.Commit
  900. }
  901. // ValidateCommitWithEmail chceck if author's e-mail of commit is corresponsind to a user.
  902. func ValidateCommitWithEmail(c *git.Commit) *User {
  903. u, err := GetUserByEmail(c.Author.Email)
  904. if err != nil {
  905. return nil
  906. }
  907. return u
  908. }
  909. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  910. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  911. var (
  912. u *User
  913. emails = map[string]*User{}
  914. newCommits = list.New()
  915. e = oldCommits.Front()
  916. )
  917. for e != nil {
  918. c := e.Value.(*git.Commit)
  919. if v, ok := emails[c.Author.Email]; !ok {
  920. u, _ = GetUserByEmail(c.Author.Email)
  921. emails[c.Author.Email] = u
  922. } else {
  923. u = v
  924. }
  925. newCommits.PushBack(UserCommit{
  926. User: u,
  927. Commit: c,
  928. })
  929. e = e.Next()
  930. }
  931. return newCommits
  932. }
  933. // GetUserByEmail returns the user object by given e-mail if exists.
  934. func GetUserByEmail(email string) (*User, error) {
  935. if len(email) == 0 {
  936. return nil, ErrUserNotExist{0, email, 0}
  937. }
  938. email = strings.ToLower(email)
  939. // First try to find the user by primary email
  940. user := &User{Email: email}
  941. has, err := x.Get(user)
  942. if err != nil {
  943. return nil, err
  944. }
  945. if has {
  946. return user, nil
  947. }
  948. // Otherwise, check in alternative list for activated email addresses
  949. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  950. has, err = x.Get(emailAddress)
  951. if err != nil {
  952. return nil, err
  953. }
  954. if has {
  955. return GetUserByID(emailAddress.UID)
  956. }
  957. return nil, ErrUserNotExist{0, email, 0}
  958. }
  959. // SearchUserOptions contains the options for searching
  960. type SearchUserOptions struct {
  961. Keyword string
  962. Type UserType
  963. OrderBy string
  964. Page int
  965. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  966. }
  967. // SearchUserByName takes keyword and part of user name to search,
  968. // it returns results in given range and number of total results.
  969. func SearchUserByName(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  970. if len(opts.Keyword) == 0 {
  971. return users, 0, nil
  972. }
  973. opts.Keyword = strings.ToLower(opts.Keyword)
  974. if opts.PageSize <= 0 || opts.PageSize > setting.UI.ExplorePagingNum {
  975. opts.PageSize = setting.UI.ExplorePagingNum
  976. }
  977. if opts.Page <= 0 {
  978. opts.Page = 1
  979. }
  980. searchQuery := "%" + opts.Keyword + "%"
  981. users = make([]*User, 0, opts.PageSize)
  982. // Append conditions
  983. sess := x.
  984. Where("LOWER(lower_name) LIKE ?", searchQuery).
  985. Or("LOWER(full_name) LIKE ?", searchQuery).
  986. And("type = ?", opts.Type)
  987. var countSess xorm.Session
  988. countSess = *sess
  989. count, err := countSess.Count(new(User))
  990. if err != nil {
  991. return nil, 0, fmt.Errorf("Count: %v", err)
  992. }
  993. if len(opts.OrderBy) > 0 {
  994. sess.OrderBy(opts.OrderBy)
  995. }
  996. return users, count, sess.
  997. Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).
  998. Find(&users)
  999. }
  1000. // ___________ .__ .__
  1001. // \_ _____/___ | | | | ______ _ __
  1002. // | __)/ _ \| | | | / _ \ \/ \/ /
  1003. // | \( <_> ) |_| |_( <_> ) /
  1004. // \___ / \____/|____/____/\____/ \/\_/
  1005. // \/
  1006. // Follow represents relations of user and his/her followers.
  1007. type Follow struct {
  1008. ID int64 `xorm:"pk autoincr"`
  1009. UserID int64 `xorm:"UNIQUE(follow)"`
  1010. FollowID int64 `xorm:"UNIQUE(follow)"`
  1011. }
  1012. // IsFollowing returns true if user is following followID.
  1013. func IsFollowing(userID, followID int64) bool {
  1014. has, _ := x.Get(&Follow{UserID: userID, FollowID: followID})
  1015. return has
  1016. }
  1017. // FollowUser marks someone be another's follower.
  1018. func FollowUser(userID, followID int64) (err error) {
  1019. if userID == followID || IsFollowing(userID, followID) {
  1020. return nil
  1021. }
  1022. sess := x.NewSession()
  1023. defer sessionRelease(sess)
  1024. if err = sess.Begin(); err != nil {
  1025. return err
  1026. }
  1027. if _, err = sess.Insert(&Follow{UserID: userID, FollowID: followID}); err != nil {
  1028. return err
  1029. }
  1030. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?", followID); err != nil {
  1031. return err
  1032. }
  1033. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following + 1 WHERE id = ?", userID); err != nil {
  1034. return err
  1035. }
  1036. return sess.Commit()
  1037. }
  1038. // UnfollowUser unmarks someone be another's follower.
  1039. func UnfollowUser(userID, followID int64) (err error) {
  1040. if userID == followID || !IsFollowing(userID, followID) {
  1041. return nil
  1042. }
  1043. sess := x.NewSession()
  1044. defer sessionRelease(sess)
  1045. if err = sess.Begin(); err != nil {
  1046. return err
  1047. }
  1048. if _, err = sess.Delete(&Follow{UserID: userID, FollowID: followID}); err != nil {
  1049. return err
  1050. }
  1051. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?", followID); err != nil {
  1052. return err
  1053. }
  1054. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following - 1 WHERE id = ?", userID); err != nil {
  1055. return err
  1056. }
  1057. return sess.Commit()
  1058. }
  1059. // GetStarredRepos returns the repos starred by a particular user
  1060. func GetStarredRepos(userID int64, private bool) ([]*Repository, error) {
  1061. sess := x.Where("star.uid=?", userID).
  1062. Join("LEFT", "star", "`repository`.id=`star`.repo_id")
  1063. if !private {
  1064. sess = sess.And("is_private=?", false)
  1065. }
  1066. repos := make([]*Repository, 0, 10)
  1067. err := sess.Find(&repos)
  1068. if err != nil {
  1069. return nil, err
  1070. }
  1071. return repos, nil
  1072. }
  1073. // GetWatchedRepos returns the repos watched by a particular user
  1074. func GetWatchedRepos(userID int64, private bool) ([]*Repository, error) {
  1075. sess := x.Where("watch.user_id=?", userID).
  1076. Join("LEFT", "watch", "`repository`.id=`watch`.repo_id")
  1077. if !private {
  1078. sess = sess.And("is_private=?", false)
  1079. }
  1080. repos := make([]*Repository, 0, 10)
  1081. err := sess.Find(&repos)
  1082. if err != nil {
  1083. return nil, err
  1084. }
  1085. return repos, nil
  1086. }