user.go 30 KB

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