user.go 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150
  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(all bool) error {
  385. ous, err := GetOrgUsersByUserID(u.ID, all)
  386. if err != nil {
  387. return err
  388. }
  389. u.Orgs = make([]*User, len(ous))
  390. for i, ou := range ous {
  391. u.Orgs[i], err = GetUserByID(ou.OrgID)
  392. if err != nil {
  393. return err
  394. }
  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. return os.Rename(UserPath(u.Name), UserPath(newUserName))
  585. }
  586. func updateUser(e Engine, u *User) error {
  587. // Organization does not need email
  588. if !u.IsOrganization() {
  589. u.Email = strings.ToLower(u.Email)
  590. has, err := e.Where("id!=?", u.ID).And("type=?", u.Type).And("email=?", u.Email).Get(new(User))
  591. if err != nil {
  592. return err
  593. } else if has {
  594. return ErrEmailAlreadyUsed{u.Email}
  595. }
  596. if len(u.AvatarEmail) == 0 {
  597. u.AvatarEmail = u.Email
  598. }
  599. u.Avatar = base.HashEmail(u.AvatarEmail)
  600. }
  601. u.LowerName = strings.ToLower(u.Name)
  602. u.Location = base.TruncateString(u.Location, 255)
  603. u.Website = base.TruncateString(u.Website, 255)
  604. u.Description = base.TruncateString(u.Description, 255)
  605. u.FullName = markdown.Sanitizer.Sanitize(u.FullName)
  606. _, err := e.Id(u.ID).AllCols().Update(u)
  607. return err
  608. }
  609. // UpdateUser updates user's information.
  610. func UpdateUser(u *User) error {
  611. return updateUser(x, u)
  612. }
  613. // deleteBeans deletes all given beans, beans should contain delete conditions.
  614. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  615. for i := range beans {
  616. if _, err = e.Delete(beans[i]); err != nil {
  617. return err
  618. }
  619. }
  620. return nil
  621. }
  622. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  623. func deleteUser(e *xorm.Session, u *User) error {
  624. // Note: A user owns any repository or belongs to any organization
  625. // cannot perform delete operation.
  626. // Check ownership of repository.
  627. count, err := getRepositoryCount(e, u)
  628. if err != nil {
  629. return fmt.Errorf("GetRepositoryCount: %v", err)
  630. } else if count > 0 {
  631. return ErrUserOwnRepos{UID: u.ID}
  632. }
  633. // Check membership of organization.
  634. count, err = u.getOrganizationCount(e)
  635. if err != nil {
  636. return fmt.Errorf("GetOrganizationCount: %v", err)
  637. } else if count > 0 {
  638. return ErrUserHasOrgs{UID: u.ID}
  639. }
  640. // ***** START: Watch *****
  641. watches := make([]*Watch, 0, 10)
  642. if err = e.Find(&watches, &Watch{UserID: u.ID}); err != nil {
  643. return fmt.Errorf("get all watches: %v", err)
  644. }
  645. for i := range watches {
  646. if _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", watches[i].RepoID); err != nil {
  647. return fmt.Errorf("decrease repository watch number[%d]: %v", watches[i].RepoID, err)
  648. }
  649. }
  650. // ***** END: Watch *****
  651. // ***** START: Star *****
  652. stars := make([]*Star, 0, 10)
  653. if err = e.Find(&stars, &Star{UID: u.ID}); err != nil {
  654. return fmt.Errorf("get all stars: %v", err)
  655. }
  656. for i := range stars {
  657. if _, err = e.Exec("UPDATE `repository` SET num_stars=num_stars-1 WHERE id=?", stars[i].RepoID); err != nil {
  658. return fmt.Errorf("decrease repository star number[%d]: %v", stars[i].RepoID, err)
  659. }
  660. }
  661. // ***** END: Star *****
  662. // ***** START: Follow *****
  663. followers := make([]*Follow, 0, 10)
  664. if err = e.Find(&followers, &Follow{UserID: u.ID}); err != nil {
  665. return fmt.Errorf("get all followers: %v", err)
  666. }
  667. for i := range followers {
  668. if _, err = e.Exec("UPDATE `user` SET num_followers=num_followers-1 WHERE id=?", followers[i].UserID); err != nil {
  669. return fmt.Errorf("decrease user follower number[%d]: %v", followers[i].UserID, err)
  670. }
  671. }
  672. // ***** END: Follow *****
  673. if err = deleteBeans(e,
  674. &AccessToken{UID: u.ID},
  675. &Collaboration{UserID: u.ID},
  676. &Access{UserID: u.ID},
  677. &Watch{UserID: u.ID},
  678. &Star{UID: u.ID},
  679. &Follow{FollowID: u.ID},
  680. &Action{UserID: u.ID},
  681. &IssueUser{UID: u.ID},
  682. &EmailAddress{UID: u.ID},
  683. ); err != nil {
  684. return fmt.Errorf("deleteBeans: %v", err)
  685. }
  686. // ***** START: PublicKey *****
  687. keys := make([]*PublicKey, 0, 10)
  688. if err = e.Find(&keys, &PublicKey{OwnerID: u.ID}); err != nil {
  689. return fmt.Errorf("get all public keys: %v", err)
  690. }
  691. keyIDs := make([]int64, len(keys))
  692. for i := range keys {
  693. keyIDs[i] = keys[i].ID
  694. }
  695. if err = deletePublicKeys(e, keyIDs...); err != nil {
  696. return fmt.Errorf("deletePublicKeys: %v", err)
  697. }
  698. // ***** END: PublicKey *****
  699. // Clear assignee.
  700. if _, err = e.Exec("UPDATE `issue` SET assignee_id=0 WHERE assignee_id=?", u.ID); err != nil {
  701. return fmt.Errorf("clear assignee: %v", err)
  702. }
  703. if _, err = e.Id(u.ID).Delete(new(User)); err != nil {
  704. return fmt.Errorf("Delete: %v", err)
  705. }
  706. // FIXME: system notice
  707. // Note: There are something just cannot be roll back,
  708. // so just keep error logs of those operations.
  709. os.RemoveAll(UserPath(u.Name))
  710. os.Remove(u.CustomAvatarPath())
  711. return nil
  712. }
  713. // DeleteUser completely and permanently deletes everything of a user,
  714. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  715. func DeleteUser(u *User) (err error) {
  716. sess := x.NewSession()
  717. defer sessionRelease(sess)
  718. if err = sess.Begin(); err != nil {
  719. return err
  720. }
  721. if err = deleteUser(sess, u); err != nil {
  722. // Note: don't wrapper error here.
  723. return err
  724. }
  725. if err = sess.Commit(); err != nil {
  726. return err
  727. }
  728. return RewriteAllPublicKeys()
  729. }
  730. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  731. func DeleteInactivateUsers() (err error) {
  732. users := make([]*User, 0, 10)
  733. if err = x.Where("is_active = ?", false).Find(&users); err != nil {
  734. return fmt.Errorf("get all inactive users: %v", err)
  735. }
  736. // FIXME: should only update authorized_keys file once after all deletions.
  737. for _, u := range users {
  738. if err = DeleteUser(u); err != nil {
  739. // Ignore users that were set inactive by admin.
  740. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  741. continue
  742. }
  743. return err
  744. }
  745. }
  746. _, err = x.Where("is_activated = ?", false).Delete(new(EmailAddress))
  747. return err
  748. }
  749. // UserPath returns the path absolute path of user repositories.
  750. func UserPath(userName string) string {
  751. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  752. }
  753. func GetUserByKeyID(keyID int64) (*User, error) {
  754. user := new(User)
  755. 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)
  756. if err != nil {
  757. return nil, err
  758. } else if !has {
  759. return nil, ErrUserNotKeyOwner
  760. }
  761. return user, nil
  762. }
  763. func getUserByID(e Engine, id int64) (*User, error) {
  764. u := new(User)
  765. has, err := e.Id(id).Get(u)
  766. if err != nil {
  767. return nil, err
  768. } else if !has {
  769. return nil, ErrUserNotExist{id, ""}
  770. }
  771. return u, nil
  772. }
  773. // GetUserByID returns the user object by given ID if exists.
  774. func GetUserByID(id int64) (*User, error) {
  775. return getUserByID(x, id)
  776. }
  777. // GetAssigneeByID returns the user with write access of repository by given ID.
  778. func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
  779. has, err := HasAccess(userID, repo, ACCESS_MODE_READ)
  780. if err != nil {
  781. return nil, err
  782. } else if !has {
  783. return nil, ErrUserNotExist{userID, ""}
  784. }
  785. return GetUserByID(userID)
  786. }
  787. // GetUserByName returns user by given name.
  788. func GetUserByName(name string) (*User, error) {
  789. if len(name) == 0 {
  790. return nil, ErrUserNotExist{0, name}
  791. }
  792. u := &User{LowerName: strings.ToLower(name)}
  793. has, err := x.Get(u)
  794. if err != nil {
  795. return nil, err
  796. } else if !has {
  797. return nil, ErrUserNotExist{0, name}
  798. }
  799. return u, nil
  800. }
  801. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  802. func GetUserEmailsByNames(names []string) []string {
  803. mails := make([]string, 0, len(names))
  804. for _, name := range names {
  805. u, err := GetUserByName(name)
  806. if err != nil {
  807. continue
  808. }
  809. if u.IsMailable() {
  810. mails = append(mails, u.Email)
  811. }
  812. }
  813. return mails
  814. }
  815. // GetUserIDsByNames returns a slice of ids corresponds to names.
  816. func GetUserIDsByNames(names []string) []int64 {
  817. ids := make([]int64, 0, len(names))
  818. for _, name := range names {
  819. u, err := GetUserByName(name)
  820. if err != nil {
  821. continue
  822. }
  823. ids = append(ids, u.ID)
  824. }
  825. return ids
  826. }
  827. // UserCommit represents a commit with validation of user.
  828. type UserCommit struct {
  829. User *User
  830. *git.Commit
  831. }
  832. // ValidateCommitWithEmail chceck if author's e-mail of commit is corresponsind to a user.
  833. func ValidateCommitWithEmail(c *git.Commit) *User {
  834. u, err := GetUserByEmail(c.Author.Email)
  835. if err != nil {
  836. return nil
  837. }
  838. return u
  839. }
  840. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  841. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  842. var (
  843. u *User
  844. emails = map[string]*User{}
  845. newCommits = list.New()
  846. e = oldCommits.Front()
  847. )
  848. for e != nil {
  849. c := e.Value.(*git.Commit)
  850. if v, ok := emails[c.Author.Email]; !ok {
  851. u, _ = GetUserByEmail(c.Author.Email)
  852. emails[c.Author.Email] = u
  853. } else {
  854. u = v
  855. }
  856. newCommits.PushBack(UserCommit{
  857. User: u,
  858. Commit: c,
  859. })
  860. e = e.Next()
  861. }
  862. return newCommits
  863. }
  864. // GetUserByEmail returns the user object by given e-mail if exists.
  865. func GetUserByEmail(email string) (*User, error) {
  866. if len(email) == 0 {
  867. return nil, ErrUserNotExist{0, "email"}
  868. }
  869. email = strings.ToLower(email)
  870. // First try to find the user by primary email
  871. user := &User{Email: email}
  872. has, err := x.Get(user)
  873. if err != nil {
  874. return nil, err
  875. }
  876. if has {
  877. return user, nil
  878. }
  879. // Otherwise, check in alternative list for activated email addresses
  880. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  881. has, err = x.Get(emailAddress)
  882. if err != nil {
  883. return nil, err
  884. }
  885. if has {
  886. return GetUserByID(emailAddress.UID)
  887. }
  888. return nil, ErrUserNotExist{0, email}
  889. }
  890. type SearchUserOptions struct {
  891. Keyword string
  892. Type UserType
  893. OrderBy string
  894. Page int
  895. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  896. }
  897. // SearchUserByName takes keyword and part of user name to search,
  898. // it returns results in given range and number of total results.
  899. func SearchUserByName(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  900. if len(opts.Keyword) == 0 {
  901. return users, 0, nil
  902. }
  903. opts.Keyword = strings.ToLower(opts.Keyword)
  904. if opts.PageSize <= 0 || opts.PageSize > setting.UI.ExplorePagingNum {
  905. opts.PageSize = setting.UI.ExplorePagingNum
  906. }
  907. if opts.Page <= 0 {
  908. opts.Page = 1
  909. }
  910. searchQuery := "%" + opts.Keyword + "%"
  911. users = make([]*User, 0, opts.PageSize)
  912. // Append conditions
  913. sess := x.Where("LOWER(lower_name) LIKE ?", searchQuery).
  914. Or("LOWER(full_name) LIKE ?", searchQuery).
  915. And("type = ?", opts.Type)
  916. var countSess xorm.Session
  917. countSess = *sess
  918. count, err := countSess.Count(new(User))
  919. if err != nil {
  920. return nil, 0, fmt.Errorf("Count: %v", err)
  921. }
  922. if len(opts.OrderBy) > 0 {
  923. sess.OrderBy(opts.OrderBy)
  924. }
  925. return users, count, sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).Find(&users)
  926. }
  927. // ___________ .__ .__
  928. // \_ _____/___ | | | | ______ _ __
  929. // | __)/ _ \| | | | / _ \ \/ \/ /
  930. // | \( <_> ) |_| |_( <_> ) /
  931. // \___ / \____/|____/____/\____/ \/\_/
  932. // \/
  933. // Follow represents relations of user and his/her followers.
  934. type Follow struct {
  935. ID int64 `xorm:"pk autoincr"`
  936. UserID int64 `xorm:"UNIQUE(follow)"`
  937. FollowID int64 `xorm:"UNIQUE(follow)"`
  938. }
  939. func IsFollowing(userID, followID int64) bool {
  940. has, _ := x.Get(&Follow{UserID: userID, FollowID: followID})
  941. return has
  942. }
  943. // FollowUser marks someone be another's follower.
  944. func FollowUser(userID, followID int64) (err error) {
  945. if userID == followID || IsFollowing(userID, followID) {
  946. return nil
  947. }
  948. sess := x.NewSession()
  949. defer sessionRelease(sess)
  950. if err = sess.Begin(); err != nil {
  951. return err
  952. }
  953. if _, err = sess.Insert(&Follow{UserID: userID, FollowID: followID}); err != nil {
  954. return err
  955. }
  956. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?", followID); err != nil {
  957. return err
  958. }
  959. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following + 1 WHERE id = ?", userID); err != nil {
  960. return err
  961. }
  962. return sess.Commit()
  963. }
  964. // UnfollowUser unmarks someone be another's follower.
  965. func UnfollowUser(userID, followID int64) (err error) {
  966. if userID == followID || !IsFollowing(userID, followID) {
  967. return nil
  968. }
  969. sess := x.NewSession()
  970. defer sessionRelease(sess)
  971. if err = sess.Begin(); err != nil {
  972. return err
  973. }
  974. if _, err = sess.Delete(&Follow{UserID: userID, FollowID: followID}); err != nil {
  975. return err
  976. }
  977. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?", followID); err != nil {
  978. return err
  979. }
  980. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following - 1 WHERE id = ?", userID); err != nil {
  981. return err
  982. }
  983. return sess.Commit()
  984. }