user.go 31 KB

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