user.go 30 KB

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