user.go 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213
  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 db
  5. import (
  6. "bufio"
  7. "bytes"
  8. "crypto/sha256"
  9. "crypto/subtle"
  10. "encoding/hex"
  11. "fmt"
  12. "image"
  13. _ "image/jpeg"
  14. "image/png"
  15. "os"
  16. "path"
  17. "path/filepath"
  18. "strings"
  19. "time"
  20. "unicode/utf8"
  21. "github.com/nfnt/resize"
  22. "github.com/unknwon/com"
  23. "golang.org/x/crypto/pbkdf2"
  24. log "unknwon.dev/clog/v2"
  25. "xorm.io/xorm"
  26. "github.com/gogs/git-module"
  27. api "github.com/gogs/go-gogs-client"
  28. "github.com/G-Node/gogs/internal/avatar"
  29. "github.com/G-Node/gogs/internal/conf"
  30. "github.com/G-Node/gogs/internal/db/errors"
  31. "github.com/G-Node/gogs/internal/errutil"
  32. "github.com/G-Node/gogs/internal/strutil"
  33. "github.com/G-Node/gogs/internal/tool"
  34. "golang.org/x/crypto/bcrypt"
  35. )
  36. // USER_AVATAR_URL_PREFIX is used to identify a URL is to access user avatar.
  37. const USER_AVATAR_URL_PREFIX = "avatars"
  38. type UserType int
  39. const (
  40. UserIndividual UserType = iota // Historic reason to make it starts at 0.
  41. UserOrganization
  42. )
  43. // User represents the object of individual and member of organization.
  44. type User struct {
  45. ID int64
  46. LowerName string `xorm:"UNIQUE NOT NULL" gorm:"UNIQUE"`
  47. Name string `xorm:"UNIQUE NOT NULL" gorm:"NOT NULL"`
  48. FullName string
  49. // Email is the primary email address (to be used for communication)
  50. Email string `xorm:"NOT NULL" gorm:"NOT NULL"`
  51. Passwd string `xorm:"NOT NULL" gorm:"NOT NULL"`
  52. LoginSource int64 `xorm:"NOT NULL DEFAULT 0" gorm:"NOT NULL;DEFAULT:0"`
  53. LoginName string
  54. Type UserType
  55. OwnedOrgs []*User `xorm:"-" gorm:"-" json:"-"`
  56. Orgs []*User `xorm:"-" gorm:"-" json:"-"`
  57. Repos []*Repository `xorm:"-" gorm:"-" json:"-"`
  58. Location string
  59. Website string
  60. Rands string `xorm:"VARCHAR(10)" gorm:"TYPE:VARCHAR(10)"`
  61. Salt string `xorm:"VARCHAR(10)" gorm:"TYPE:VARCHAR(10)"`
  62. Created time.Time `xorm:"-" gorm:"-" json:"-"`
  63. CreatedUnix int64
  64. Updated time.Time `xorm:"-" gorm:"-" json:"-"`
  65. UpdatedUnix int64
  66. // Remember visibility choice for convenience, true for private
  67. LastRepoVisibility bool
  68. // Maximum repository creation limit, -1 means use global default
  69. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1" gorm:"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" gorm:"TYPE:VARCHAR(2048);NOT NULL"`
  78. AvatarEmail string `xorm:"NOT NULL" gorm:"NOT NULL"`
  79. UseCustomAvatar bool
  80. // Counters
  81. NumFollowers int
  82. NumFollowing int `xorm:"NOT NULL DEFAULT 0" gorm:"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:"-" gorm:"-" json:"-"`
  90. Members []*User `xorm:"-" gorm:"-" 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 LoginPlain.
  125. func (u *User) IsLocal() bool {
  126. return u.LoginSource <= 0
  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 conf.Repository.MaxCreationLimit
  136. }
  137. return u.MaxRepoCreation
  138. }
  139. func (u *User) CanCreateRepo() bool {
  140. if u.MaxRepoCreation <= -1 {
  141. if conf.Repository.MaxCreationLimit <= -1 {
  142. return true
  143. }
  144. return u.NumRepos < conf.Repository.MaxCreationLimit
  145. }
  146. return u.NumRepos < u.MaxRepoCreation
  147. }
  148. func (u *User) CanCreateOrganization() bool {
  149. return !conf.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 conf.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 conf.Server.Subpath + "/org/" + u.Name + "/dashboard/"
  163. }
  164. return conf.Server.Subpath + "/"
  165. }
  166. // HomeLink returns the user or organization home page link.
  167. func (u *User) HomeLink() string {
  168. return conf.Server.Subpath + "/" + u.Name
  169. }
  170. func (u *User) HTMLURL() string {
  171. return conf.Server.ExternalURL + 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. conf.Auth.ActivateCodeLives, 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(conf.Picture.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 := conf.Server.Subpath + "/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", conf.Server.Subpath, USER_AVATAR_URL_PREFIX, u.ID)
  228. case conf.Picture.DisableGravatar:
  229. if !com.IsExist(u.CustomAvatarPath()) {
  230. if err := u.GenerateRandomAvatar(); err != nil {
  231. log.Error("GenerateRandomAvatar: %v", err)
  232. }
  233. }
  234. return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, 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 conf.Server.ExternalURL + strings.TrimPrefix(link, conf.Server.Subpath)[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 conf.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 conf.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. // EncodePassword encodes password to safe format.
  280. func (u *User) EncodePassword() {
  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.EncodePassword()
  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(conf.Picture.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, AccessModeAdmin)
  328. if err != nil {
  329. log.Error("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, AccessModeWrite)
  336. if err != nil {
  337. log.Error("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 == UserOrganization
  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 TwoFactors.IsUserEnabled(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 = ?", UserOrganization).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(conf.CustomDir(), "blocklist")
  426. if !com.IsExist(fpath) {
  427. return false
  428. }
  429. f, err := os.Open(fpath)
  430. if err != nil {
  431. log.Error("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 strutil.RandomChars(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. type ErrNameNotAllowed struct {
  462. args errutil.Args
  463. }
  464. func IsErrNameNotAllowed(err error) bool {
  465. _, ok := err.(ErrNameNotAllowed)
  466. return ok
  467. }
  468. func (err ErrNameNotAllowed) Value() string {
  469. val, ok := err.args["name"].(string)
  470. if ok {
  471. return val
  472. }
  473. val, ok = err.args["pattern"].(string)
  474. if ok {
  475. return val
  476. }
  477. return "<value not found>"
  478. }
  479. func (err ErrNameNotAllowed) Error() string {
  480. return fmt.Sprintf("name is not allowed: %v", err.args)
  481. }
  482. // isNameAllowed checks if name is reserved or pattern of name is not allowed
  483. // based on given reserved names and patterns.
  484. // Names are exact match, patterns can be prefix or suffix match with placeholder '*'.
  485. func isNameAllowed(names, patterns []string, name string) error {
  486. name = strings.TrimSpace(strings.ToLower(name))
  487. if utf8.RuneCountInString(name) == 0 {
  488. return ErrNameNotAllowed{args: errutil.Args{"reason": "empty name"}}
  489. }
  490. for i := range names {
  491. if name == names[i] {
  492. return ErrNameNotAllowed{args: errutil.Args{"reason": "reserved", "name": name}}
  493. }
  494. }
  495. for _, pat := range patterns {
  496. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  497. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  498. return ErrNameNotAllowed{args: errutil.Args{"reason": "reserved", "pattern": pat}}
  499. }
  500. }
  501. return nil
  502. }
  503. // isUsernameAllowed return an error if given name is a reserved name or pattern for users.
  504. func isUsernameAllowed(name string) error {
  505. return isNameAllowed(reservedUsernames, reservedUserPatterns, name)
  506. }
  507. // CreateUser creates record of a new user.
  508. // Deprecated: Use Users.Create instead.
  509. func CreateUser(u *User) (err error) {
  510. if err = isUsernameAllowed(u.Name); err != nil {
  511. return err
  512. }
  513. isExist, err := IsUserExist(0, u.Name)
  514. if err != nil {
  515. return err
  516. } else if isExist {
  517. return ErrUserAlreadyExist{args: errutil.Args{"name": u.Name}}
  518. }
  519. u.Email = strings.ToLower(u.Email)
  520. isExist, err = IsEmailUsed(u.Email)
  521. if err != nil {
  522. return err
  523. } else if isExist {
  524. return ErrEmailAlreadyUsed{args: errutil.Args{"email": u.Email}}
  525. }
  526. if IsBlockedDomain(u.Email) {
  527. return ErrBlockedDomain{u.Email}
  528. }
  529. u.LowerName = strings.ToLower(u.Name)
  530. u.AvatarEmail = u.Email
  531. u.Avatar = tool.HashEmail(u.AvatarEmail)
  532. if u.Rands, err = GetUserSalt(); err != nil {
  533. return err
  534. }
  535. if u.Salt, err = GetUserSalt(); err != nil {
  536. return err
  537. }
  538. u.EncodePassword()
  539. u.MaxRepoCreation = -1
  540. sess := x.NewSession()
  541. defer sess.Close()
  542. if err = sess.Begin(); err != nil {
  543. return err
  544. }
  545. if _, err = sess.Insert(u); err != nil {
  546. return err
  547. } else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
  548. return err
  549. }
  550. return sess.Commit()
  551. }
  552. func countUsers(e Engine) int64 {
  553. count, _ := e.Where("type=0").Count(new(User))
  554. return count
  555. }
  556. // CountUsers returns number of users.
  557. func CountUsers() int64 {
  558. return countUsers(x)
  559. }
  560. // Users returns number of users in given page.
  561. func ListUsers(page, pageSize int) ([]*User, error) {
  562. users := make([]*User, 0, pageSize)
  563. return users, x.Limit(pageSize, (page-1)*pageSize).Where("type=0").Asc("id").Find(&users)
  564. }
  565. // parseUserFromCode returns user by username encoded in code.
  566. // It returns nil if code or username is invalid.
  567. func parseUserFromCode(code string) (user *User) {
  568. if len(code) <= tool.TIME_LIMIT_CODE_LENGTH {
  569. return nil
  570. }
  571. // Use tail hex username to query user
  572. hexStr := code[tool.TIME_LIMIT_CODE_LENGTH:]
  573. if b, err := hex.DecodeString(hexStr); err == nil {
  574. if user, err = GetUserByName(string(b)); user != nil {
  575. return user
  576. } else if !IsErrUserNotExist(err) {
  577. log.Error("Failed to get user by name %q: %v", string(b), err)
  578. }
  579. }
  580. return nil
  581. }
  582. // verify active code when active account
  583. func VerifyUserActiveCode(code string) (user *User) {
  584. minutes := conf.Auth.ActivateCodeLives
  585. if user = parseUserFromCode(code); user != nil {
  586. // time limit code
  587. prefix := code[:tool.TIME_LIMIT_CODE_LENGTH]
  588. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands
  589. if tool.VerifyTimeLimitCode(data, minutes, prefix) {
  590. return user
  591. }
  592. }
  593. return nil
  594. }
  595. // verify active code when active account
  596. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  597. minutes := conf.Auth.ActivateCodeLives
  598. if user := parseUserFromCode(code); user != nil {
  599. // time limit code
  600. prefix := code[:tool.TIME_LIMIT_CODE_LENGTH]
  601. data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands
  602. if tool.VerifyTimeLimitCode(data, minutes, prefix) {
  603. emailAddress := &EmailAddress{Email: email}
  604. if has, _ := x.Get(emailAddress); has {
  605. return emailAddress
  606. }
  607. }
  608. }
  609. return nil
  610. }
  611. // ChangeUserName changes all corresponding setting from old user name to new one.
  612. func ChangeUserName(u *User, newUserName string) (err error) {
  613. if err = isUsernameAllowed(newUserName); err != nil {
  614. return err
  615. }
  616. isExist, err := IsUserExist(0, newUserName)
  617. if err != nil {
  618. return err
  619. } else if isExist {
  620. return ErrUserAlreadyExist{args: errutil.Args{"name": newUserName}}
  621. }
  622. if err = ChangeUsernameInPullRequests(u.Name, newUserName); err != nil {
  623. return fmt.Errorf("ChangeUsernameInPullRequests: %v", err)
  624. }
  625. // Delete all local copies of repositories and wikis the user owns.
  626. if err = x.Where("owner_id=?", u.ID).Iterate(new(Repository), func(idx int, bean interface{}) error {
  627. repo := bean.(*Repository)
  628. deleteRepoLocalCopy(repo)
  629. // TODO: By the same reasoning, shouldn't we also sync access to the local wiki path?
  630. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  631. return nil
  632. }); err != nil {
  633. return fmt.Errorf("delete repository and wiki local copy: %v", err)
  634. }
  635. // Rename or create user base directory
  636. baseDir := UserPath(u.Name)
  637. newBaseDir := UserPath(newUserName)
  638. if com.IsExist(baseDir) {
  639. return os.Rename(baseDir, newBaseDir)
  640. }
  641. return os.MkdirAll(newBaseDir, os.ModePerm)
  642. }
  643. func updateUser(e Engine, u *User) error {
  644. // Organization does not need email
  645. if !u.IsOrganization() {
  646. u.Email = strings.ToLower(u.Email)
  647. has, err := e.Where("id!=?", u.ID).And("type=?", u.Type).And("email=?", u.Email).Get(new(User))
  648. if err != nil {
  649. return err
  650. } else if has {
  651. return ErrEmailAlreadyUsed{args: errutil.Args{"email": u.Email}}
  652. }
  653. if len(u.AvatarEmail) == 0 {
  654. u.AvatarEmail = u.Email
  655. }
  656. u.Avatar = tool.HashEmail(u.AvatarEmail)
  657. }
  658. u.LowerName = strings.ToLower(u.Name)
  659. u.Location = tool.TruncateString(u.Location, 255)
  660. u.Website = tool.TruncateString(u.Website, 255)
  661. u.Description = tool.TruncateString(u.Description, 255)
  662. _, err := e.ID(u.ID).AllCols().Update(u)
  663. return err
  664. }
  665. // UpdateUser updates user's information.
  666. func UpdateUser(u *User) error {
  667. return updateUser(x, u)
  668. }
  669. // deleteBeans deletes all given beans, beans should contain delete conditions.
  670. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  671. for i := range beans {
  672. if _, err = e.Delete(beans[i]); err != nil {
  673. return err
  674. }
  675. }
  676. return nil
  677. }
  678. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  679. func deleteUser(e *xorm.Session, u *User) error {
  680. // Note: A user owns any repository or belongs to any organization
  681. // cannot perform delete operation.
  682. // Check ownership of repository.
  683. count, err := getRepositoryCount(e, u)
  684. if err != nil {
  685. return fmt.Errorf("GetRepositoryCount: %v", err)
  686. } else if count > 0 {
  687. return ErrUserOwnRepos{UID: u.ID}
  688. }
  689. // Check membership of organization.
  690. count, err = u.getOrganizationCount(e)
  691. if err != nil {
  692. return fmt.Errorf("GetOrganizationCount: %v", err)
  693. } else if count > 0 {
  694. return ErrUserHasOrgs{UID: u.ID}
  695. }
  696. // ***** START: Watch *****
  697. watches := make([]*Watch, 0, 10)
  698. if err = e.Find(&watches, &Watch{UserID: u.ID}); err != nil {
  699. return fmt.Errorf("get all watches: %v", err)
  700. }
  701. for i := range watches {
  702. if _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", watches[i].RepoID); err != nil {
  703. return fmt.Errorf("decrease repository watch number[%d]: %v", watches[i].RepoID, err)
  704. }
  705. }
  706. // ***** END: Watch *****
  707. // ***** START: Star *****
  708. stars := make([]*Star, 0, 10)
  709. if err = e.Find(&stars, &Star{UID: u.ID}); err != nil {
  710. return fmt.Errorf("get all stars: %v", err)
  711. }
  712. for i := range stars {
  713. if _, err = e.Exec("UPDATE `repository` SET num_stars=num_stars-1 WHERE id=?", stars[i].RepoID); err != nil {
  714. return fmt.Errorf("decrease repository star number[%d]: %v", stars[i].RepoID, err)
  715. }
  716. }
  717. // ***** END: Star *****
  718. // ***** START: Follow *****
  719. followers := make([]*Follow, 0, 10)
  720. if err = e.Find(&followers, &Follow{UserID: u.ID}); err != nil {
  721. return fmt.Errorf("get all followers: %v", err)
  722. }
  723. for i := range followers {
  724. if _, err = e.Exec("UPDATE `user` SET num_followers=num_followers-1 WHERE id=?", followers[i].UserID); err != nil {
  725. return fmt.Errorf("decrease user follower number[%d]: %v", followers[i].UserID, err)
  726. }
  727. }
  728. // ***** END: Follow *****
  729. if err = deleteBeans(e,
  730. &AccessToken{UserID: u.ID},
  731. &Collaboration{UserID: u.ID},
  732. &Access{UserID: u.ID},
  733. &Watch{UserID: u.ID},
  734. &Star{UID: u.ID},
  735. &Follow{FollowID: u.ID},
  736. &Action{UserID: u.ID},
  737. &IssueUser{UID: u.ID},
  738. &EmailAddress{UID: u.ID},
  739. ); err != nil {
  740. return fmt.Errorf("deleteBeans: %v", err)
  741. }
  742. // ***** START: PublicKey *****
  743. keys := make([]*PublicKey, 0, 10)
  744. if err = e.Find(&keys, &PublicKey{OwnerID: u.ID}); err != nil {
  745. return fmt.Errorf("get all public keys: %v", err)
  746. }
  747. keyIDs := make([]int64, len(keys))
  748. for i := range keys {
  749. keyIDs[i] = keys[i].ID
  750. }
  751. if err = deletePublicKeys(e, keyIDs...); err != nil {
  752. return fmt.Errorf("deletePublicKeys: %v", err)
  753. }
  754. // ***** END: PublicKey *****
  755. // Clear assignee.
  756. if _, err = e.Exec("UPDATE `issue` SET assignee_id=0 WHERE assignee_id=?", u.ID); err != nil {
  757. return fmt.Errorf("clear assignee: %v", err)
  758. }
  759. if _, err = e.ID(u.ID).Delete(new(User)); err != nil {
  760. return fmt.Errorf("Delete: %v", err)
  761. }
  762. // FIXME: system notice
  763. // Note: There are something just cannot be roll back,
  764. // so just keep error logs of those operations.
  765. _ = os.RemoveAll(UserPath(u.Name))
  766. _ = os.Remove(u.CustomAvatarPath())
  767. return nil
  768. }
  769. // DeleteUser completely and permanently deletes everything of a user,
  770. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  771. func DeleteUser(u *User) (err error) {
  772. sess := x.NewSession()
  773. defer sess.Close()
  774. if err = sess.Begin(); err != nil {
  775. return err
  776. }
  777. if err = deleteUser(sess, u); err != nil {
  778. // Note: don't wrapper error here.
  779. return err
  780. }
  781. if err = sess.Commit(); err != nil {
  782. return err
  783. }
  784. return RewriteAuthorizedKeys()
  785. }
  786. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  787. func DeleteInactivateUsers() (err error) {
  788. users := make([]*User, 0, 10)
  789. if err = x.Where("is_active = ?", false).Find(&users); err != nil {
  790. return fmt.Errorf("get all inactive users: %v", err)
  791. }
  792. // FIXME: should only update authorized_keys file once after all deletions.
  793. for _, u := range users {
  794. if err = DeleteUser(u); err != nil {
  795. // Ignore users that were set inactive by admin.
  796. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  797. continue
  798. }
  799. return err
  800. }
  801. }
  802. _, err = x.Where("is_activated = ?", false).Delete(new(EmailAddress))
  803. return err
  804. }
  805. // UserPath returns the path absolute path of user repositories.
  806. func UserPath(username string) string {
  807. return filepath.Join(conf.Repository.Root, strings.ToLower(username))
  808. }
  809. func GetUserByKeyID(keyID int64) (*User, error) {
  810. user := new(User)
  811. 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)
  812. if err != nil {
  813. return nil, err
  814. } else if !has {
  815. return nil, errors.UserNotKeyOwner{KeyID: keyID}
  816. }
  817. return user, nil
  818. }
  819. func getUserByID(e Engine, id int64) (*User, error) {
  820. u := new(User)
  821. has, err := e.ID(id).Get(u)
  822. if err != nil {
  823. return nil, err
  824. } else if !has {
  825. return nil, ErrUserNotExist{args: map[string]interface{}{"userID": id}}
  826. }
  827. return u, nil
  828. }
  829. // GetUserByID returns the user object by given ID if exists.
  830. // Deprecated: Use Users.GetByID instead.
  831. func GetUserByID(id int64) (*User, error) {
  832. return getUserByID(x, id)
  833. }
  834. // GetAssigneeByID returns the user with write access of repository by given ID.
  835. func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
  836. has, err := HasAccess(userID, repo, AccessModeRead)
  837. if err != nil {
  838. return nil, err
  839. } else if !has {
  840. return nil, ErrUserNotExist{args: map[string]interface{}{"userID": userID}}
  841. }
  842. return GetUserByID(userID)
  843. }
  844. // GetUserByName returns a user by given name.
  845. // Deprecated: Use Users.GetByUsername instead.
  846. func GetUserByName(name string) (*User, error) {
  847. if len(name) == 0 {
  848. return nil, ErrUserNotExist{args: map[string]interface{}{"name": name}}
  849. }
  850. u := &User{LowerName: strings.ToLower(name)}
  851. has, err := x.Get(u)
  852. if err != nil {
  853. return nil, err
  854. } else if !has {
  855. return nil, ErrUserNotExist{args: map[string]interface{}{"name": name}}
  856. }
  857. return u, nil
  858. }
  859. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  860. func GetUserEmailsByNames(names []string) []string {
  861. mails := make([]string, 0, len(names))
  862. for _, name := range names {
  863. u, err := GetUserByName(name)
  864. if err != nil {
  865. continue
  866. }
  867. if u.IsMailable() {
  868. mails = append(mails, u.Email)
  869. }
  870. }
  871. return mails
  872. }
  873. // GetUserIDsByNames returns a slice of ids corresponds to names.
  874. func GetUserIDsByNames(names []string) []int64 {
  875. ids := make([]int64, 0, len(names))
  876. for _, name := range names {
  877. u, err := GetUserByName(name)
  878. if err != nil {
  879. continue
  880. }
  881. ids = append(ids, u.ID)
  882. }
  883. return ids
  884. }
  885. // UserCommit represents a commit with validation of user.
  886. type UserCommit struct {
  887. User *User
  888. *git.Commit
  889. }
  890. // ValidateCommitWithEmail chceck if author's e-mail of commit is corresponsind to a user.
  891. func ValidateCommitWithEmail(c *git.Commit) *User {
  892. u, err := GetUserByEmail(c.Author.Email)
  893. if err != nil {
  894. return nil
  895. }
  896. return u
  897. }
  898. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  899. func ValidateCommitsWithEmails(oldCommits []*git.Commit) []*UserCommit {
  900. emails := make(map[string]*User)
  901. newCommits := make([]*UserCommit, len(oldCommits))
  902. for i := range oldCommits {
  903. var u *User
  904. if v, ok := emails[oldCommits[i].Author.Email]; !ok {
  905. u, _ = GetUserByEmail(oldCommits[i].Author.Email)
  906. emails[oldCommits[i].Author.Email] = u
  907. } else {
  908. u = v
  909. }
  910. newCommits[i] = &UserCommit{
  911. User: u,
  912. Commit: oldCommits[i],
  913. }
  914. }
  915. return newCommits
  916. }
  917. // GetUserByEmail returns the user object by given e-mail if exists.
  918. // Deprecated: Use Users.GetByEmail instead.
  919. func GetUserByEmail(email string) (*User, error) {
  920. if len(email) == 0 {
  921. return nil, ErrUserNotExist{args: map[string]interface{}{"email": email}}
  922. }
  923. email = strings.ToLower(email)
  924. // First try to find the user by primary email
  925. user := &User{Email: email}
  926. has, err := x.Get(user)
  927. if err != nil {
  928. return nil, err
  929. }
  930. if has {
  931. return user, nil
  932. }
  933. // Otherwise, check in alternative list for activated email addresses
  934. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  935. has, err = x.Get(emailAddress)
  936. if err != nil {
  937. return nil, err
  938. }
  939. if has {
  940. return GetUserByID(emailAddress.UID)
  941. }
  942. return nil, ErrUserNotExist{args: map[string]interface{}{"email": email}}
  943. }
  944. type SearchUserOptions struct {
  945. Keyword string
  946. Type UserType
  947. OrderBy string
  948. Page int
  949. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  950. }
  951. // SearchUserByName takes keyword and part of user name to search,
  952. // it returns results in given range and number of total results.
  953. func SearchUserByName(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  954. if len(opts.Keyword) == 0 {
  955. return users, 0, nil
  956. }
  957. opts.Keyword = strings.ToLower(opts.Keyword)
  958. if opts.PageSize <= 0 || opts.PageSize > conf.UI.ExplorePagingNum {
  959. opts.PageSize = conf.UI.ExplorePagingNum
  960. }
  961. if opts.Page <= 0 {
  962. opts.Page = 1
  963. }
  964. searchQuery := "%" + opts.Keyword + "%"
  965. users = make([]*User, 0, opts.PageSize)
  966. // Append conditions
  967. sess := x.Where("LOWER(lower_name) LIKE ?", searchQuery).
  968. Or("LOWER(full_name) LIKE ?", searchQuery).
  969. And("type = ?", opts.Type)
  970. countSess := *sess
  971. count, err := countSess.Count(new(User))
  972. if err != nil {
  973. return nil, 0, fmt.Errorf("Count: %v", err)
  974. }
  975. if len(opts.OrderBy) > 0 {
  976. sess.OrderBy(opts.OrderBy)
  977. }
  978. return users, count, sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).Find(&users)
  979. }
  980. // ___________ .__ .__
  981. // \_ _____/___ | | | | ______ _ __
  982. // | __)/ _ \| | | | / _ \ \/ \/ /
  983. // | \( <_> ) |_| |_( <_> ) /
  984. // \___ / \____/|____/____/\____/ \/\_/
  985. // \/
  986. // Follow represents relations of user and his/her followers.
  987. type Follow struct {
  988. ID int64
  989. UserID int64 `xorm:"UNIQUE(follow)"`
  990. FollowID int64 `xorm:"UNIQUE(follow)"`
  991. }
  992. func IsFollowing(userID, followID int64) bool {
  993. has, _ := x.Get(&Follow{UserID: userID, FollowID: followID})
  994. return has
  995. }
  996. // FollowUser marks someone be another's follower.
  997. func FollowUser(userID, followID int64) (err error) {
  998. if userID == followID || IsFollowing(userID, followID) {
  999. return nil
  1000. }
  1001. sess := x.NewSession()
  1002. defer sess.Close()
  1003. if err = sess.Begin(); err != nil {
  1004. return err
  1005. }
  1006. if _, err = sess.Insert(&Follow{UserID: userID, FollowID: followID}); err != nil {
  1007. return err
  1008. }
  1009. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?", followID); err != nil {
  1010. return err
  1011. }
  1012. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following + 1 WHERE id = ?", userID); err != nil {
  1013. return err
  1014. }
  1015. return sess.Commit()
  1016. }
  1017. // UnfollowUser unmarks someone be another's follower.
  1018. func UnfollowUser(userID, followID int64) (err error) {
  1019. if userID == followID || !IsFollowing(userID, followID) {
  1020. return nil
  1021. }
  1022. sess := x.NewSession()
  1023. defer sess.Close()
  1024. if err = sess.Begin(); err != nil {
  1025. return err
  1026. }
  1027. if _, err = sess.Delete(&Follow{UserID: userID, FollowID: followID}); err != nil {
  1028. return err
  1029. }
  1030. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?", followID); err != nil {
  1031. return err
  1032. }
  1033. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following - 1 WHERE id = ?", userID); err != nil {
  1034. return err
  1035. }
  1036. return sess.Commit()
  1037. }