summaryrefslogtreecommitdiffstats
path: root/modules/middleware
diff options
context:
space:
mode:
authorUnknwon <u@gogs.io>2016-03-11 11:56:52 -0500
committerUnknwon <u@gogs.io>2016-03-11 11:56:52 -0500
commit514382e2ebfe6869268aeb919c1fa4d224687e13 (patch)
tree1aa8c4b3b1e771a5dc6f0bdd74567961570efcaa /modules/middleware
parentcb1eadc2768ea5ffb2967eb4262e96730c3f9ba5 (diff)
downloadgitea-514382e2ebfe6869268aeb919c1fa4d224687e13.tar.gz
gitea-514382e2ebfe6869268aeb919c1fa4d224687e13.zip
Rename module: middleware -> context
Diffstat (limited to 'modules/middleware')
-rw-r--r--modules/middleware/auth.go128
-rw-r--r--modules/middleware/context.go266
-rw-r--r--modules/middleware/org.go141
-rw-r--r--modules/middleware/repo.go368
4 files changed, 0 insertions, 903 deletions
diff --git a/modules/middleware/auth.go b/modules/middleware/auth.go
deleted file mode 100644
index 4e549a0782..0000000000
--- a/modules/middleware/auth.go
+++ /dev/null
@@ -1,128 +0,0 @@
-// Copyright 2014 The Gogs Authors. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package middleware
-
-import (
- "fmt"
- "net/url"
-
- "github.com/go-macaron/csrf"
- "gopkg.in/macaron.v1"
-
- "github.com/gogits/gogs/models"
- "github.com/gogits/gogs/modules/auth"
- "github.com/gogits/gogs/modules/base"
- "github.com/gogits/gogs/modules/log"
- "github.com/gogits/gogs/modules/setting"
-)
-
-type ToggleOptions struct {
- SignInRequire bool
- SignOutRequire bool
- AdminRequire bool
- DisableCsrf bool
-}
-
-// AutoSignIn reads cookie and try to auto-login.
-func AutoSignIn(ctx *Context) (bool, error) {
- if !models.HasEngine {
- return false, nil
- }
-
- uname := ctx.GetCookie(setting.CookieUserName)
- if len(uname) == 0 {
- return false, nil
- }
-
- isSucceed := false
- defer func() {
- if !isSucceed {
- log.Trace("auto-login cookie cleared: %s", uname)
- ctx.SetCookie(setting.CookieUserName, "", -1, setting.AppSubUrl)
- ctx.SetCookie(setting.CookieRememberName, "", -1, setting.AppSubUrl)
- }
- }()
-
- u, err := models.GetUserByName(uname)
- if err != nil {
- if !models.IsErrUserNotExist(err) {
- return false, fmt.Errorf("GetUserByName: %v", err)
- }
- return false, nil
- }
-
- if val, _ := ctx.GetSuperSecureCookie(
- base.EncodeMD5(u.Rands+u.Passwd), setting.CookieRememberName); val != u.Name {
- return false, nil
- }
-
- isSucceed = true
- ctx.Session.Set("uid", u.Id)
- ctx.Session.Set("uname", u.Name)
- return true, nil
-}
-
-func Toggle(options *ToggleOptions) macaron.Handler {
- return func(ctx *Context) {
- // Cannot view any page before installation.
- if !setting.InstallLock {
- ctx.Redirect(setting.AppSubUrl + "/install")
- return
- }
-
- // Checking non-logged users landing page.
- if !ctx.IsSigned && ctx.Req.RequestURI == "/" && setting.LandingPageUrl != setting.LANDING_PAGE_HOME {
- ctx.Redirect(setting.AppSubUrl + string(setting.LandingPageUrl))
- return
- }
-
- // Redirect to dashboard if user tries to visit any non-login page.
- if options.SignOutRequire && ctx.IsSigned && ctx.Req.RequestURI != "/" {
- ctx.Redirect(setting.AppSubUrl + "/")
- return
- }
-
- if !options.SignOutRequire && !options.DisableCsrf && ctx.Req.Method == "POST" && !auth.IsAPIPath(ctx.Req.URL.Path) {
- csrf.Validate(ctx.Context, ctx.csrf)
- if ctx.Written() {
- return
- }
- }
-
- if options.SignInRequire {
- if !ctx.IsSigned {
- // Restrict API calls with error message.
- if auth.IsAPIPath(ctx.Req.URL.Path) {
- ctx.APIError(403, "", "Only signed in user is allowed to call APIs.")
- return
- }
-
- ctx.SetCookie("redirect_to", url.QueryEscape(setting.AppSubUrl+ctx.Req.RequestURI), 0, setting.AppSubUrl)
- ctx.Redirect(setting.AppSubUrl + "/user/login")
- return
- } else if !ctx.User.IsActive && setting.Service.RegisterEmailConfirm {
- ctx.Data["Title"] = ctx.Tr("auth.active_your_account")
- ctx.HTML(200, "user/auth/activate")
- return
- }
- }
-
- // Auto-signin info is provided and has not signed in.
- if !options.SignOutRequire && !ctx.IsSigned && !auth.IsAPIPath(ctx.Req.URL.Path) &&
- len(ctx.GetCookie(setting.CookieUserName)) > 0 {
- ctx.SetCookie("redirect_to", url.QueryEscape(setting.AppSubUrl+ctx.Req.RequestURI), 0, setting.AppSubUrl)
- ctx.Redirect(setting.AppSubUrl + "/user/login")
- return
- }
-
- if options.AdminRequire {
- if !ctx.User.IsAdmin {
- ctx.Error(403)
- return
- }
- ctx.Data["PageIsAdmin"] = true
- }
- }
-}
diff --git a/modules/middleware/context.go b/modules/middleware/context.go
deleted file mode 100644
index d2b7de4a27..0000000000
--- a/modules/middleware/context.go
+++ /dev/null
@@ -1,266 +0,0 @@
-// Copyright 2014 The Gogs Authors. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package middleware
-
-import (
- "fmt"
- "html/template"
- "io"
- "net/http"
- "strings"
- "time"
-
- "github.com/go-macaron/cache"
- "github.com/go-macaron/csrf"
- "github.com/go-macaron/i18n"
- "github.com/go-macaron/session"
- "gopkg.in/macaron.v1"
-
- "github.com/gogits/git-module"
-
- "github.com/gogits/gogs/models"
- "github.com/gogits/gogs/modules/auth"
- "github.com/gogits/gogs/modules/base"
- "github.com/gogits/gogs/modules/log"
- "github.com/gogits/gogs/modules/setting"
-)
-
-type PullRequestContext struct {
- BaseRepo *models.Repository
- Allowed bool
- SameRepo bool
- HeadInfo string // [<user>:]<branch>
-}
-
-type RepoContext struct {
- AccessMode models.AccessMode
- IsWatching bool
- IsViewBranch bool
- IsViewTag bool
- IsViewCommit bool
- Repository *models.Repository
- Owner *models.User
- Commit *git.Commit
- Tag *git.Tag
- GitRepo *git.Repository
- BranchName string
- TagName string
- TreeName string
- CommitID string
- RepoLink string
- CloneLink models.CloneLink
- CommitsCount int64
- Mirror *models.Mirror
-
- PullRequest *PullRequestContext
-}
-
-// Context represents context of a request.
-type Context struct {
- *macaron.Context
- Cache cache.Cache
- csrf csrf.CSRF
- Flash *session.Flash
- Session session.Store
-
- User *models.User
- IsSigned bool
- IsBasicAuth bool
-
- Repo *RepoContext
-
- Org struct {
- IsOwner bool
- IsMember bool
- IsTeamMember bool // Is member of team.
- IsTeamAdmin bool // In owner team or team that has admin permission level.
- Organization *models.User
- OrgLink string
-
- Team *models.Team
- }
-}
-
-// IsOwner returns true if current user is the owner of repository.
-func (r *RepoContext) IsOwner() bool {
- return r.AccessMode >= models.ACCESS_MODE_OWNER
-}
-
-// IsAdmin returns true if current user has admin or higher access of repository.
-func (r *RepoContext) IsAdmin() bool {
- return r.AccessMode >= models.ACCESS_MODE_ADMIN
-}
-
-// IsWriter returns true if current user has write or higher access of repository.
-func (r *RepoContext) IsWriter() bool {
- return r.AccessMode >= models.ACCESS_MODE_WRITE
-}
-
-// HasAccess returns true if the current user has at least read access for this repository
-func (r *RepoContext) HasAccess() bool {
- return r.AccessMode >= models.ACCESS_MODE_READ
-}
-
-// HasError returns true if error occurs in form validation.
-func (ctx *Context) HasApiError() bool {
- hasErr, ok := ctx.Data["HasError"]
- if !ok {
- return false
- }
- return hasErr.(bool)
-}
-
-func (ctx *Context) GetErrMsg() string {
- return ctx.Data["ErrorMsg"].(string)
-}
-
-// HasError returns true if error occurs in form validation.
-func (ctx *Context) HasError() bool {
- hasErr, ok := ctx.Data["HasError"]
- if !ok {
- return false
- }
- ctx.Flash.ErrorMsg = ctx.Data["ErrorMsg"].(string)
- ctx.Data["Flash"] = ctx.Flash
- return hasErr.(bool)
-}
-
-// HasValue returns true if value of given name exists.
-func (ctx *Context) HasValue(name string) bool {
- _, ok := ctx.Data[name]
- return ok
-}
-
-// HTML calls Context.HTML and converts template name to string.
-func (ctx *Context) HTML(status int, name base.TplName) {
- log.Debug("Template: %s", name)
- ctx.Context.HTML(status, string(name))
-}
-
-// RenderWithErr used for page has form validation but need to prompt error to users.
-func (ctx *Context) RenderWithErr(msg string, tpl base.TplName, form interface{}) {
- if form != nil {
- auth.AssignForm(form, ctx.Data)
- }
- ctx.Flash.ErrorMsg = msg
- ctx.Data["Flash"] = ctx.Flash
- ctx.HTML(200, tpl)
-}
-
-// Handle handles and logs error by given status.
-func (ctx *Context) Handle(status int, title string, err error) {
- if err != nil {
- log.Error(4, "%s: %v", title, err)
- if macaron.Env != macaron.PROD {
- ctx.Data["ErrorMsg"] = err
- }
- }
-
- switch status {
- case 404:
- ctx.Data["Title"] = "Page Not Found"
- case 500:
- ctx.Data["Title"] = "Internal Server Error"
- }
- ctx.HTML(status, base.TplName(fmt.Sprintf("status/%d", status)))
-}
-
-func (ctx *Context) HandleText(status int, title string) {
- if (status/100 == 4) || (status/100 == 5) {
- log.Error(4, "%s", title)
- }
- ctx.PlainText(status, []byte(title))
-}
-
-// APIError logs error with title if status is 500.
-func (ctx *Context) APIError(status int, title string, obj interface{}) {
- var message string
- if err, ok := obj.(error); ok {
- message = err.Error()
- } else {
- message = obj.(string)
- }
-
- if status == 500 {
- log.Error(4, "%s: %s", title, message)
- }
-
- ctx.JSON(status, map[string]string{
- "message": message,
- "url": base.DOC_URL,
- })
-}
-
-func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{}) {
- modtime := time.Now()
- for _, p := range params {
- switch v := p.(type) {
- case time.Time:
- modtime = v
- }
- }
- ctx.Resp.Header().Set("Content-Description", "File Transfer")
- ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
- ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+name)
- ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary")
- ctx.Resp.Header().Set("Expires", "0")
- ctx.Resp.Header().Set("Cache-Control", "must-revalidate")
- ctx.Resp.Header().Set("Pragma", "public")
- http.ServeContent(ctx.Resp, ctx.Req.Request, name, modtime, r)
-}
-
-// Contexter initializes a classic context for a request.
-func Contexter() macaron.Handler {
- return func(c *macaron.Context, l i18n.Locale, cache cache.Cache, sess session.Store, f *session.Flash, x csrf.CSRF) {
- ctx := &Context{
- Context: c,
- Cache: cache,
- csrf: x,
- Flash: f,
- Session: sess,
- Repo: &RepoContext{
- PullRequest: &PullRequestContext{},
- },
- }
- // Compute current URL for real-time change language.
- ctx.Data["Link"] = setting.AppSubUrl + strings.TrimSuffix(ctx.Req.URL.Path, "/")
-
- ctx.Data["PageStartTime"] = time.Now()
-
- // Get user from session if logined.
- ctx.User, ctx.IsBasicAuth = auth.SignedInUser(ctx.Context, ctx.Session)
-
- if ctx.User != nil {
- ctx.IsSigned = true
- ctx.Data["IsSigned"] = ctx.IsSigned
- ctx.Data["SignedUser"] = ctx.User
- ctx.Data["SignedUserID"] = ctx.User.Id
- ctx.Data["SignedUserName"] = ctx.User.Name
- ctx.Data["IsAdmin"] = ctx.User.IsAdmin
- } else {
- ctx.Data["SignedUserID"] = 0
- ctx.Data["SignedUserName"] = ""
- }
-
- // If request sends files, parse them here otherwise the Query() can't be parsed and the CsrfToken will be invalid.
- if ctx.Req.Method == "POST" && strings.Contains(ctx.Req.Header.Get("Content-Type"), "multipart/form-data") {
- if err := ctx.Req.ParseMultipartForm(setting.AttachmentMaxSize << 20); err != nil && !strings.Contains(err.Error(), "EOF") { // 32MB max size
- ctx.Handle(500, "ParseMultipartForm", err)
- return
- }
- }
-
- ctx.Data["CsrfToken"] = x.GetToken()
- ctx.Data["CsrfTokenHtml"] = template.HTML(`<input type="hidden" name="_csrf" value="` + x.GetToken() + `">`)
- log.Debug("Session ID: %s", sess.ID())
- log.Debug("CSRF Token: %v", ctx.Data["CsrfToken"])
-
- ctx.Data["ShowRegistrationButton"] = setting.Service.ShowRegistrationButton
- ctx.Data["ShowFooterBranding"] = setting.ShowFooterBranding
- ctx.Data["ShowFooterVersion"] = setting.ShowFooterVersion
-
- c.Map(ctx)
- }
-}
diff --git a/modules/middleware/org.go b/modules/middleware/org.go
deleted file mode 100644
index eec2b556fd..0000000000
--- a/modules/middleware/org.go
+++ /dev/null
@@ -1,141 +0,0 @@
-// Copyright 2014 The Gogs Authors. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package middleware
-
-import (
- "strings"
-
- "gopkg.in/macaron.v1"
-
- "github.com/gogits/gogs/models"
- "github.com/gogits/gogs/modules/setting"
-)
-
-func HandleOrgAssignment(ctx *Context, args ...bool) {
- var (
- requireMember bool
- requireOwner bool
- requireTeamMember bool
- requireTeamAdmin bool
- )
- if len(args) >= 1 {
- requireMember = args[0]
- }
- if len(args) >= 2 {
- requireOwner = args[1]
- }
- if len(args) >= 3 {
- requireTeamMember = args[2]
- }
- if len(args) >= 4 {
- requireTeamAdmin = args[3]
- }
-
- orgName := ctx.Params(":org")
-
- var err error
- ctx.Org.Organization, err = models.GetUserByName(orgName)
- if err != nil {
- if models.IsErrUserNotExist(err) {
- ctx.Handle(404, "GetUserByName", err)
- } else {
- ctx.Handle(500, "GetUserByName", err)
- }
- return
- }
- org := ctx.Org.Organization
- ctx.Data["Org"] = org
-
- // Force redirection when username is actually a user.
- if !org.IsOrganization() {
- ctx.Redirect("/" + org.Name)
- return
- }
-
- // Admin has super access.
- if ctx.IsSigned && ctx.User.IsAdmin {
- ctx.Org.IsOwner = true
- ctx.Org.IsMember = true
- ctx.Org.IsTeamMember = true
- ctx.Org.IsTeamAdmin = true
- } else if ctx.IsSigned {
- ctx.Org.IsOwner = org.IsOwnedBy(ctx.User.Id)
- if ctx.Org.IsOwner {
- ctx.Org.IsMember = true
- ctx.Org.IsTeamMember = true
- ctx.Org.IsTeamAdmin = true
- } else {
- if org.IsOrgMember(ctx.User.Id) {
- ctx.Org.IsMember = true
- }
- }
- } else {
- // Fake data.
- ctx.Data["SignedUser"] = &models.User{}
- }
- if (requireMember && !ctx.Org.IsMember) ||
- (requireOwner && !ctx.Org.IsOwner) {
- ctx.Handle(404, "OrgAssignment", err)
- return
- }
- ctx.Data["IsOrganizationOwner"] = ctx.Org.IsOwner
- ctx.Data["IsOrganizationMember"] = ctx.Org.IsMember
-
- ctx.Org.OrgLink = setting.AppSubUrl + "/org/" + org.Name
- ctx.Data["OrgLink"] = ctx.Org.OrgLink
-
- // Team.
- if ctx.Org.IsMember {
- if ctx.Org.IsOwner {
- if err := org.GetTeams(); err != nil {
- ctx.Handle(500, "GetTeams", err)
- return
- }
- } else {
- if err := org.GetUserTeams(ctx.User.Id); err != nil {
- ctx.Handle(500, "GetUserTeams", err)
- return
- }
- }
- }
-
- teamName := ctx.Params(":team")
- if len(teamName) > 0 {
- teamExists := false
- for _, team := range org.Teams {
- if team.LowerName == strings.ToLower(teamName) {
- teamExists = true
- ctx.Org.Team = team
- ctx.Org.IsTeamMember = true
- ctx.Data["Team"] = ctx.Org.Team
- break
- }
- }
-
- if !teamExists {
- ctx.Handle(404, "OrgAssignment", err)
- return
- }
-
- ctx.Data["IsTeamMember"] = ctx.Org.IsTeamMember
- if requireTeamMember && !ctx.Org.IsTeamMember {
- ctx.Handle(404, "OrgAssignment", err)
- return
- }
-
- ctx.Org.IsTeamAdmin = ctx.Org.Team.IsOwnerTeam() || ctx.Org.Team.Authorize >= models.ACCESS_MODE_ADMIN
- ctx.Data["IsTeamAdmin"] = ctx.Org.IsTeamAdmin
- if requireTeamAdmin && !ctx.Org.IsTeamAdmin {
- ctx.Handle(404, "OrgAssignment", err)
- return
- }
- }
-}
-
-func OrgAssignment(args ...bool) macaron.Handler {
- return func(ctx *Context) {
- HandleOrgAssignment(ctx, args...)
- }
-}
diff --git a/modules/middleware/repo.go b/modules/middleware/repo.go
deleted file mode 100644
index f96b87d437..0000000000
--- a/modules/middleware/repo.go
+++ /dev/null
@@ -1,368 +0,0 @@
-// Copyright 2014 The Gogs Authors. All rights reserved.
-// Use of this source code is governed by a MIT-style
-// license that can be found in the LICENSE file.
-
-package middleware
-
-import (
- "fmt"
- "path"
- "strings"
-
- "gopkg.in/macaron.v1"
-
- "github.com/gogits/git-module"
-
- "github.com/gogits/gogs/models"
- "github.com/gogits/gogs/modules/log"
- "github.com/gogits/gogs/modules/setting"
-)
-
-func RetrieveBaseRepo(ctx *Context, repo *models.Repository) {
- // Non-fork repository will not return error in this method.
- if err := repo.GetBaseRepo(); err != nil {
- if models.IsErrRepoNotExist(err) {
- repo.IsFork = false
- repo.ForkID = 0
- return
- }
- ctx.Handle(500, "GetBaseRepo", err)
- return
- } else if err = repo.BaseRepo.GetOwner(); err != nil {
- ctx.Handle(500, "BaseRepo.GetOwner", err)
- return
- }
-}
-
-func RepoAssignment(args ...bool) macaron.Handler {
- return func(ctx *Context) {
- var (
- displayBare bool // To display bare page if it is a bare repo.
- )
- if len(args) >= 1 {
- displayBare = args[0]
- }
-
- var (
- owner *models.User
- err error
- )
-
- userName := ctx.Params(":username")
- repoName := ctx.Params(":reponame")
- refName := ctx.Params(":branchname")
- if len(refName) == 0 {
- refName = ctx.Params(":path")
- }
-
- // Check if the user is the same as the repository owner
- if ctx.IsSigned && ctx.User.LowerName == strings.ToLower(userName) {
- owner = ctx.User
- } else {
- owner, err = models.GetUserByName(userName)
- if err != nil {
- if models.IsErrUserNotExist(err) {
- ctx.Handle(404, "GetUserByName", err)
- } else {
- ctx.Handle(500, "GetUserByName", err)
- }
- return
- }
- }
- ctx.Repo.Owner = owner
-
- // Get repository.
- repo, err := models.GetRepositoryByName(owner.Id, repoName)
- if err != nil {
- if models.IsErrRepoNotExist(err) {
- ctx.Handle(404, "GetRepositoryByName", err)
- } else {
- ctx.Handle(500, "GetRepositoryByName", err)
- }
- return
- } else if err = repo.GetOwner(); err != nil {
- ctx.Handle(500, "GetOwner", err)
- return
- }
-
- // Admin has super access.
- if ctx.IsSigned && ctx.User.IsAdmin {
- ctx.Repo.AccessMode = models.ACCESS_MODE_OWNER
- } else {
- mode, err := models.AccessLevel(ctx.User, repo)
- if err != nil {
- ctx.Handle(500, "AccessLevel", err)
- return
- }
- ctx.Repo.AccessMode = mode
- }
-
- // Check access.
- if ctx.Repo.AccessMode == models.ACCESS_MODE_NONE {
- ctx.Handle(404, "no access right", err)
- return
- }
- ctx.Data["HasAccess"] = true
-
- if repo.IsMirror {
- ctx.Repo.Mirror, err = models.GetMirror(repo.ID)
- if err != nil {
- ctx.Handle(500, "GetMirror", err)
- return
- }
- ctx.Data["MirrorInterval"] = ctx.Repo.Mirror.Interval
- ctx.Data["Mirror"] = ctx.Repo.Mirror
- }
-
- ctx.Repo.Repository = repo
- ctx.Data["IsBareRepo"] = ctx.Repo.Repository.IsBare
-
- gitRepo, err := git.OpenRepository(models.RepoPath(userName, repoName))
- if err != nil {
- ctx.Handle(500, "RepoAssignment Invalid repo "+models.RepoPath(userName, repoName), err)
- return
- }
- ctx.Repo.GitRepo = gitRepo
- ctx.Repo.RepoLink = repo.RepoLink()
- ctx.Data["RepoLink"] = ctx.Repo.RepoLink
- ctx.Data["RepoRelPath"] = ctx.Repo.Owner.Name + "/" + ctx.Repo.Repository.Name
-
- tags, err := ctx.Repo.GitRepo.GetTags()
- if err != nil {
- ctx.Handle(500, "GetTags", err)
- return
- }
- ctx.Data["Tags"] = tags
- ctx.Repo.Repository.NumTags = len(tags)
-
- ctx.Data["Title"] = owner.Name + "/" + repo.Name
- ctx.Data["Repository"] = repo
- ctx.Data["Owner"] = ctx.Repo.Repository.Owner
- ctx.Data["IsRepositoryOwner"] = ctx.Repo.IsOwner()
- ctx.Data["IsRepositoryAdmin"] = ctx.Repo.IsAdmin()
- ctx.Data["IsRepositoryWriter"] = ctx.Repo.IsWriter()
-
- ctx.Data["DisableSSH"] = setting.SSH.Disabled
- ctx.Data["CloneLink"] = repo.CloneLink()
- ctx.Data["WikiCloneLink"] = repo.WikiCloneLink()
-
- if ctx.IsSigned {
- ctx.Data["IsWatchingRepo"] = models.IsWatching(ctx.User.Id, repo.ID)
- ctx.Data["IsStaringRepo"] = models.IsStaring(ctx.User.Id, repo.ID)
- }
-
- // repo is bare and display enable
- if ctx.Repo.Repository.IsBare {
- log.Debug("Bare repository: %s", ctx.Repo.RepoLink)
- // NOTE: to prevent templating error
- ctx.Data["BranchName"] = ""
- if displayBare {
- if !ctx.Repo.IsAdmin() {
- ctx.Flash.Info(ctx.Tr("repo.repo_is_empty"), true)
- }
- ctx.HTML(200, "repo/bare")
- }
- return
- }
-
- ctx.Data["TagName"] = ctx.Repo.TagName
- brs, err := ctx.Repo.GitRepo.GetBranches()
- if err != nil {
- ctx.Handle(500, "GetBranches", err)
- return
- }
- ctx.Data["Branches"] = brs
- ctx.Data["BrancheCount"] = len(brs)
-
- // If not branch selected, try default one.
- // If default branch doesn't exists, fall back to some other branch.
- if len(ctx.Repo.BranchName) == 0 {
- if len(ctx.Repo.Repository.DefaultBranch) > 0 && gitRepo.IsBranchExist(ctx.Repo.Repository.DefaultBranch) {
- ctx.Repo.BranchName = ctx.Repo.Repository.DefaultBranch
- } else if len(brs) > 0 {
- ctx.Repo.BranchName = brs[0]
- }
- }
- ctx.Data["BranchName"] = ctx.Repo.BranchName
- ctx.Data["CommitID"] = ctx.Repo.CommitID
-
- if repo.IsFork {
- RetrieveBaseRepo(ctx, repo)
- if ctx.Written() {
- return
- }
- }
-
- // People who have push access and propose a new pull request.
- if ctx.Repo.IsWriter() {
- // Pull request is allowed if this is a fork repository
- // and base repository accepts pull requests.
- if repo.BaseRepo != nil {
- if repo.BaseRepo.AllowsPulls() {
- ctx.Data["BaseRepo"] = repo.BaseRepo
- ctx.Repo.PullRequest.BaseRepo = repo.BaseRepo
- ctx.Repo.PullRequest.Allowed = true
- ctx.Repo.PullRequest.HeadInfo = ctx.Repo.Owner.Name + ":" + ctx.Repo.BranchName
- }
- } else {
- // Or, this is repository accepts pull requests between branches.
- if repo.AllowsPulls() {
- ctx.Data["BaseRepo"] = repo
- ctx.Repo.PullRequest.BaseRepo = repo
- ctx.Repo.PullRequest.Allowed = true
- ctx.Repo.PullRequest.SameRepo = true
- ctx.Repo.PullRequest.HeadInfo = ctx.Repo.BranchName
- }
- }
- }
- fmt.Println(222222, ctx.Repo.PullRequest)
- ctx.Data["PullRequestCtx"] = ctx.Repo.PullRequest
-
- if ctx.Query("go-get") == "1" {
- ctx.Data["GoGetImport"] = path.Join(setting.Domain, setting.AppSubUrl, owner.Name, repo.Name)
- prefix := setting.AppUrl + path.Join(owner.Name, repo.Name, "src", ctx.Repo.BranchName)
- ctx.Data["GoDocDirectory"] = prefix + "{/dir}"
- ctx.Data["GoDocFile"] = prefix + "{/dir}/{file}#L{line}"
- }
- }
-}
-
-// RepoRef handles repository reference name including those contain `/`.
-func RepoRef() macaron.Handler {
- return func(ctx *Context) {
- // Empty repository does not have reference information.
- if ctx.Repo.Repository.IsBare {
- return
- }
-
- var (
- refName string
- err error
- )
-
- // For API calls.
- if ctx.Repo.GitRepo == nil {
- repoPath := models.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
- gitRepo, err := git.OpenRepository(repoPath)
- if err != nil {
- ctx.Handle(500, "RepoRef Invalid repo "+repoPath, err)
- return
- }
- ctx.Repo.GitRepo = gitRepo
- }
-
- // Get default branch.
- if len(ctx.Params("*")) == 0 {
- refName = ctx.Repo.Repository.DefaultBranch
- if !ctx.Repo.GitRepo.IsBranchExist(refName) {
- brs, err := ctx.Repo.GitRepo.GetBranches()
- if err != nil {
- ctx.Handle(500, "GetBranches", err)
- return
- }
- refName = brs[0]
- }
- ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName)
- if err != nil {
- ctx.Handle(500, "GetBranchCommit", err)
- return
- }
- ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
- ctx.Repo.IsViewBranch = true
-
- } else {
- hasMatched := false
- parts := strings.Split(ctx.Params("*"), "/")
- for i, part := range parts {
- refName = strings.TrimPrefix(refName+"/"+part, "/")
-
- if ctx.Repo.GitRepo.IsBranchExist(refName) ||
- ctx.Repo.GitRepo.IsTagExist(refName) {
- if i < len(parts)-1 {
- ctx.Repo.TreeName = strings.Join(parts[i+1:], "/")
- }
- hasMatched = true
- break
- }
- }
- if !hasMatched && len(parts[0]) == 40 {
- refName = parts[0]
- ctx.Repo.TreeName = strings.Join(parts[1:], "/")
- }
-
- if ctx.Repo.GitRepo.IsBranchExist(refName) {
- ctx.Repo.IsViewBranch = true
-
- ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName)
- if err != nil {
- ctx.Handle(500, "GetBranchCommit", err)
- return
- }
- ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
-
- } else if ctx.Repo.GitRepo.IsTagExist(refName) {
- ctx.Repo.IsViewTag = true
- ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetTagCommit(refName)
- if err != nil {
- ctx.Handle(500, "GetTagCommit", err)
- return
- }
- ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
- } else if len(refName) == 40 {
- ctx.Repo.IsViewCommit = true
- ctx.Repo.CommitID = refName
-
- ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetCommit(refName)
- if err != nil {
- ctx.Handle(404, "GetCommit", nil)
- return
- }
- } else {
- ctx.Handle(404, "RepoRef invalid repo", fmt.Errorf("branch or tag not exist: %s", refName))
- return
- }
- }
-
- ctx.Repo.BranchName = refName
- ctx.Data["BranchName"] = ctx.Repo.BranchName
- ctx.Data["CommitID"] = ctx.Repo.CommitID
- ctx.Data["IsViewBranch"] = ctx.Repo.IsViewBranch
- ctx.Data["IsViewTag"] = ctx.Repo.IsViewTag
- ctx.Data["IsViewCommit"] = ctx.Repo.IsViewCommit
-
- ctx.Repo.CommitsCount, err = ctx.Repo.Commit.CommitsCount()
- if err != nil {
- ctx.Handle(500, "CommitsCount", err)
- return
- }
- ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
- }
-}
-
-func RequireRepoAdmin() macaron.Handler {
- return func(ctx *Context) {
- if !ctx.IsSigned || (!ctx.Repo.IsAdmin() && !ctx.User.IsAdmin) {
- ctx.Handle(404, ctx.Req.RequestURI, nil)
- return
- }
- }
-}
-
-func RequireRepoWriter() macaron.Handler {
- return func(ctx *Context) {
- if !ctx.IsSigned || (!ctx.Repo.IsWriter() && !ctx.User.IsAdmin) {
- ctx.Handle(404, ctx.Req.RequestURI, nil)
- return
- }
- }
-}
-
-// GitHookService checks if repository Git hooks service has been enabled.
-func GitHookService() macaron.Handler {
- return func(ctx *Context) {
- if !ctx.User.CanEditGitHook() {
- ctx.Handle(404, "GitHookService", nil)
- return
- }
- }
-}