user.go 31 KB

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