You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

repo.go 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2017 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package context
  6. import (
  7. "fmt"
  8. "io/ioutil"
  9. "path"
  10. "strings"
  11. "code.gitea.io/git"
  12. "code.gitea.io/gitea/models"
  13. "code.gitea.io/gitea/modules/cache"
  14. "code.gitea.io/gitea/modules/setting"
  15. "github.com/Unknwon/com"
  16. "gopkg.in/editorconfig/editorconfig-core-go.v1"
  17. "gopkg.in/macaron.v1"
  18. )
  19. // PullRequest contains informations to make a pull request
  20. type PullRequest struct {
  21. BaseRepo *models.Repository
  22. Allowed bool
  23. SameRepo bool
  24. HeadInfo string // [<user>:]<branch>
  25. }
  26. // Repository contains information to operate a repository
  27. type Repository struct {
  28. AccessMode models.AccessMode
  29. IsWatching bool
  30. IsViewBranch bool
  31. IsViewTag bool
  32. IsViewCommit bool
  33. Repository *models.Repository
  34. Owner *models.User
  35. Commit *git.Commit
  36. Tag *git.Tag
  37. GitRepo *git.Repository
  38. BranchName string
  39. TagName string
  40. TreePath string
  41. CommitID string
  42. RepoLink string
  43. CloneLink models.CloneLink
  44. CommitsCount int64
  45. Mirror *models.Mirror
  46. PullRequest *PullRequest
  47. }
  48. // IsOwner returns true if current user is the owner of repository.
  49. func (r *Repository) IsOwner() bool {
  50. return r.AccessMode >= models.AccessModeOwner
  51. }
  52. // IsAdmin returns true if current user has admin or higher access of repository.
  53. func (r *Repository) IsAdmin() bool {
  54. return r.AccessMode >= models.AccessModeAdmin
  55. }
  56. // IsWriter returns true if current user has write or higher access of repository.
  57. func (r *Repository) IsWriter() bool {
  58. return r.AccessMode >= models.AccessModeWrite
  59. }
  60. // HasAccess returns true if the current user has at least read access for this repository
  61. func (r *Repository) HasAccess() bool {
  62. return r.AccessMode >= models.AccessModeRead
  63. }
  64. // CanEnableEditor returns true if repository is editable and user has proper access level.
  65. func (r *Repository) CanEnableEditor() bool {
  66. return r.Repository.CanEnableEditor() && r.IsViewBranch && r.IsWriter()
  67. }
  68. // CanCreateBranch returns true if repository is editable and user has proper access level.
  69. func (r *Repository) CanCreateBranch() bool {
  70. return r.Repository.CanCreateBranch() && r.IsWriter()
  71. }
  72. // CanCommitToBranch returns true if repository is editable and user has proper access level
  73. // and branch is not protected
  74. func (r *Repository) CanCommitToBranch(doer *models.User) (bool, error) {
  75. protectedBranch, err := r.Repository.IsProtectedBranch(r.BranchName, doer)
  76. if err != nil {
  77. return false, err
  78. }
  79. return r.CanEnableEditor() && !protectedBranch, nil
  80. }
  81. // CanUseTimetracker returns whether or not a user can use the timetracker.
  82. func (r *Repository) CanUseTimetracker(issue *models.Issue, user *models.User) bool {
  83. // Checking for following:
  84. // 1. Is timetracker enabled
  85. // 2. Is the user a contributor, admin, poster or assignee and do the repository policies require this?
  86. return r.Repository.IsTimetrackerEnabled() && (!r.Repository.AllowOnlyContributorsToTrackTime() ||
  87. r.IsWriter() || issue.IsPoster(user.ID) || issue.AssigneeID == user.ID)
  88. }
  89. // GetCommitsCount returns cached commit count for current view
  90. func (r *Repository) GetCommitsCount() (int64, error) {
  91. var contextName string
  92. if r.IsViewBranch {
  93. contextName = r.BranchName
  94. } else if r.IsViewTag {
  95. contextName = r.TagName
  96. } else {
  97. contextName = r.CommitID
  98. }
  99. return cache.GetInt64(r.Repository.GetCommitsCountCacheKey(contextName, r.IsViewBranch || r.IsViewTag), func() (int64, error) {
  100. return r.Commit.CommitsCount()
  101. })
  102. }
  103. // GetEditorconfig returns the .editorconfig definition if found in the
  104. // HEAD of the default repo branch.
  105. func (r *Repository) GetEditorconfig() (*editorconfig.Editorconfig, error) {
  106. commit, err := r.GitRepo.GetBranchCommit(r.Repository.DefaultBranch)
  107. if err != nil {
  108. return nil, err
  109. }
  110. treeEntry, err := commit.GetTreeEntryByPath(".editorconfig")
  111. if err != nil {
  112. return nil, err
  113. }
  114. reader, err := treeEntry.Blob().Data()
  115. if err != nil {
  116. return nil, err
  117. }
  118. data, err := ioutil.ReadAll(reader)
  119. if err != nil {
  120. return nil, err
  121. }
  122. return editorconfig.ParseBytes(data)
  123. }
  124. // RetrieveBaseRepo retrieves base repository
  125. func RetrieveBaseRepo(ctx *Context, repo *models.Repository) {
  126. // Non-fork repository will not return error in this method.
  127. if err := repo.GetBaseRepo(); err != nil {
  128. if models.IsErrRepoNotExist(err) {
  129. repo.IsFork = false
  130. repo.ForkID = 0
  131. return
  132. }
  133. ctx.Handle(500, "GetBaseRepo", err)
  134. return
  135. } else if err = repo.BaseRepo.GetOwner(); err != nil {
  136. ctx.Handle(500, "BaseRepo.GetOwner", err)
  137. return
  138. }
  139. }
  140. // ComposeGoGetImport returns go-get-import meta content.
  141. func ComposeGoGetImport(owner, repo string) string {
  142. return path.Join(setting.Domain, setting.AppSubURL, owner, repo)
  143. }
  144. // EarlyResponseForGoGetMeta responses appropriate go-get meta with status 200
  145. // if user does not have actual access to the requested repository,
  146. // or the owner or repository does not exist at all.
  147. // This is particular a workaround for "go get" command which does not respect
  148. // .netrc file.
  149. func EarlyResponseForGoGetMeta(ctx *Context) {
  150. username := ctx.Params(":username")
  151. reponame := ctx.Params(":reponame")
  152. ctx.PlainText(200, []byte(com.Expand(`<meta name="go-import" content="{GoGetImport} git {CloneLink}">`,
  153. map[string]string{
  154. "GoGetImport": ComposeGoGetImport(username, strings.TrimSuffix(reponame, ".git")),
  155. "CloneLink": models.ComposeHTTPSCloneURL(username, reponame),
  156. })))
  157. }
  158. // RedirectToRepo redirect to a differently-named repository
  159. func RedirectToRepo(ctx *Context, redirectRepoID int64) {
  160. ownerName := ctx.Params(":username")
  161. previousRepoName := ctx.Params(":reponame")
  162. repo, err := models.GetRepositoryByID(redirectRepoID)
  163. if err != nil {
  164. ctx.Handle(500, "GetRepositoryByID", err)
  165. return
  166. }
  167. redirectPath := strings.Replace(
  168. ctx.Req.URL.Path,
  169. fmt.Sprintf("%s/%s", ownerName, previousRepoName),
  170. fmt.Sprintf("%s/%s", ownerName, repo.Name),
  171. 1,
  172. )
  173. ctx.Redirect(redirectPath)
  174. }
  175. func repoAssignment(ctx *Context, repo *models.Repository) {
  176. // Admin has super access.
  177. if ctx.IsSigned && ctx.User.IsAdmin {
  178. ctx.Repo.AccessMode = models.AccessModeOwner
  179. } else {
  180. var userID int64
  181. if ctx.User != nil {
  182. userID = ctx.User.ID
  183. }
  184. mode, err := models.AccessLevel(userID, repo)
  185. if err != nil {
  186. ctx.Handle(500, "AccessLevel", err)
  187. return
  188. }
  189. ctx.Repo.AccessMode = mode
  190. }
  191. // Check access.
  192. if ctx.Repo.AccessMode == models.AccessModeNone {
  193. if ctx.Query("go-get") == "1" {
  194. EarlyResponseForGoGetMeta(ctx)
  195. return
  196. }
  197. ctx.Handle(404, "no access right", nil)
  198. return
  199. }
  200. ctx.Data["HasAccess"] = true
  201. if repo.IsMirror {
  202. var err error
  203. ctx.Repo.Mirror, err = models.GetMirrorByRepoID(repo.ID)
  204. if err != nil {
  205. ctx.Handle(500, "GetMirror", err)
  206. return
  207. }
  208. ctx.Data["MirrorEnablePrune"] = ctx.Repo.Mirror.EnablePrune
  209. ctx.Data["MirrorInterval"] = ctx.Repo.Mirror.Interval
  210. ctx.Data["Mirror"] = ctx.Repo.Mirror
  211. }
  212. ctx.Repo.Repository = repo
  213. ctx.Data["RepoName"] = ctx.Repo.Repository.Name
  214. ctx.Data["IsBareRepo"] = ctx.Repo.Repository.IsBare
  215. }
  216. // RepoIDAssignment returns a macaron handler which assigns the repo to the context.
  217. func RepoIDAssignment() macaron.Handler {
  218. return func(ctx *Context) {
  219. repoID := ctx.ParamsInt64(":repoid")
  220. // Get repository.
  221. repo, err := models.GetRepositoryByID(repoID)
  222. if err != nil {
  223. if models.IsErrRepoNotExist(err) {
  224. ctx.Handle(404, "GetRepositoryByID", nil)
  225. } else {
  226. ctx.Handle(500, "GetRepositoryByID", err)
  227. }
  228. return
  229. }
  230. if err = repo.GetOwner(); err != nil {
  231. ctx.Handle(500, "GetOwner", err)
  232. return
  233. }
  234. repoAssignment(ctx, repo)
  235. }
  236. }
  237. // RepoAssignment returns a macaron to handle repository assignment
  238. func RepoAssignment() macaron.Handler {
  239. return func(ctx *Context) {
  240. var (
  241. owner *models.User
  242. err error
  243. )
  244. userName := ctx.Params(":username")
  245. repoName := ctx.Params(":reponame")
  246. // Check if the user is the same as the repository owner
  247. if ctx.IsSigned && ctx.User.LowerName == strings.ToLower(userName) {
  248. owner = ctx.User
  249. } else {
  250. owner, err = models.GetUserByName(userName)
  251. if err != nil {
  252. if models.IsErrUserNotExist(err) {
  253. if ctx.Query("go-get") == "1" {
  254. EarlyResponseForGoGetMeta(ctx)
  255. return
  256. }
  257. ctx.Handle(404, "GetUserByName", nil)
  258. } else {
  259. ctx.Handle(500, "GetUserByName", err)
  260. }
  261. return
  262. }
  263. }
  264. ctx.Repo.Owner = owner
  265. ctx.Data["Username"] = ctx.Repo.Owner.Name
  266. // Get repository.
  267. repo, err := models.GetRepositoryByName(owner.ID, repoName)
  268. if err != nil {
  269. if models.IsErrRepoNotExist(err) {
  270. redirectRepoID, err := models.LookupRepoRedirect(owner.ID, repoName)
  271. if err == nil {
  272. RedirectToRepo(ctx, redirectRepoID)
  273. } else if models.IsErrRepoRedirectNotExist(err) {
  274. if ctx.Query("go-get") == "1" {
  275. EarlyResponseForGoGetMeta(ctx)
  276. return
  277. }
  278. ctx.Handle(404, "GetRepositoryByName", nil)
  279. } else {
  280. ctx.Handle(500, "LookupRepoRedirect", err)
  281. }
  282. } else {
  283. ctx.Handle(500, "GetRepositoryByName", err)
  284. }
  285. return
  286. }
  287. repo.Owner = owner
  288. repoAssignment(ctx, repo)
  289. if ctx.Written() {
  290. return
  291. }
  292. gitRepo, err := git.OpenRepository(models.RepoPath(userName, repoName))
  293. if err != nil {
  294. ctx.Handle(500, "RepoAssignment Invalid repo "+models.RepoPath(userName, repoName), err)
  295. return
  296. }
  297. ctx.Repo.GitRepo = gitRepo
  298. ctx.Repo.RepoLink = repo.Link()
  299. ctx.Data["RepoLink"] = ctx.Repo.RepoLink
  300. ctx.Data["RepoRelPath"] = ctx.Repo.Owner.Name + "/" + ctx.Repo.Repository.Name
  301. tags, err := ctx.Repo.GitRepo.GetTags()
  302. if err != nil {
  303. ctx.Handle(500, "GetTags", err)
  304. return
  305. }
  306. ctx.Data["Tags"] = tags
  307. count, err := models.GetReleaseCountByRepoID(ctx.Repo.Repository.ID, models.FindReleasesOptions{
  308. IncludeDrafts: false,
  309. IncludeTags: true,
  310. })
  311. if err != nil {
  312. ctx.Handle(500, "GetReleaseCountByRepoID", err)
  313. return
  314. }
  315. ctx.Repo.Repository.NumReleases = int(count)
  316. ctx.Data["Title"] = owner.Name + "/" + repo.Name
  317. ctx.Data["Repository"] = repo
  318. ctx.Data["Owner"] = ctx.Repo.Repository.Owner
  319. ctx.Data["IsRepositoryOwner"] = ctx.Repo.IsOwner()
  320. ctx.Data["IsRepositoryAdmin"] = ctx.Repo.IsAdmin()
  321. ctx.Data["IsRepositoryWriter"] = ctx.Repo.IsWriter()
  322. if ctx.Data["CanSignedUserFork"], err = ctx.Repo.Repository.CanUserFork(ctx.User); err != nil {
  323. ctx.Handle(500, "CanUserFork", err)
  324. return
  325. }
  326. ctx.Data["DisableSSH"] = setting.SSH.Disabled
  327. ctx.Data["ExposeAnonSSH"] = setting.SSH.ExposeAnonymous
  328. ctx.Data["DisableHTTP"] = setting.Repository.DisableHTTPGit
  329. ctx.Data["CloneLink"] = repo.CloneLink()
  330. ctx.Data["WikiCloneLink"] = repo.WikiCloneLink()
  331. if ctx.IsSigned {
  332. ctx.Data["IsWatchingRepo"] = models.IsWatching(ctx.User.ID, repo.ID)
  333. ctx.Data["IsStaringRepo"] = models.IsStaring(ctx.User.ID, repo.ID)
  334. }
  335. // repo is bare and display enable
  336. if ctx.Repo.Repository.IsBare {
  337. ctx.Data["BranchName"] = ctx.Repo.Repository.DefaultBranch
  338. return
  339. }
  340. ctx.Data["TagName"] = ctx.Repo.TagName
  341. brs, err := ctx.Repo.GitRepo.GetBranches()
  342. if err != nil {
  343. ctx.Handle(500, "GetBranches", err)
  344. return
  345. }
  346. ctx.Data["Branches"] = brs
  347. ctx.Data["BrancheCount"] = len(brs)
  348. // If not branch selected, try default one.
  349. // If default branch doesn't exists, fall back to some other branch.
  350. if len(ctx.Repo.BranchName) == 0 {
  351. if len(ctx.Repo.Repository.DefaultBranch) > 0 && gitRepo.IsBranchExist(ctx.Repo.Repository.DefaultBranch) {
  352. ctx.Repo.BranchName = ctx.Repo.Repository.DefaultBranch
  353. } else if len(brs) > 0 {
  354. ctx.Repo.BranchName = brs[0]
  355. }
  356. }
  357. ctx.Data["BranchName"] = ctx.Repo.BranchName
  358. ctx.Data["CommitID"] = ctx.Repo.CommitID
  359. if repo.IsFork {
  360. RetrieveBaseRepo(ctx, repo)
  361. if ctx.Written() {
  362. return
  363. }
  364. }
  365. // People who have push access or have forked repository can propose a new pull request.
  366. if ctx.Repo.IsWriter() || (ctx.IsSigned && ctx.User.HasForkedRepo(ctx.Repo.Repository.ID)) {
  367. // Pull request is allowed if this is a fork repository
  368. // and base repository accepts pull requests.
  369. if repo.BaseRepo != nil && repo.BaseRepo.AllowsPulls() {
  370. ctx.Data["BaseRepo"] = repo.BaseRepo
  371. ctx.Repo.PullRequest.BaseRepo = repo.BaseRepo
  372. ctx.Repo.PullRequest.Allowed = true
  373. ctx.Repo.PullRequest.HeadInfo = ctx.Repo.Owner.Name + ":" + ctx.Repo.BranchName
  374. } else {
  375. // Or, this is repository accepts pull requests between branches.
  376. if repo.AllowsPulls() {
  377. ctx.Data["BaseRepo"] = repo
  378. ctx.Repo.PullRequest.BaseRepo = repo
  379. ctx.Repo.PullRequest.Allowed = true
  380. ctx.Repo.PullRequest.SameRepo = true
  381. ctx.Repo.PullRequest.HeadInfo = ctx.Repo.BranchName
  382. }
  383. }
  384. // Reset repo units as otherwise user specific units wont be loaded later
  385. ctx.Repo.Repository.Units = nil
  386. }
  387. ctx.Data["PullRequestCtx"] = ctx.Repo.PullRequest
  388. if ctx.Query("go-get") == "1" {
  389. ctx.Data["GoGetImport"] = ComposeGoGetImport(owner.Name, repo.Name)
  390. prefix := setting.AppURL + path.Join(owner.Name, repo.Name, "src", ctx.Repo.BranchName)
  391. ctx.Data["GoDocDirectory"] = prefix + "{/dir}"
  392. ctx.Data["GoDocFile"] = prefix + "{/dir}/{file}#L{line}"
  393. }
  394. }
  395. }
  396. // RepoRef handles repository reference name including those contain `/`.
  397. func RepoRef() macaron.Handler {
  398. return func(ctx *Context) {
  399. // Empty repository does not have reference information.
  400. if ctx.Repo.Repository.IsBare {
  401. return
  402. }
  403. var (
  404. refName string
  405. err error
  406. )
  407. // For API calls.
  408. if ctx.Repo.GitRepo == nil {
  409. repoPath := models.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
  410. ctx.Repo.GitRepo, err = git.OpenRepository(repoPath)
  411. if err != nil {
  412. ctx.Handle(500, "RepoRef Invalid repo "+repoPath, err)
  413. return
  414. }
  415. }
  416. // Get default branch.
  417. if len(ctx.Params("*")) == 0 {
  418. refName = ctx.Repo.Repository.DefaultBranch
  419. if !ctx.Repo.GitRepo.IsBranchExist(refName) {
  420. brs, err := ctx.Repo.GitRepo.GetBranches()
  421. if err != nil {
  422. ctx.Handle(500, "GetBranches", err)
  423. return
  424. } else if len(brs) == 0 {
  425. err = fmt.Errorf("No branches in non-bare repository %s",
  426. ctx.Repo.GitRepo.Path)
  427. ctx.Handle(500, "GetBranches", err)
  428. return
  429. }
  430. refName = brs[0]
  431. }
  432. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName)
  433. if err != nil {
  434. ctx.Handle(500, "GetBranchCommit", err)
  435. return
  436. }
  437. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  438. ctx.Repo.IsViewBranch = true
  439. } else {
  440. hasMatched := false
  441. parts := strings.Split(ctx.Params("*"), "/")
  442. for i, part := range parts {
  443. refName = strings.TrimPrefix(refName+"/"+part, "/")
  444. if ctx.Repo.GitRepo.IsBranchExist(refName) ||
  445. ctx.Repo.GitRepo.IsTagExist(refName) {
  446. if i < len(parts)-1 {
  447. ctx.Repo.TreePath = strings.Join(parts[i+1:], "/")
  448. }
  449. hasMatched = true
  450. break
  451. }
  452. }
  453. if !hasMatched && len(parts[0]) == 40 {
  454. refName = parts[0]
  455. ctx.Repo.TreePath = strings.Join(parts[1:], "/")
  456. }
  457. if ctx.Repo.GitRepo.IsBranchExist(refName) {
  458. ctx.Repo.IsViewBranch = true
  459. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName)
  460. if err != nil {
  461. ctx.Handle(500, "GetBranchCommit", err)
  462. return
  463. }
  464. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  465. } else if ctx.Repo.GitRepo.IsTagExist(refName) {
  466. ctx.Repo.IsViewTag = true
  467. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetTagCommit(refName)
  468. if err != nil {
  469. ctx.Handle(500, "GetTagCommit", err)
  470. return
  471. }
  472. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  473. } else if len(refName) == 40 {
  474. ctx.Repo.IsViewCommit = true
  475. ctx.Repo.CommitID = refName
  476. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetCommit(refName)
  477. if err != nil {
  478. ctx.Handle(404, "GetCommit", nil)
  479. return
  480. }
  481. } else {
  482. ctx.Handle(404, "RepoRef invalid repo", fmt.Errorf("branch or tag not exist: %s", refName))
  483. return
  484. }
  485. }
  486. ctx.Repo.BranchName = refName
  487. ctx.Data["BranchName"] = ctx.Repo.BranchName
  488. ctx.Data["CommitID"] = ctx.Repo.CommitID
  489. ctx.Data["TreePath"] = ctx.Repo.TreePath
  490. ctx.Data["IsViewBranch"] = ctx.Repo.IsViewBranch
  491. ctx.Data["IsViewTag"] = ctx.Repo.IsViewTag
  492. ctx.Data["IsViewCommit"] = ctx.Repo.IsViewCommit
  493. ctx.Data["CanCreateBranch"] = ctx.Repo.CanCreateBranch()
  494. ctx.Repo.CommitsCount, err = ctx.Repo.GetCommitsCount()
  495. if err != nil {
  496. ctx.Handle(500, "GetCommitsCount", err)
  497. return
  498. }
  499. ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
  500. }
  501. }
  502. // RequireRepoAdmin returns a macaron middleware for requiring repository admin permission
  503. func RequireRepoAdmin() macaron.Handler {
  504. return func(ctx *Context) {
  505. if !ctx.IsSigned || (!ctx.Repo.IsAdmin() && !ctx.User.IsAdmin) {
  506. ctx.Handle(404, ctx.Req.RequestURI, nil)
  507. return
  508. }
  509. }
  510. }
  511. // RequireRepoWriter returns a macaron middleware for requiring repository write permission
  512. func RequireRepoWriter() macaron.Handler {
  513. return func(ctx *Context) {
  514. if !ctx.IsSigned || (!ctx.Repo.IsWriter() && !ctx.User.IsAdmin) {
  515. ctx.Handle(404, ctx.Req.RequestURI, nil)
  516. return
  517. }
  518. }
  519. }
  520. // LoadRepoUnits loads repsitory's units, it should be called after repository and user loaded
  521. func LoadRepoUnits() macaron.Handler {
  522. return func(ctx *Context) {
  523. var isAdmin bool
  524. if ctx.User != nil && ctx.User.IsAdmin {
  525. isAdmin = true
  526. }
  527. var userID int64
  528. if ctx.User != nil {
  529. userID = ctx.User.ID
  530. }
  531. err := ctx.Repo.Repository.LoadUnitsByUserID(userID, isAdmin)
  532. if err != nil {
  533. ctx.Handle(500, "LoadUnitsByUserID", err)
  534. return
  535. }
  536. }
  537. }
  538. // CheckUnit will check whether unit type is enabled
  539. func CheckUnit(unitType models.UnitType) macaron.Handler {
  540. return func(ctx *Context) {
  541. if !ctx.Repo.Repository.UnitEnabled(unitType) {
  542. ctx.Handle(404, "CheckUnit", fmt.Errorf("%s: %v", ctx.Tr("units.error.unit_not_allowed"), unitType))
  543. }
  544. }
  545. }
  546. // CheckAnyUnit will check whether any of the unit types are enabled
  547. func CheckAnyUnit(unitTypes ...models.UnitType) macaron.Handler {
  548. return func(ctx *Context) {
  549. if !ctx.Repo.Repository.AnyUnitEnabled(unitTypes...) {
  550. ctx.Handle(404, "CheckAnyUnit", fmt.Errorf("%s: %v", ctx.Tr("units.error.unit_not_allowed"), unitTypes))
  551. }
  552. }
  553. }
  554. // GitHookService checks if repository Git hooks service has been enabled.
  555. func GitHookService() macaron.Handler {
  556. return func(ctx *Context) {
  557. if !ctx.User.CanEditGitHook() {
  558. ctx.Handle(404, "GitHookService", nil)
  559. return
  560. }
  561. }
  562. }
  563. // UnitTypes returns a macaron middleware to set unit types to context variables.
  564. func UnitTypes() macaron.Handler {
  565. return func(ctx *Context) {
  566. ctx.Data["UnitTypeCode"] = models.UnitTypeCode
  567. ctx.Data["UnitTypeIssues"] = models.UnitTypeIssues
  568. ctx.Data["UnitTypePullRequests"] = models.UnitTypePullRequests
  569. ctx.Data["UnitTypeReleases"] = models.UnitTypeReleases
  570. ctx.Data["UnitTypeWiki"] = models.UnitTypeWiki
  571. ctx.Data["UnitTypeExternalWiki"] = models.UnitTypeExternalWiki
  572. ctx.Data["UnitTypeExternalTracker"] = models.UnitTypeExternalTracker
  573. }
  574. }