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

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