user.go 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153
  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. u.Orgs = make([]*User, 0, len(orgIDs))
  390. if err = x.In("id", orgIDs).Find(&u.Orgs); err != nil {
  391. return err
  392. }
  393. return nil
  394. }
  395. // DisplayName returns full name if it's not empty,
  396. // returns username otherwise.
  397. func (u *User) DisplayName() string {
  398. if len(u.FullName) > 0 {
  399. return u.FullName
  400. }
  401. return u.Name
  402. }
  403. func (u *User) ShortName(length int) string {
  404. return base.EllipsisString(u.Name, length)
  405. }
  406. // IsMailable checks if a user is elegible
  407. // to receive emails.
  408. func (u *User) IsMailable() bool {
  409. return u.IsActive
  410. }
  411. // IsUserExist checks if given user name exist,
  412. // the user name should be noncased unique.
  413. // If uid is presented, then check will rule out that one,
  414. // it is used when update a user name in settings page.
  415. func IsUserExist(uid int64, name string) (bool, error) {
  416. if len(name) == 0 {
  417. return false, nil
  418. }
  419. return x.Where("id!=?", uid).Get(&User{LowerName: strings.ToLower(name)})
  420. }
  421. // GetUserSalt returns a ramdom user salt token.
  422. func GetUserSalt() (string, error) {
  423. return base.GetRandomString(10)
  424. }
  425. // NewGhostUser creates and returns a fake user for someone has deleted his/her account.
  426. func NewGhostUser() *User {
  427. return &User{
  428. ID: -1,
  429. Name: "Ghost",
  430. LowerName: "ghost",
  431. }
  432. }
  433. var (
  434. reservedUsernames = []string{"assets", "css", "img", "js", "less", "plugins", "debug", "raw", "install", "api", "avatar", "user", "org", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin", "new", ".", ".."}
  435. reservedUserPatterns = []string{"*.keys"}
  436. )
  437. // isUsableName checks if name is reserved or pattern of name is not allowed
  438. // based on given reserved names and patterns.
  439. // Names are exact match, patterns can be prefix or suffix match with placeholder '*'.
  440. func isUsableName(names, patterns []string, name string) error {
  441. name = strings.TrimSpace(strings.ToLower(name))
  442. if utf8.RuneCountInString(name) == 0 {
  443. return ErrNameEmpty
  444. }
  445. for i := range names {
  446. if name == names[i] {
  447. return ErrNameReserved{name}
  448. }
  449. }
  450. for _, pat := range patterns {
  451. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  452. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  453. return ErrNamePatternNotAllowed{pat}
  454. }
  455. }
  456. return nil
  457. }
  458. func IsUsableUsername(name string) error {
  459. return isUsableName(reservedUsernames, reservedUserPatterns, name)
  460. }
  461. // CreateUser creates record of a new user.
  462. func CreateUser(u *User) (err error) {
  463. if err = IsUsableUsername(u.Name); err != nil {
  464. return err
  465. }
  466. isExist, err := IsUserExist(0, u.Name)
  467. if err != nil {
  468. return err
  469. } else if isExist {
  470. return ErrUserAlreadyExist{u.Name}
  471. }
  472. u.Email = strings.ToLower(u.Email)
  473. isExist, err = IsEmailUsed(u.Email)
  474. if err != nil {
  475. return err
  476. } else if isExist {
  477. return ErrEmailAlreadyUsed{u.Email}
  478. }
  479. u.LowerName = strings.ToLower(u.Name)
  480. u.AvatarEmail = u.Email
  481. u.Avatar = base.HashEmail(u.AvatarEmail)
  482. if u.Rands, err = GetUserSalt(); err != nil {
  483. return err
  484. }
  485. if u.Salt, err = GetUserSalt(); err != nil {
  486. return err
  487. }
  488. u.EncodePasswd()
  489. u.MaxRepoCreation = -1
  490. sess := x.NewSession()
  491. defer sessionRelease(sess)
  492. if err = sess.Begin(); err != nil {
  493. return err
  494. }
  495. if _, err = sess.Insert(u); err != nil {
  496. return err
  497. } else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
  498. return err
  499. }
  500. return sess.Commit()
  501. }
  502. func countUsers(e Engine) int64 {
  503. count, _ := e.Where("type=0").Count(new(User))
  504. return count
  505. }
  506. // CountUsers returns number of users.
  507. func CountUsers() int64 {
  508. return countUsers(x)
  509. }
  510. // Users returns number of users in given page.
  511. func Users(page, pageSize int) ([]*User, error) {
  512. users := make([]*User, 0, pageSize)
  513. return users, x.Limit(pageSize, (page-1)*pageSize).Where("type=0").Asc("id").Find(&users)
  514. }
  515. // get user by erify code
  516. func getVerifyUser(code string) (user *User) {
  517. if len(code) <= base.TimeLimitCodeLength {
  518. return nil
  519. }
  520. // use tail hex username query user
  521. hexStr := code[base.TimeLimitCodeLength:]
  522. if b, err := hex.DecodeString(hexStr); err == nil {
  523. if user, err = GetUserByName(string(b)); user != nil {
  524. return user
  525. }
  526. log.Error(4, "user.getVerifyUser: %v", err)
  527. }
  528. return nil
  529. }
  530. // verify active code when active account
  531. func VerifyUserActiveCode(code string) (user *User) {
  532. minutes := setting.Service.ActiveCodeLives
  533. if user = getVerifyUser(code); user != nil {
  534. // time limit code
  535. prefix := code[:base.TimeLimitCodeLength]
  536. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands
  537. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  538. return user
  539. }
  540. }
  541. return nil
  542. }
  543. // verify active code when active account
  544. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  545. minutes := setting.Service.ActiveCodeLives
  546. if user := getVerifyUser(code); user != nil {
  547. // time limit code
  548. prefix := code[:base.TimeLimitCodeLength]
  549. data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands
  550. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  551. emailAddress := &EmailAddress{Email: email}
  552. if has, _ := x.Get(emailAddress); has {
  553. return emailAddress
  554. }
  555. }
  556. }
  557. return nil
  558. }
  559. // ChangeUserName changes all corresponding setting from old user name to new one.
  560. func ChangeUserName(u *User, newUserName string) (err error) {
  561. if err = IsUsableUsername(newUserName); err != nil {
  562. return err
  563. }
  564. isExist, err := IsUserExist(0, newUserName)
  565. if err != nil {
  566. return err
  567. } else if isExist {
  568. return ErrUserAlreadyExist{newUserName}
  569. }
  570. if err = ChangeUsernameInPullRequests(u.Name, newUserName); err != nil {
  571. return fmt.Errorf("ChangeUsernameInPullRequests: %v", err)
  572. }
  573. // Delete all local copies of repository wiki that user owns.
  574. if err = x.Where("owner_id=?", u.ID).Iterate(new(Repository), func(idx int, bean interface{}) error {
  575. repo := bean.(*Repository)
  576. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  577. return nil
  578. }); err != nil {
  579. return fmt.Errorf("Delete repository wiki local copy: %v", err)
  580. }
  581. // Rename or create user base directory
  582. baseDir := UserPath(u.Name)
  583. newBaseDir := UserPath(newUserName)
  584. if com.IsExist(baseDir) {
  585. return os.Rename(baseDir, newBaseDir)
  586. }
  587. return os.MkdirAll(newBaseDir, os.ModePerm)
  588. }
  589. func updateUser(e Engine, u *User) error {
  590. // Organization does not need email
  591. if !u.IsOrganization() {
  592. u.Email = strings.ToLower(u.Email)
  593. has, err := e.Where("id!=?", u.ID).And("type=?", u.Type).And("email=?", u.Email).Get(new(User))
  594. if err != nil {
  595. return err
  596. } else if has {
  597. return ErrEmailAlreadyUsed{u.Email}
  598. }
  599. if len(u.AvatarEmail) == 0 {
  600. u.AvatarEmail = u.Email
  601. }
  602. u.Avatar = base.HashEmail(u.AvatarEmail)
  603. }
  604. u.LowerName = strings.ToLower(u.Name)
  605. u.Location = base.TruncateString(u.Location, 255)
  606. u.Website = base.TruncateString(u.Website, 255)
  607. u.Description = base.TruncateString(u.Description, 255)
  608. u.FullName = markdown.Sanitizer.Sanitize(u.FullName)
  609. _, err := e.Id(u.ID).AllCols().Update(u)
  610. return err
  611. }
  612. // UpdateUser updates user's information.
  613. func UpdateUser(u *User) error {
  614. return updateUser(x, u)
  615. }
  616. // deleteBeans deletes all given beans, beans should contain delete conditions.
  617. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  618. for i := range beans {
  619. if _, err = e.Delete(beans[i]); err != nil {
  620. return err
  621. }
  622. }
  623. return nil
  624. }
  625. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  626. func deleteUser(e *xorm.Session, u *User) error {
  627. // Note: A user owns any repository or belongs to any organization
  628. // cannot perform delete operation.
  629. // Check ownership of repository.
  630. count, err := getRepositoryCount(e, u)
  631. if err != nil {
  632. return fmt.Errorf("GetRepositoryCount: %v", err)
  633. } else if count > 0 {
  634. return ErrUserOwnRepos{UID: u.ID}
  635. }
  636. // Check membership of organization.
  637. count, err = u.getOrganizationCount(e)
  638. if err != nil {
  639. return fmt.Errorf("GetOrganizationCount: %v", err)
  640. } else if count > 0 {
  641. return ErrUserHasOrgs{UID: u.ID}
  642. }
  643. // ***** START: Watch *****
  644. watches := make([]*Watch, 0, 10)
  645. if err = e.Find(&watches, &Watch{UserID: u.ID}); err != nil {
  646. return fmt.Errorf("get all watches: %v", err)
  647. }
  648. for i := range watches {
  649. if _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", watches[i].RepoID); err != nil {
  650. return fmt.Errorf("decrease repository watch number[%d]: %v", watches[i].RepoID, err)
  651. }
  652. }
  653. // ***** END: Watch *****
  654. // ***** START: Star *****
  655. stars := make([]*Star, 0, 10)
  656. if err = e.Find(&stars, &Star{UID: u.ID}); err != nil {
  657. return fmt.Errorf("get all stars: %v", err)
  658. }
  659. for i := range stars {
  660. if _, err = e.Exec("UPDATE `repository` SET num_stars=num_stars-1 WHERE id=?", stars[i].RepoID); err != nil {
  661. return fmt.Errorf("decrease repository star number[%d]: %v", stars[i].RepoID, err)
  662. }
  663. }
  664. // ***** END: Star *****
  665. // ***** START: Follow *****
  666. followers := make([]*Follow, 0, 10)
  667. if err = e.Find(&followers, &Follow{UserID: u.ID}); err != nil {
  668. return fmt.Errorf("get all followers: %v", err)
  669. }
  670. for i := range followers {
  671. if _, err = e.Exec("UPDATE `user` SET num_followers=num_followers-1 WHERE id=?", followers[i].UserID); err != nil {
  672. return fmt.Errorf("decrease user follower number[%d]: %v", followers[i].UserID, err)
  673. }
  674. }
  675. // ***** END: Follow *****
  676. if err = deleteBeans(e,
  677. &AccessToken{UID: u.ID},
  678. &Collaboration{UserID: u.ID},
  679. &Access{UserID: u.ID},
  680. &Watch{UserID: u.ID},
  681. &Star{UID: u.ID},
  682. &Follow{FollowID: u.ID},
  683. &Action{UserID: u.ID},
  684. &IssueUser{UID: u.ID},
  685. &EmailAddress{UID: u.ID},
  686. ); err != nil {
  687. return fmt.Errorf("deleteBeans: %v", err)
  688. }
  689. // ***** START: PublicKey *****
  690. keys := make([]*PublicKey, 0, 10)
  691. if err = e.Find(&keys, &PublicKey{OwnerID: u.ID}); err != nil {
  692. return fmt.Errorf("get all public keys: %v", err)
  693. }
  694. keyIDs := make([]int64, len(keys))
  695. for i := range keys {
  696. keyIDs[i] = keys[i].ID
  697. }
  698. if err = deletePublicKeys(e, keyIDs...); err != nil {
  699. return fmt.Errorf("deletePublicKeys: %v", err)
  700. }
  701. // ***** END: PublicKey *****
  702. // Clear assignee.
  703. if _, err = e.Exec("UPDATE `issue` SET assignee_id=0 WHERE assignee_id=?", u.ID); err != nil {
  704. return fmt.Errorf("clear assignee: %v", err)
  705. }
  706. if _, err = e.Id(u.ID).Delete(new(User)); err != nil {
  707. return fmt.Errorf("Delete: %v", err)
  708. }
  709. // FIXME: system notice
  710. // Note: There are something just cannot be roll back,
  711. // so just keep error logs of those operations.
  712. os.RemoveAll(UserPath(u.Name))
  713. os.Remove(u.CustomAvatarPath())
  714. return nil
  715. }
  716. // DeleteUser completely and permanently deletes everything of a user,
  717. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  718. func DeleteUser(u *User) (err error) {
  719. sess := x.NewSession()
  720. defer sessionRelease(sess)
  721. if err = sess.Begin(); err != nil {
  722. return err
  723. }
  724. if err = deleteUser(sess, u); err != nil {
  725. // Note: don't wrapper error here.
  726. return err
  727. }
  728. if err = sess.Commit(); err != nil {
  729. return err
  730. }
  731. return RewriteAllPublicKeys()
  732. }
  733. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  734. func DeleteInactivateUsers() (err error) {
  735. users := make([]*User, 0, 10)
  736. if err = x.Where("is_active = ?", false).Find(&users); err != nil {
  737. return fmt.Errorf("get all inactive users: %v", err)
  738. }
  739. // FIXME: should only update authorized_keys file once after all deletions.
  740. for _, u := range users {
  741. if err = DeleteUser(u); err != nil {
  742. // Ignore users that were set inactive by admin.
  743. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  744. continue
  745. }
  746. return err
  747. }
  748. }
  749. _, err = x.Where("is_activated = ?", false).Delete(new(EmailAddress))
  750. return err
  751. }
  752. // UserPath returns the path absolute path of user repositories.
  753. func UserPath(userName string) string {
  754. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  755. }
  756. func GetUserByKeyID(keyID int64) (*User, error) {
  757. user := new(User)
  758. 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)
  759. if err != nil {
  760. return nil, err
  761. } else if !has {
  762. return nil, ErrUserNotKeyOwner
  763. }
  764. return user, nil
  765. }
  766. func getUserByID(e Engine, id int64) (*User, error) {
  767. u := new(User)
  768. has, err := e.Id(id).Get(u)
  769. if err != nil {
  770. return nil, err
  771. } else if !has {
  772. return nil, ErrUserNotExist{id, ""}
  773. }
  774. return u, nil
  775. }
  776. // GetUserByID returns the user object by given ID if exists.
  777. func GetUserByID(id int64) (*User, error) {
  778. return getUserByID(x, id)
  779. }
  780. // GetAssigneeByID returns the user with write access of repository by given ID.
  781. func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
  782. has, err := HasAccess(userID, repo, ACCESS_MODE_READ)
  783. if err != nil {
  784. return nil, err
  785. } else if !has {
  786. return nil, ErrUserNotExist{userID, ""}
  787. }
  788. return GetUserByID(userID)
  789. }
  790. // GetUserByName returns user by given name.
  791. func GetUserByName(name string) (*User, error) {
  792. if len(name) == 0 {
  793. return nil, ErrUserNotExist{0, name}
  794. }
  795. u := &User{LowerName: strings.ToLower(name)}
  796. has, err := x.Get(u)
  797. if err != nil {
  798. return nil, err
  799. } else if !has {
  800. return nil, ErrUserNotExist{0, name}
  801. }
  802. return u, nil
  803. }
  804. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  805. func GetUserEmailsByNames(names []string) []string {
  806. mails := make([]string, 0, len(names))
  807. for _, name := range names {
  808. u, err := GetUserByName(name)
  809. if err != nil {
  810. continue
  811. }
  812. if u.IsMailable() {
  813. mails = append(mails, u.Email)
  814. }
  815. }
  816. return mails
  817. }
  818. // GetUserIDsByNames returns a slice of ids corresponds to names.
  819. func GetUserIDsByNames(names []string) []int64 {
  820. ids := make([]int64, 0, len(names))
  821. for _, name := range names {
  822. u, err := GetUserByName(name)
  823. if err != nil {
  824. continue
  825. }
  826. ids = append(ids, u.ID)
  827. }
  828. return ids
  829. }
  830. // UserCommit represents a commit with validation of user.
  831. type UserCommit struct {
  832. User *User
  833. *git.Commit
  834. }
  835. // ValidateCommitWithEmail chceck if author's e-mail of commit is corresponsind to a user.
  836. func ValidateCommitWithEmail(c *git.Commit) *User {
  837. u, err := GetUserByEmail(c.Author.Email)
  838. if err != nil {
  839. return nil
  840. }
  841. return u
  842. }
  843. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  844. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  845. var (
  846. u *User
  847. emails = map[string]*User{}
  848. newCommits = list.New()
  849. e = oldCommits.Front()
  850. )
  851. for e != nil {
  852. c := e.Value.(*git.Commit)
  853. if v, ok := emails[c.Author.Email]; !ok {
  854. u, _ = GetUserByEmail(c.Author.Email)
  855. emails[c.Author.Email] = u
  856. } else {
  857. u = v
  858. }
  859. newCommits.PushBack(UserCommit{
  860. User: u,
  861. Commit: c,
  862. })
  863. e = e.Next()
  864. }
  865. return newCommits
  866. }
  867. // GetUserByEmail returns the user object by given e-mail if exists.
  868. func GetUserByEmail(email string) (*User, error) {
  869. if len(email) == 0 {
  870. return nil, ErrUserNotExist{0, "email"}
  871. }
  872. email = strings.ToLower(email)
  873. // First try to find the user by primary email
  874. user := &User{Email: email}
  875. has, err := x.Get(user)
  876. if err != nil {
  877. return nil, err
  878. }
  879. if has {
  880. return user, nil
  881. }
  882. // Otherwise, check in alternative list for activated email addresses
  883. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  884. has, err = x.Get(emailAddress)
  885. if err != nil {
  886. return nil, err
  887. }
  888. if has {
  889. return GetUserByID(emailAddress.UID)
  890. }
  891. return nil, ErrUserNotExist{0, email}
  892. }
  893. type SearchUserOptions struct {
  894. Keyword string
  895. Type UserType
  896. OrderBy string
  897. Page int
  898. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  899. }
  900. // SearchUserByName takes keyword and part of user name to search,
  901. // it returns results in given range and number of total results.
  902. func SearchUserByName(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  903. if len(opts.Keyword) == 0 {
  904. return users, 0, nil
  905. }
  906. opts.Keyword = strings.ToLower(opts.Keyword)
  907. if opts.PageSize <= 0 || opts.PageSize > setting.UI.ExplorePagingNum {
  908. opts.PageSize = setting.UI.ExplorePagingNum
  909. }
  910. if opts.Page <= 0 {
  911. opts.Page = 1
  912. }
  913. searchQuery := "%" + opts.Keyword + "%"
  914. users = make([]*User, 0, opts.PageSize)
  915. // Append conditions
  916. sess := x.Where("LOWER(lower_name) LIKE ?", searchQuery).
  917. Or("LOWER(full_name) LIKE ?", searchQuery).
  918. And("type = ?", opts.Type)
  919. var countSess xorm.Session
  920. countSess = *sess
  921. count, err := countSess.Count(new(User))
  922. if err != nil {
  923. return nil, 0, fmt.Errorf("Count: %v", err)
  924. }
  925. if len(opts.OrderBy) > 0 {
  926. sess.OrderBy(opts.OrderBy)
  927. }
  928. return users, count, sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).Find(&users)
  929. }
  930. // ___________ .__ .__
  931. // \_ _____/___ | | | | ______ _ __
  932. // | __)/ _ \| | | | / _ \ \/ \/ /
  933. // | \( <_> ) |_| |_( <_> ) /
  934. // \___ / \____/|____/____/\____/ \/\_/
  935. // \/
  936. // Follow represents relations of user and his/her followers.
  937. type Follow struct {
  938. ID int64 `xorm:"pk autoincr"`
  939. UserID int64 `xorm:"UNIQUE(follow)"`
  940. FollowID int64 `xorm:"UNIQUE(follow)"`
  941. }
  942. func IsFollowing(userID, followID int64) bool {
  943. has, _ := x.Get(&Follow{UserID: userID, FollowID: followID})
  944. return has
  945. }
  946. // FollowUser marks someone be another's follower.
  947. func FollowUser(userID, followID int64) (err error) {
  948. if userID == followID || IsFollowing(userID, followID) {
  949. return nil
  950. }
  951. sess := x.NewSession()
  952. defer sessionRelease(sess)
  953. if err = sess.Begin(); err != nil {
  954. return err
  955. }
  956. if _, err = sess.Insert(&Follow{UserID: userID, FollowID: followID}); err != nil {
  957. return err
  958. }
  959. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?", followID); err != nil {
  960. return err
  961. }
  962. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following + 1 WHERE id = ?", userID); err != nil {
  963. return err
  964. }
  965. return sess.Commit()
  966. }
  967. // UnfollowUser unmarks someone be another's follower.
  968. func UnfollowUser(userID, followID int64) (err error) {
  969. if userID == followID || !IsFollowing(userID, followID) {
  970. return nil
  971. }
  972. sess := x.NewSession()
  973. defer sessionRelease(sess)
  974. if err = sess.Begin(); err != nil {
  975. return err
  976. }
  977. if _, err = sess.Delete(&Follow{UserID: userID, FollowID: followID}); err != nil {
  978. return err
  979. }
  980. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?", followID); err != nil {
  981. return err
  982. }
  983. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following - 1 WHERE id = ?", userID); err != nil {
  984. return err
  985. }
  986. return sess.Commit()
  987. }