user.go 30 KB

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