user.go 31 KB

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