1
1
mirror of https://github.com/go-gitea/gitea synced 2025-08-23 09:58:27 +00:00

Move macaron to chi (#14293)

Use [chi](https://github.com/go-chi/chi) instead of the forked [macaron](https://gitea.com/macaron/macaron). Since macaron and chi have conflicts with session share, this big PR becomes a have-to thing. According my previous idea, we can replace macaron step by step but I'm wrong. :( Below is a list of big changes on this PR.

- [x] Define `context.ResponseWriter` interface with an implementation `context.Response`.
- [x] Use chi instead of macaron, and also a customize `Route` to wrap chi so that the router usage is similar as before.
- [x] Create different routers for `web`, `api`, `internal` and `install` so that the codes will be more clear and no magic .
- [x] Use https://github.com/unrolled/render instead of macaron's internal render
- [x] Use https://github.com/NYTimes/gziphandler instead of https://gitea.com/macaron/gzip
- [x] Use https://gitea.com/go-chi/session which is a modified version of https://gitea.com/macaron/session and removed `nodb` support since it will not be maintained. **BREAK**
- [x] Use https://gitea.com/go-chi/captcha which is a modified version of https://gitea.com/macaron/captcha
- [x] Use https://gitea.com/go-chi/cache which is a modified version of https://gitea.com/macaron/cache
- [x] Use https://gitea.com/go-chi/binding which is a modified version of https://gitea.com/macaron/binding
- [x] Use https://github.com/go-chi/cors instead of https://gitea.com/macaron/cors
- [x] Dropped https://gitea.com/macaron/i18n and make a new one in `code.gitea.io/gitea/modules/translation`
- [x] Move validation form structs from `code.gitea.io/gitea/modules/auth` to `code.gitea.io/gitea/modules/forms` to avoid dependency cycle.
- [x] Removed macaron log service because it's not need any more. **BREAK**
- [x] All form structs have to be get by `web.GetForm(ctx)` in the route function but not as a function parameter on routes definition.
- [x] Move Git HTTP protocol implementation to use routers directly.
- [x] Fix the problem that chi routes don't support trailing slash but macaron did.
- [x] `/api/v1/swagger` now will be redirect to `/api/swagger` but not render directly so that `APIContext` will not create a html render. 

Notices:
- Chi router don't support request with trailing slash
- Integration test `TestUserHeatmap` maybe mysql version related. It's failed on my macOS(mysql 5.7.29 installed via brew) but succeed on CI.

Co-authored-by: 6543 <6543@obermui.de>
This commit is contained in:
Lunny Xiao
2021-01-26 23:36:53 +08:00
committed by GitHub
parent 3adbbb4255
commit 6433ba0ec3
353 changed files with 5463 additions and 20785 deletions

View File

@@ -16,19 +16,16 @@ import (
"text/template"
"time"
"code.gitea.io/gitea/modules/auth/sso"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/httpcache"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/metrics"
"code.gitea.io/gitea/modules/public"
"code.gitea.io/gitea/modules/middlewares"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/storage"
"code.gitea.io/gitea/routers"
"code.gitea.io/gitea/modules/templates"
"gitea.com/go-chi/session"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/prometheus/client_golang/prometheus"
)
type routerLoggerOptions struct {
@@ -39,20 +36,21 @@ type routerLoggerOptions struct {
}
// SignedUserName returns signed user's name via context
// FIXME currently no any data stored on chi.Context but macaron.Context, so this will
// return "" before we remove macaron totally
func SignedUserName(req *http.Request) string {
if v, ok := req.Context().Value("SignedUserName").(string); ok {
return v
ctx := context.GetContext(req)
if ctx != nil {
v := ctx.Data["SignedUserName"]
if res, ok := v.(string); ok {
return res
}
}
return ""
}
func setupAccessLogger(c chi.Router) {
func accessLogger() func(http.Handler) http.Handler {
logger := log.GetLogger("access")
logTemplate, _ := template.New("log").Parse(setting.AccessLogTemplate)
c.Use(func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
start := time.Now()
next.ServeHTTP(w, req)
@@ -70,15 +68,15 @@ func setupAccessLogger(c chi.Router) {
ResponseWriter: rw,
})
if err != nil {
log.Error("Could not set up macaron access logger: %v", err.Error())
log.Error("Could not set up chi access logger: %v", err.Error())
}
err = logger.SendLog(log.INFO, "", "", 0, buf.String(), "")
if err != nil {
log.Error("Could not set up macaron access logger: %v", err.Error())
log.Error("Could not set up chi access logger: %v", err.Error())
}
})
})
}
}
// LoggerHandler is a handler that will log the routing to the default gitea log
@@ -179,131 +177,70 @@ func storageHandler(storageSetting setting.Storage, prefix string, objStore stor
}
}
var (
sessionManager *session.Manager
)
// NewChi creates a chi Router
func NewChi() chi.Router {
c := chi.NewRouter()
c.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
next.ServeHTTP(context.NewResponse(resp), req)
})
})
c.Use(middleware.RealIP)
if !setting.DisableRouterLog && setting.RouterLogLevel != log.NONE {
if log.GetLogger("router").GetLevel() <= setting.RouterLogLevel {
c.Use(LoggerHandler(setting.RouterLogLevel))
}
}
var opt = session.Options{
Provider: setting.SessionConfig.Provider,
ProviderConfig: setting.SessionConfig.ProviderConfig,
CookieName: setting.SessionConfig.CookieName,
CookiePath: setting.SessionConfig.CookiePath,
Gclifetime: setting.SessionConfig.Gclifetime,
Maxlifetime: setting.SessionConfig.Maxlifetime,
Secure: setting.SessionConfig.Secure,
Domain: setting.SessionConfig.Domain,
}
opt = session.PrepareOptions([]session.Options{opt})
var err error
sessionManager, err = session.NewManager(opt.Provider, opt)
if err != nil {
panic(err)
}
c.Use(Recovery())
if setting.EnableAccessLog {
setupAccessLogger(c)
}
c.Use(public.Custom(
&public.Options{
SkipLogging: setting.DisableRouterLog,
},
))
c.Use(public.Static(
&public.Options{
Directory: path.Join(setting.StaticRootPath, "public"),
SkipLogging: setting.DisableRouterLog,
},
))
c.Use(storageHandler(setting.Avatar.Storage, "avatars", storage.Avatars))
c.Use(storageHandler(setting.RepoAvatar.Storage, "repo-avatars", storage.RepoAvatars))
return c
type dataStore struct {
Data map[string]interface{}
}
// RegisterInstallRoute registers the install routes
func RegisterInstallRoute(c chi.Router) {
m := NewMacaron()
RegisterMacaronInstallRoute(m)
// We need at least one handler in chi so that it does not drop
// our middleware: https://github.com/go-gitea/gitea/issues/13725#issuecomment-735244395
c.Get("/", func(w http.ResponseWriter, req *http.Request) {
m.ServeHTTP(w, req)
})
c.NotFound(func(w http.ResponseWriter, req *http.Request) {
m.ServeHTTP(w, req)
})
c.MethodNotAllowed(func(w http.ResponseWriter, req *http.Request) {
m.ServeHTTP(w, req)
})
func (d *dataStore) GetData() map[string]interface{} {
return d.Data
}
// NormalRoutes represents non install routes
func NormalRoutes() http.Handler {
r := chi.NewRouter()
// Recovery returns a middleware that recovers from any panics and writes a 500 and a log if so.
// This error will be created with the gitea 500 page.
func Recovery() func(next http.Handler) http.Handler {
var rnd = templates.HTMLRenderer()
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
defer func() {
if err := recover(); err != nil {
combinedErr := fmt.Sprintf("PANIC: %v\n%s", err, string(log.Stack(2)))
log.Error("%v", combinedErr)
// for health check
r.Head("/", func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(http.StatusOK)
})
sessionStore := session.GetSession(req)
if sessionStore == nil {
if setting.IsProd() {
http.Error(w, http.StatusText(500), 500)
} else {
http.Error(w, combinedErr, 500)
}
return
}
if setting.HasRobotsTxt {
r.Get("/robots.txt", func(w http.ResponseWriter, req *http.Request) {
filePath := path.Join(setting.CustomPath, "robots.txt")
fi, err := os.Stat(filePath)
if err == nil && httpcache.HandleTimeCache(req, w, fi) {
return
}
http.ServeFile(w, req, filePath)
var lc = middlewares.Locale(w, req)
var store = dataStore{
Data: templates.Vars{
"Language": lc.Language(),
"CurrentURL": setting.AppSubURL + req.URL.RequestURI(),
"i18n": lc,
},
}
// Get user from session if logged in.
user, _ := sso.SignedInUser(req, w, &store, sessionStore)
if user != nil {
store.Data["IsSigned"] = true
store.Data["SignedUser"] = user
store.Data["SignedUserID"] = user.ID
store.Data["SignedUserName"] = user.Name
store.Data["IsAdmin"] = user.IsAdmin
} else {
store.Data["SignedUserID"] = int64(0)
store.Data["SignedUserName"] = ""
}
w.Header().Set(`X-Frame-Options`, `SAMEORIGIN`)
if !setting.IsProd() {
store.Data["ErrorMsg"] = combinedErr
}
err = rnd.HTML(w, 500, "status/500", templates.BaseVars().Merge(store.Data))
if err != nil {
log.Error("%v", err)
}
}
}()
next.ServeHTTP(w, req)
})
}
r.Get("/apple-touch-icon.png", func(w http.ResponseWriter, req *http.Request) {
http.Redirect(w, req, path.Join(setting.StaticURLPrefix, "img/apple-touch-icon.png"), 301)
})
// prometheus metrics endpoint
if setting.Metrics.Enabled {
c := metrics.NewCollector()
prometheus.MustRegister(c)
r.Get("/metrics", routers.Metrics)
}
return r
}
// DelegateToMacaron delegates other routes to macaron
func DelegateToMacaron(r chi.Router) {
m := NewMacaron()
RegisterMacaronRoutes(m)
r.NotFound(func(w http.ResponseWriter, req *http.Request) {
m.ServeHTTP(w, req)
})
r.MethodNotAllowed(func(w http.ResponseWriter, req *http.Request) {
m.ServeHTTP(w, req)
})
}

View File

@@ -7,38 +7,23 @@ package routes
import (
"fmt"
"net/http"
"path"
"code.gitea.io/gitea/modules/auth/sso"
"code.gitea.io/gitea/modules/forms"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/middlewares"
"code.gitea.io/gitea/modules/public"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/templates"
"code.gitea.io/gitea/modules/web"
"code.gitea.io/gitea/routers"
"github.com/unrolled/render"
"gitea.com/go-chi/session"
)
type dataStore struct {
Data map[string]interface{}
}
func (d *dataStore) GetData() map[string]interface{} {
return d.Data
}
// Recovery returns a middleware that recovers from any panics and writes a 500 and a log if so.
// Although similar to macaron.Recovery() the main difference is that this error will be created
// with the gitea 500 page.
func Recovery() func(next http.Handler) http.Handler {
func installRecovery() func(next http.Handler) http.Handler {
var rnd = templates.HTMLRenderer()
return func(next http.Handler) http.Handler {
rnd := render.New(render.Options{
Extensions: []string{".tmpl"},
Directory: "templates",
Funcs: templates.NewFuncMap(),
Asset: templates.GetAsset,
AssetNames: templates.GetAssetNames,
IsDevelopment: !setting.IsProd(),
})
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
defer func() {
// Why we need this? The first recover will try to render a beautiful
@@ -62,35 +47,16 @@ func Recovery() func(next http.Handler) http.Handler {
log.Error("%v", combinedErr)
lc := middlewares.Locale(w, req)
// TODO: this should be replaced by real session after macaron removed totally
sessionStore, err := sessionManager.Start(w, req)
if err != nil {
// Just invoke the above recover catch
panic("session(start): " + err.Error())
}
var store = dataStore{
Data: templates.Vars{
"Language": lc.Language(),
"CurrentURL": setting.AppSubURL + req.URL.RequestURI(),
"i18n": lc,
"Language": lc.Language(),
"CurrentURL": setting.AppSubURL + req.URL.RequestURI(),
"i18n": lc,
"SignedUserID": int64(0),
"SignedUserName": "",
},
}
// Get user from session if logged in.
user, _ := sso.SignedInUser(req, w, &store, sessionStore)
if user != nil {
store.Data["IsSigned"] = true
store.Data["SignedUser"] = user
store.Data["SignedUserID"] = user.ID
store.Data["SignedUserName"] = user.Name
store.Data["IsAdmin"] = user.IsAdmin
} else {
store.Data["SignedUserID"] = int64(0)
store.Data["SignedUserName"] = ""
}
w.Header().Set(`X-Frame-Options`, `SAMEORIGIN`)
if !setting.IsProd() {
@@ -107,3 +73,44 @@ func Recovery() func(next http.Handler) http.Handler {
})
}
}
// InstallRoutes registers the install routes
func InstallRoutes() *web.Route {
r := web.NewRoute()
for _, middle := range commonMiddlewares() {
r.Use(middle)
}
r.Use(session.Sessioner(session.Options{
Provider: setting.SessionConfig.Provider,
ProviderConfig: setting.SessionConfig.ProviderConfig,
CookieName: setting.SessionConfig.CookieName,
CookiePath: setting.SessionConfig.CookiePath,
Gclifetime: setting.SessionConfig.Gclifetime,
Maxlifetime: setting.SessionConfig.Maxlifetime,
Secure: setting.SessionConfig.Secure,
Domain: setting.SessionConfig.Domain,
}))
r.Use(installRecovery())
r.Use(public.Custom(
&public.Options{
SkipLogging: setting.DisableRouterLog,
},
))
r.Use(public.Static(
&public.Options{
Directory: path.Join(setting.StaticRootPath, "public"),
SkipLogging: setting.DisableRouterLog,
},
))
r.Use(routers.InstallInit)
r.Get("/", routers.Install)
r.Post("/", web.Bind(forms.InstallForm{}), routers.InstallPost)
r.NotFound(func(w http.ResponseWriter, req *http.Request) {
http.Redirect(w, req, setting.AppURL, 302)
})
return r
}

View File

@@ -6,19 +6,29 @@ package routes
import (
"encoding/gob"
"fmt"
"net/http"
"os"
"path"
"strings"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/auth"
"code.gitea.io/gitea/modules/context"
auth "code.gitea.io/gitea/modules/forms"
"code.gitea.io/gitea/modules/httpcache"
"code.gitea.io/gitea/modules/lfs"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/options"
"code.gitea.io/gitea/modules/metrics"
"code.gitea.io/gitea/modules/public"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/storage"
"code.gitea.io/gitea/modules/templates"
"code.gitea.io/gitea/modules/validation"
"code.gitea.io/gitea/modules/web"
"code.gitea.io/gitea/routers"
"code.gitea.io/gitea/routers/admin"
apiv1 "code.gitea.io/gitea/routers/api/v1"
"code.gitea.io/gitea/routers/api/v1/misc"
"code.gitea.io/gitea/routers/dev"
"code.gitea.io/gitea/routers/events"
"code.gitea.io/gitea/routers/org"
@@ -31,77 +41,79 @@ import (
// to registers all internal adapters
_ "code.gitea.io/gitea/modules/session"
"gitea.com/macaron/binding"
"gitea.com/macaron/cache"
"gitea.com/macaron/captcha"
"gitea.com/macaron/cors"
"gitea.com/macaron/csrf"
"gitea.com/macaron/gzip"
"gitea.com/macaron/i18n"
"gitea.com/macaron/macaron"
"gitea.com/macaron/session"
"gitea.com/macaron/toolbox"
"gitea.com/go-chi/captcha"
"gitea.com/go-chi/session"
"github.com/NYTimes/gziphandler"
"github.com/go-chi/chi/middleware"
"github.com/prometheus/client_golang/prometheus"
"github.com/tstranex/u2f"
)
// NewMacaron initializes Macaron instance.
func NewMacaron() *macaron.Macaron {
gob.Register(&u2f.Challenge{})
var m *macaron.Macaron
if setting.RedirectMacaronLog {
loggerAsWriter := log.NewLoggerAsWriter("INFO", log.GetLogger("macaron"))
m = macaron.NewWithLogger(loggerAsWriter)
} else {
m = macaron.New()
const (
// GzipMinSize represents min size to compress for the body size of response
GzipMinSize = 1400
)
func commonMiddlewares() []func(http.Handler) http.Handler {
var handlers = []func(http.Handler) http.Handler{
func(next http.Handler) http.Handler {
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
next.ServeHTTP(context.NewResponse(resp), req)
})
},
middleware.RealIP,
}
if setting.EnableGzip {
m.Use(gzip.Middleware())
}
if setting.Protocol == setting.FCGI || setting.Protocol == setting.FCGIUnix {
m.SetURLPrefix(setting.AppSubURL)
}
m.Use(templates.HTMLRenderer())
mailer.InitMailRender(templates.Mailer())
localeNames, err := options.Dir("locale")
if err != nil {
log.Fatal("Failed to list locale files: %v", err)
}
localFiles := make(map[string][]byte)
for _, name := range localeNames {
localFiles[name], err = options.Locale(name)
if err != nil {
log.Fatal("Failed to load %s locale file. %v", name, err)
if !setting.DisableRouterLog && setting.RouterLogLevel != log.NONE {
if log.GetLogger("router").GetLevel() <= setting.RouterLogLevel {
handlers = append(handlers, LoggerHandler(setting.RouterLogLevel))
}
}
handlers = append(handlers, func(next http.Handler) http.Handler {
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
// Why we need this? The Recovery() will try to render a beautiful
// error page for user, but the process can still panic again, and other
// middleware like session also may panic then we have to recover twice
// and send a simple error page that should not panic any more.
defer func() {
if err := recover(); err != nil {
combinedErr := fmt.Sprintf("PANIC: %v\n%s", err, string(log.Stack(2)))
log.Error("%v", combinedErr)
if setting.IsProd() {
http.Error(resp, http.StatusText(500), 500)
} else {
http.Error(resp, combinedErr, 500)
}
}
}()
next.ServeHTTP(resp, req)
})
})
m.Use(i18n.I18n(i18n.Options{
SubURL: setting.AppSubURL,
Files: localFiles,
Langs: setting.Langs,
Names: setting.Names,
DefaultLang: "en-US",
Redirect: false,
CookieHttpOnly: true,
Secure: setting.SessionConfig.Secure,
CookieDomain: setting.SessionConfig.Domain,
}))
m.Use(cache.Cacher(cache.Options{
Adapter: setting.CacheService.Adapter,
AdapterConfig: setting.CacheService.Conn,
Interval: setting.CacheService.Interval,
}))
m.Use(captcha.Captchaer(captcha.Options{
SubURL: setting.AppSubURL,
}))
m.Use(session.Sessioner(session.Options{
if setting.EnableAccessLog {
handlers = append(handlers, accessLogger())
}
return handlers
}
// NormalRoutes represents non install routes
func NormalRoutes() *web.Route {
r := web.NewRoute()
for _, middle := range commonMiddlewares() {
r.Use(middle)
}
r.Use(Recovery())
r.Mount("/", WebRoutes())
r.Mount("/api/v1", apiv1.Routes())
r.Mount("/api/internal", private.Routes())
return r
}
// WebRoutes returns all web routes
func WebRoutes() *web.Route {
r := web.NewRoute()
r.Use(session.Sessioner(session.Options{
Provider: setting.SessionConfig.Provider,
ProviderConfig: setting.SessionConfig.ProviderConfig,
CookieName: setting.SessionConfig.CookieName,
@@ -111,47 +123,104 @@ func NewMacaron() *macaron.Macaron {
Secure: setting.SessionConfig.Secure,
Domain: setting.SessionConfig.Domain,
}))
m.Use(csrf.Csrfer(csrf.Options{
Secret: setting.SecretKey,
Cookie: setting.CSRFCookieName,
SetCookie: true,
Secure: setting.SessionConfig.Secure,
CookieHttpOnly: setting.CSRFCookieHTTPOnly,
Header: "X-Csrf-Token",
CookieDomain: setting.SessionConfig.Domain,
CookiePath: setting.AppSubURL,
}))
m.Use(toolbox.Toolboxer(m, toolbox.Options{
HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{
{
Desc: "Database connection",
Func: models.Ping,
},
r.Use(public.Custom(
&public.Options{
SkipLogging: setting.DisableRouterLog,
},
DisableDebug: !setting.EnablePprof,
}))
m.Use(context.Contexter())
m.SetAutoHead(true)
return m
}
))
r.Use(public.Static(
&public.Options{
Directory: path.Join(setting.StaticRootPath, "public"),
SkipLogging: setting.DisableRouterLog,
},
))
// RegisterMacaronInstallRoute registers the install routes
func RegisterMacaronInstallRoute(m *macaron.Macaron) {
m.Combo("/", routers.InstallInit).Get(routers.Install).
Post(binding.BindIgnErr(auth.InstallForm{}), routers.InstallPost)
m.NotFound(func(ctx *context.Context) {
ctx.Redirect(setting.AppURL, 302)
r.Use(storageHandler(setting.Avatar.Storage, "avatars", storage.Avatars))
r.Use(storageHandler(setting.RepoAvatar.Storage, "repo-avatars", storage.RepoAvatars))
gob.Register(&u2f.Challenge{})
if setting.EnableGzip {
h, err := gziphandler.GzipHandlerWithOpts(gziphandler.MinSize(GzipMinSize))
if err != nil {
log.Fatal("GzipHandlerWithOpts failed: %v", err)
}
r.Use(h)
}
if (setting.Protocol == setting.FCGI || setting.Protocol == setting.FCGIUnix) && setting.AppSubURL != "" {
r.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
req.URL.Path = strings.TrimPrefix(req.URL.Path, setting.AppSubURL)
next.ServeHTTP(resp, req)
})
})
}
mailer.InitMailRender(templates.Mailer())
r.Use(captcha.Captchaer(context.GetImageCaptcha()))
// Removed: toolbox.Toolboxer middleware will provide debug informations which seems unnecessary
r.Use(context.Contexter())
// Removed: SetAutoHead allow a get request redirect to head if get method is not exist
r.Use(user.GetNotificationCount)
r.Use(repo.GetActiveStopwatch)
r.Use(func(ctx *context.Context) {
ctx.Data["UnitWikiGlobalDisabled"] = models.UnitTypeWiki.UnitGlobalDisabled()
ctx.Data["UnitIssuesGlobalDisabled"] = models.UnitTypeIssues.UnitGlobalDisabled()
ctx.Data["UnitPullsGlobalDisabled"] = models.UnitTypePullRequests.UnitGlobalDisabled()
ctx.Data["UnitProjectsGlobalDisabled"] = models.UnitTypeProjects.UnitGlobalDisabled()
})
// for health check
r.Head("/", func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(http.StatusOK)
})
if setting.HasRobotsTxt {
r.Get("/robots.txt", func(w http.ResponseWriter, req *http.Request) {
filePath := path.Join(setting.CustomPath, "robots.txt")
fi, err := os.Stat(filePath)
if err == nil && httpcache.HandleTimeCache(req, w, fi) {
return
}
http.ServeFile(w, req, filePath)
})
}
r.Get("/apple-touch-icon.png", func(w http.ResponseWriter, req *http.Request) {
http.Redirect(w, req, path.Join(setting.StaticURLPrefix, "img/apple-touch-icon.png"), 301)
})
// prometheus metrics endpoint
if setting.Metrics.Enabled {
c := metrics.NewCollector()
prometheus.MustRegister(c)
r.Get("/metrics", routers.Metrics)
}
if setting.API.EnableSwagger {
// Note: The route moved from apiroutes because it's in fact want to render a web page
r.Get("/api/swagger", misc.Swagger) // Render V1 by default
}
RegisterRoutes(r)
return r
}
// RegisterMacaronRoutes routes routes to Macaron
func RegisterMacaronRoutes(m *macaron.Macaron) {
// RegisterRoutes routes routes to Macaron
func RegisterRoutes(m *web.Route) {
reqSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: true})
ignSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: setting.Service.RequireSignInView})
ignSignInAndCsrf := context.Toggle(&context.ToggleOptions{DisableCSRF: true})
reqSignOut := context.Toggle(&context.ToggleOptions{SignOutRequired: true})
bindIgnErr := binding.BindIgnErr
//bindIgnErr := binding.BindIgnErr
bindIgnErr := web.Bind
validation.AddBindingRules()
openIDSignInEnabled := func(ctx *context.Context) {
@@ -175,15 +244,6 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
}
}
m.Use(user.GetNotificationCount)
m.Use(repo.GetActiveStopwatch)
m.Use(func(ctx *context.Context) {
ctx.Data["UnitWikiGlobalDisabled"] = models.UnitTypeWiki.UnitGlobalDisabled()
ctx.Data["UnitIssuesGlobalDisabled"] = models.UnitTypeIssues.UnitGlobalDisabled()
ctx.Data["UnitPullsGlobalDisabled"] = models.UnitTypePullRequests.UnitGlobalDisabled()
ctx.Data["UnitProjectsGlobalDisabled"] = models.UnitTypeProjects.UnitGlobalDisabled()
})
// FIXME: not all routes need go through same middlewares.
// Especially some AJAX requests, we can reduce middleware number to improve performance.
// Routers.
@@ -198,8 +258,6 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
m.Get("/organizations", routers.ExploreOrganizations)
m.Get("/code", routers.ExploreCode)
}, ignSignIn)
m.Combo("/install", routers.InstallInit).Get(routers.Install).
Post(bindIgnErr(auth.InstallForm{}), routers.InstallPost)
m.Get("/issues", reqSignIn, user.Issues)
m.Get("/pulls", reqSignIn, user.Pulls)
m.Get("/milestones", reqSignIn, reqMilestonesDashboardPageEnabled, user.Milestones)
@@ -226,8 +284,8 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
m.Get("/sign_up", user.SignUp)
m.Post("/sign_up", bindIgnErr(auth.RegisterForm{}), user.SignUpPost)
m.Group("/oauth2", func() {
m.Get("/:provider", user.SignInOAuth)
m.Get("/:provider/callback", user.SignInOAuthCallback)
m.Get("/{provider}", user.SignInOAuth)
m.Get("/{provider}/callback", user.SignInOAuthCallback)
})
m.Get("/link_account", user.LinkAccount)
m.Post("/link_account_signin", bindIgnErr(auth.SignInForm{}), user.LinkAccountPostSignIn)
@@ -261,7 +319,7 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
m.Post("", bindIgnErr(auth.UpdateProfileForm{}), userSetting.ProfilePost)
m.Get("/change_password", user.MustChangePassword)
m.Post("/change_password", bindIgnErr(auth.MustChangePasswordForm{}), user.MustChangePasswordPost)
m.Post("/avatar", binding.MultipartForm(auth.AvatarForm{}), userSetting.AvatarPost)
m.Post("/avatar", bindIgnErr(auth.AvatarForm{}), userSetting.AvatarPost)
m.Post("/avatar/delete", userSetting.DeleteAvatar)
m.Group("/account", func() {
m.Combo("").Get(userSetting.Account).Post(bindIgnErr(auth.ChangePasswordForm{}), userSetting.AccountPost)
@@ -291,9 +349,9 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
m.Post("/account_link", userSetting.DeleteAccountLink)
})
m.Group("/applications/oauth2", func() {
m.Get("/:id", userSetting.OAuth2ApplicationShow)
m.Post("/:id", bindIgnErr(auth.EditOAuth2ApplicationForm{}), userSetting.OAuthApplicationsEdit)
m.Post("/:id/regenerate_secret", userSetting.OAuthApplicationsRegenerateSecret)
m.Get("/{id}", userSetting.OAuth2ApplicationShow)
m.Post("/{id}", bindIgnErr(auth.EditOAuth2ApplicationForm{}), userSetting.OAuthApplicationsEdit)
m.Post("/{id}/regenerate_secret", userSetting.OAuthApplicationsRegenerateSecret)
m.Post("", bindIgnErr(auth.EditOAuth2ApplicationForm{}), userSetting.OAuthApplicationsPost)
m.Post("/delete", userSetting.DeleteOAuth2Application)
m.Post("/revoke", userSetting.RevokeOAuth2Grant)
@@ -316,18 +374,18 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
// r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds)
m.Any("/activate", user.Activate, reqSignIn)
m.Any("/activate_email", user.ActivateEmail)
m.Get("/avatar/:username/:size", user.Avatar)
m.Get("/avatar/{username}/{size}", user.Avatar)
m.Get("/email2user", user.Email2User)
m.Get("/recover_account", user.ResetPasswd)
m.Post("/recover_account", user.ResetPasswdPost)
m.Get("/forgot_password", user.ForgotPasswd)
m.Post("/forgot_password", user.ForgotPasswdPost)
m.Post("/logout", user.SignOut)
m.Get("/task/:task", user.TaskStatus)
m.Get("/task/{task}", user.TaskStatus)
})
// ***** END: User *****
m.Get("/avatar/:hash", user.AvatarByEmailHash)
m.Get("/avatar/{hash}", user.AvatarByEmailHash)
adminReq := context.Toggle(&context.ToggleOptions{SignInRequired: true, AdminRequired: true})
@@ -339,12 +397,12 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
m.Post("/config/test_mail", admin.SendTestMail)
m.Group("/monitor", func() {
m.Get("", admin.Monitor)
m.Post("/cancel/:pid", admin.MonitorCancel)
m.Group("/queue/:qid", func() {
m.Post("/cancel/{pid}", admin.MonitorCancel)
m.Group("/queue/{qid}", func() {
m.Get("", admin.Queue)
m.Post("/set", admin.SetQueueSettings)
m.Post("/add", admin.AddWorkers)
m.Post("/cancel/:pid", admin.WorkerCancel)
m.Post("/cancel/{pid}", admin.WorkerCancel)
m.Post("/flush", admin.Flush)
})
})
@@ -352,8 +410,8 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
m.Group("/users", func() {
m.Get("", admin.Users)
m.Combo("/new").Get(admin.NewUser).Post(bindIgnErr(auth.AdminCreateUserForm{}), admin.NewUserPost)
m.Combo("/:userid").Get(admin.EditUser).Post(bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost)
m.Post("/:userid/delete", admin.DeleteUser)
m.Combo("/{userid}").Get(admin.EditUser).Post(bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost)
m.Post("/{userid}/delete", admin.DeleteUser)
})
m.Group("/emails", func() {
@@ -374,20 +432,20 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
m.Group("/hooks", func() {
m.Get("", admin.DefaultOrSystemWebhooks)
m.Post("/delete", admin.DeleteDefaultOrSystemWebhook)
m.Get("/:id", repo.WebHooksEdit)
m.Post("/gitea/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
m.Post("/gogs/:id", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksEditPost)
m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
m.Post("/discord/:id", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksEditPost)
m.Post("/dingtalk/:id", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost)
m.Post("/telegram/:id", bindIgnErr(auth.NewTelegramHookForm{}), repo.TelegramHooksEditPost)
m.Post("/matrix/:id", bindIgnErr(auth.NewMatrixHookForm{}), repo.MatrixHooksEditPost)
m.Post("/msteams/:id", bindIgnErr(auth.NewMSTeamsHookForm{}), repo.MSTeamsHooksEditPost)
m.Post("/feishu/:id", bindIgnErr(auth.NewFeishuHookForm{}), repo.FeishuHooksEditPost)
m.Get("/{id}", repo.WebHooksEdit)
m.Post("/gitea/{id}", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
m.Post("/gogs/{id}", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksEditPost)
m.Post("/slack/{id}", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
m.Post("/discord/{id}", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksEditPost)
m.Post("/dingtalk/{id}", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost)
m.Post("/telegram/{id}", bindIgnErr(auth.NewTelegramHookForm{}), repo.TelegramHooksEditPost)
m.Post("/matrix/{id}", bindIgnErr(auth.NewMatrixHookForm{}), repo.MatrixHooksEditPost)
m.Post("/msteams/{id}", bindIgnErr(auth.NewMSTeamsHookForm{}), repo.MSTeamsHooksEditPost)
m.Post("/feishu/{id}", bindIgnErr(auth.NewFeishuHookForm{}), repo.FeishuHooksEditPost)
})
m.Group("/^:configType(default-hooks|system-hooks)$", func() {
m.Get("/:type/new", repo.WebhooksNew)
m.Group("/{configType:default-hooks|system-hooks}", func() {
m.Get("/{type}/new", repo.WebhooksNew)
m.Post("/gitea/new", bindIgnErr(auth.NewWebhookForm{}), repo.GiteaHooksNewPost)
m.Post("/gogs/new", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksNewPost)
m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
@@ -402,9 +460,9 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
m.Group("/auths", func() {
m.Get("", admin.Authentications)
m.Combo("/new").Get(admin.NewAuthSource).Post(bindIgnErr(auth.AuthenticationForm{}), admin.NewAuthSourcePost)
m.Combo("/:authid").Get(admin.EditAuthSource).
m.Combo("/{authid}").Get(admin.EditAuthSource).
Post(bindIgnErr(auth.AuthenticationForm{}), admin.EditAuthSourcePost)
m.Post("/:authid/delete", admin.DeleteAuthSource)
m.Post("/{authid}/delete", admin.DeleteAuthSource)
})
m.Group("/notices", func() {
@@ -416,15 +474,15 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
// ***** END: Admin *****
m.Group("", func() {
m.Get("/:username", user.Profile)
m.Get("/attachments/:uuid", repo.GetAttachment)
m.Get("/{username}", user.Profile)
m.Get("/attachments/{uuid}", repo.GetAttachment)
}, ignSignIn)
m.Group("/:username", func() {
m.Post("/action/:action", user.Action)
m.Group("/{username}", func() {
m.Post("/action/{action}", user.Action)
}, reqSignIn)
if macaron.Env == macaron.DEV {
if !setting.IsProd() {
m.Get("/template/*", dev.TemplatePreview)
}
@@ -449,44 +507,44 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
m.Post("/create", bindIgnErr(auth.CreateOrgForm{}), org.CreatePost)
})
m.Group("/:org", func() {
m.Group("/{org}", func() {
m.Get("/dashboard", user.Dashboard)
m.Get("/dashboard/:team", user.Dashboard)
m.Get("/dashboard/{team}", user.Dashboard)
m.Get("/issues", user.Issues)
m.Get("/issues/:team", user.Issues)
m.Get("/issues/{team}", user.Issues)
m.Get("/pulls", user.Pulls)
m.Get("/pulls/:team", user.Pulls)
m.Get("/pulls/{team}", user.Pulls)
m.Get("/milestones", reqMilestonesDashboardPageEnabled, user.Milestones)
m.Get("/milestones/:team", reqMilestonesDashboardPageEnabled, user.Milestones)
m.Get("/milestones/{team}", reqMilestonesDashboardPageEnabled, user.Milestones)
m.Get("/members", org.Members)
m.Post("/members/action/:action", org.MembersAction)
m.Post("/members/action/{action}", org.MembersAction)
m.Get("/teams", org.Teams)
}, context.OrgAssignment(true, false, true))
m.Group("/:org", func() {
m.Get("/teams/:team", org.TeamMembers)
m.Get("/teams/:team/repositories", org.TeamRepositories)
m.Post("/teams/:team/action/:action", org.TeamsAction)
m.Post("/teams/:team/action/repo/:action", org.TeamsRepoAction)
m.Group("/{org}", func() {
m.Get("/teams/{team}", org.TeamMembers)
m.Get("/teams/{team}/repositories", org.TeamRepositories)
m.Post("/teams/{team}/action/{action}", org.TeamsAction)
m.Post("/teams/{team}/action/repo/{action}", org.TeamsRepoAction)
}, context.OrgAssignment(true, false, true))
m.Group("/:org", func() {
m.Group("/{org}", func() {
m.Get("/teams/new", org.NewTeam)
m.Post("/teams/new", bindIgnErr(auth.CreateTeamForm{}), org.NewTeamPost)
m.Get("/teams/:team/edit", org.EditTeam)
m.Post("/teams/:team/edit", bindIgnErr(auth.CreateTeamForm{}), org.EditTeamPost)
m.Post("/teams/:team/delete", org.DeleteTeam)
m.Get("/teams/{team}/edit", org.EditTeam)
m.Post("/teams/{team}/edit", bindIgnErr(auth.CreateTeamForm{}), org.EditTeamPost)
m.Post("/teams/{team}/delete", org.DeleteTeam)
m.Group("/settings", func() {
m.Combo("").Get(org.Settings).
Post(bindIgnErr(auth.UpdateOrgSettingForm{}), org.SettingsPost)
m.Post("/avatar", binding.MultipartForm(auth.AvatarForm{}), org.SettingsAvatar)
m.Post("/avatar", bindIgnErr(auth.AvatarForm{}), org.SettingsAvatar)
m.Post("/avatar/delete", org.SettingsDeleteAvatar)
m.Group("/hooks", func() {
m.Get("", org.Webhooks)
m.Post("/delete", org.DeleteWebhook)
m.Get("/:type/new", repo.WebhooksNew)
m.Get("/{type}/new", repo.WebhooksNew)
m.Post("/gitea/new", bindIgnErr(auth.NewWebhookForm{}), repo.GiteaHooksNewPost)
m.Post("/gogs/new", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksNewPost)
m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
@@ -496,16 +554,16 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
m.Post("/matrix/new", bindIgnErr(auth.NewMatrixHookForm{}), repo.MatrixHooksNewPost)
m.Post("/msteams/new", bindIgnErr(auth.NewMSTeamsHookForm{}), repo.MSTeamsHooksNewPost)
m.Post("/feishu/new", bindIgnErr(auth.NewFeishuHookForm{}), repo.FeishuHooksNewPost)
m.Get("/:id", repo.WebHooksEdit)
m.Post("/gitea/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
m.Post("/gogs/:id", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksEditPost)
m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
m.Post("/discord/:id", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksEditPost)
m.Post("/dingtalk/:id", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost)
m.Post("/telegram/:id", bindIgnErr(auth.NewTelegramHookForm{}), repo.TelegramHooksEditPost)
m.Post("/matrix/:id", bindIgnErr(auth.NewMatrixHookForm{}), repo.MatrixHooksEditPost)
m.Post("/msteams/:id", bindIgnErr(auth.NewMSTeamsHookForm{}), repo.MSTeamsHooksEditPost)
m.Post("/feishu/:id", bindIgnErr(auth.NewFeishuHookForm{}), repo.FeishuHooksEditPost)
m.Get("/{id}", repo.WebHooksEdit)
m.Post("/gitea/{id}", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
m.Post("/gogs/{id}", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksEditPost)
m.Post("/slack/{id}", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
m.Post("/discord/{id}", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksEditPost)
m.Post("/dingtalk/{id}", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost)
m.Post("/telegram/{id}", bindIgnErr(auth.NewTelegramHookForm{}), repo.TelegramHooksEditPost)
m.Post("/matrix/{id}", bindIgnErr(auth.NewMatrixHookForm{}), repo.MatrixHooksEditPost)
m.Post("/msteams/{id}", bindIgnErr(auth.NewMSTeamsHookForm{}), repo.MSTeamsHooksEditPost)
m.Post("/feishu/{id}", bindIgnErr(auth.NewFeishuHookForm{}), repo.FeishuHooksEditPost)
})
m.Group("/labels", func() {
@@ -529,19 +587,19 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
m.Get("/migrate", repo.Migrate)
m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost)
m.Group("/fork", func() {
m.Combo("/:repoid").Get(repo.Fork).
m.Combo("/{repoid}").Get(repo.Fork).
Post(bindIgnErr(auth.CreateRepoForm{}), repo.ForkPost)
}, context.RepoIDAssignment(), context.UnitTypes(), reqRepoCodeReader)
}, reqSignIn)
// ***** Release Attachment Download without Signin
m.Get("/:username/:reponame/releases/download/:vTag/:fileName", ignSignIn, context.RepoAssignment(), repo.MustBeNotEmpty, repo.RedirectDownload)
m.Get("/{username}/{reponame}/releases/download/{vTag}/{fileName}", ignSignIn, context.RepoAssignment(), repo.MustBeNotEmpty, repo.RedirectDownload)
m.Group("/:username/:reponame", func() {
m.Group("/{username}/{reponame}", func() {
m.Group("/settings", func() {
m.Combo("").Get(repo.Settings).
Post(bindIgnErr(auth.RepoSettingForm{}), repo.SettingsPost)
m.Post("/avatar", binding.MultipartForm(auth.AvatarForm{}), repo.SettingsAvatar)
m.Post("/avatar", bindIgnErr(auth.AvatarForm{}), repo.SettingsAvatar)
m.Post("/avatar/delete", repo.SettingsDeleteAvatar)
m.Group("/collaboration", func() {
@@ -562,7 +620,7 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
m.Group("/hooks", func() {
m.Get("", repo.Webhooks)
m.Post("/delete", repo.DeleteWebhook)
m.Get("/:type/new", repo.WebhooksNew)
m.Get("/{type}/new", repo.WebhooksNew)
m.Post("/gitea/new", bindIgnErr(auth.NewWebhookForm{}), repo.GiteaHooksNewPost)
m.Post("/gogs/new", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksNewPost)
m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
@@ -572,21 +630,21 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
m.Post("/matrix/new", bindIgnErr(auth.NewMatrixHookForm{}), repo.MatrixHooksNewPost)
m.Post("/msteams/new", bindIgnErr(auth.NewMSTeamsHookForm{}), repo.MSTeamsHooksNewPost)
m.Post("/feishu/new", bindIgnErr(auth.NewFeishuHookForm{}), repo.FeishuHooksNewPost)
m.Get("/:id", repo.WebHooksEdit)
m.Post("/:id/test", repo.TestWebhook)
m.Post("/gitea/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
m.Post("/gogs/:id", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksEditPost)
m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
m.Post("/discord/:id", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksEditPost)
m.Post("/dingtalk/:id", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost)
m.Post("/telegram/:id", bindIgnErr(auth.NewTelegramHookForm{}), repo.TelegramHooksEditPost)
m.Post("/matrix/:id", bindIgnErr(auth.NewMatrixHookForm{}), repo.MatrixHooksEditPost)
m.Post("/msteams/:id", bindIgnErr(auth.NewMSTeamsHookForm{}), repo.MSTeamsHooksEditPost)
m.Post("/feishu/:id", bindIgnErr(auth.NewFeishuHookForm{}), repo.FeishuHooksEditPost)
m.Get("/{id}", repo.WebHooksEdit)
m.Post("/{id}/test", repo.TestWebhook)
m.Post("/gitea/{id}", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
m.Post("/gogs/{id}", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksEditPost)
m.Post("/slack/{id}", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
m.Post("/discord/{id}", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksEditPost)
m.Post("/dingtalk/{id}", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost)
m.Post("/telegram/{id}", bindIgnErr(auth.NewTelegramHookForm{}), repo.TelegramHooksEditPost)
m.Post("/matrix/{id}", bindIgnErr(auth.NewMatrixHookForm{}), repo.MatrixHooksEditPost)
m.Post("/msteams/{id}", bindIgnErr(auth.NewMSTeamsHookForm{}), repo.MSTeamsHooksEditPost)
m.Post("/feishu/{id}", bindIgnErr(auth.NewFeishuHookForm{}), repo.FeishuHooksEditPost)
m.Group("/git", func() {
m.Get("", repo.GitHooks)
m.Combo("/:name").Get(repo.GitHooksEdit).
m.Combo("/{name}").Get(repo.GitHooksEdit).
Post(repo.GitHooksEditPost)
}, context.GitHookService())
})
@@ -598,16 +656,16 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
})
m.Group("/lfs", func() {
m.Get("", repo.LFSFiles)
m.Get("/show/:oid", repo.LFSFileGet)
m.Post("/delete/:oid", repo.LFSDelete)
m.Get("/", repo.LFSFiles)
m.Get("/show/{oid}", repo.LFSFileGet)
m.Post("/delete/{oid}", repo.LFSDelete)
m.Get("/pointers", repo.LFSPointerFiles)
m.Post("/pointers/associate", repo.LFSAutoAssociate)
m.Get("/find", repo.LFSFileFind)
m.Group("/locks", func() {
m.Get("/", repo.LFSLocks)
m.Post("/", repo.LFSLockFile)
m.Post("/:lid/unlock", repo.LFSUnlock)
m.Post("/{lid}/unlock", repo.LFSUnlock)
})
})
@@ -617,12 +675,12 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
})
}, reqSignIn, context.RepoAssignment(), context.UnitTypes(), reqRepoAdmin, context.RepoRef())
m.Post("/:username/:reponame/action/:action", reqSignIn, context.RepoAssignment(), context.UnitTypes(), repo.Action)
m.Post("/{username}/{reponame}/action/{action}", reqSignIn, context.RepoAssignment(), context.UnitTypes(), repo.Action)
// Grouping for those endpoints not requiring authentication
m.Group("/:username/:reponame", func() {
m.Group("/{username}/{reponame}", func() {
m.Group("/milestone", func() {
m.Get("/:id", repo.MilestoneIssuesAndPulls)
m.Get("/{id}", repo.MilestoneIssuesAndPulls)
}, reqRepoIssuesOrPullsReader, context.RepoRef())
m.Combo("/compare/*", repo.MustBeNotEmpty, reqRepoCodeReader, repo.SetEditorconfigIfExists).
Get(ignSignIn, repo.SetDiffViewStyle, repo.CompareDiff).
@@ -630,7 +688,7 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
}, context.RepoAssignment(), context.UnitTypes())
// Grouping for those endpoints that do require authentication
m.Group("/:username/:reponame", func() {
m.Group("/{username}/{reponame}", func() {
m.Group("/issues", func() {
m.Group("/new", func() {
m.Combo("").Get(context.RepoRef(), repo.NewIssue).
@@ -641,7 +699,7 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
// FIXME: should use different URLs but mostly same logic for comments of issue and pull reuqest.
// So they can apply their own enable/disable logic on routers.
m.Group("/issues", func() {
m.Group("/:index", func() {
m.Group("/{index}", func() {
m.Post("/title", repo.UpdateIssueTitle)
m.Post("/content", repo.UpdateIssueContent)
m.Post("/watch", repo.IssueWatch)
@@ -658,13 +716,13 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
m.Post("/cancel", repo.CancelStopwatch)
})
})
m.Post("/reactions/:action", bindIgnErr(auth.ReactionForm{}), repo.ChangeIssueReaction)
m.Post("/reactions/{action}", bindIgnErr(auth.ReactionForm{}), repo.ChangeIssueReaction)
m.Post("/lock", reqRepoIssueWriter, bindIgnErr(auth.IssueLockForm{}), repo.LockIssue)
m.Post("/unlock", reqRepoIssueWriter, repo.UnlockIssue)
}, context.RepoMustNotBeArchived())
m.Group("/:index", func() {
m.Group("/{index}", func() {
m.Get("/attachments", repo.GetIssueAttachments)
m.Get("/attachments/:uuid", repo.GetAttachment)
m.Get("/attachments/{uuid}", repo.GetAttachment)
})
m.Post("/labels", reqRepoIssuesOrPullsWriter, repo.UpdateIssueLabel)
@@ -677,12 +735,12 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
m.Post("/attachments", repo.UploadIssueAttachment)
m.Post("/attachments/remove", repo.DeleteAttachment)
}, context.RepoMustNotBeArchived())
m.Group("/comments/:id", func() {
m.Group("/comments/{id}", func() {
m.Post("", repo.UpdateCommentContent)
m.Post("/delete", repo.DeleteComment)
m.Post("/reactions/:action", bindIgnErr(auth.ReactionForm{}), repo.ChangeCommentReaction)
m.Post("/reactions/{action}", bindIgnErr(auth.ReactionForm{}), repo.ChangeCommentReaction)
}, context.RepoMustNotBeArchived())
m.Group("/comments/:id", func() {
m.Group("/comments/{id}", func() {
m.Get("/attachments", repo.GetCommentAttachments)
})
m.Group("/labels", func() {
@@ -694,13 +752,13 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
m.Group("/milestones", func() {
m.Combo("/new").Get(repo.NewMilestone).
Post(bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost)
m.Get("/:id/edit", repo.EditMilestone)
m.Post("/:id/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.EditMilestonePost)
m.Post("/:id/:action", repo.ChangeMilestoneStatus)
m.Get("/{id}/edit", repo.EditMilestone)
m.Post("/{id}/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.EditMilestonePost)
m.Post("/{id}/{action}", repo.ChangeMilestoneStatus)
m.Post("/delete", repo.DeleteMilestone)
}, context.RepoMustNotBeArchived(), reqRepoIssuesOrPullsWriter, context.RepoRef())
m.Group("/pull", func() {
m.Post("/:index/target_branch", repo.UpdatePullRequestTarget)
m.Post("/{index}/target_branch", repo.UpdatePullRequestTarget)
}, context.RepoMustNotBeArchived())
m.Group("", func() {
@@ -723,7 +781,7 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
}, context.RepoMustNotBeArchived(), reqRepoCodeWriter, repo.MustBeNotEmpty)
m.Group("/branches", func() {
m.Group("/_new/", func() {
m.Group("/_new", func() {
m.Post("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.CreateBranch)
m.Post("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.CreateBranch)
m.Post("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.CreateBranch)
@@ -735,14 +793,14 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
}, reqSignIn, context.RepoAssignment(), context.UnitTypes())
// Releases
m.Group("/:username/:reponame", func() {
m.Group("/{username}/{reponame}", func() {
m.Get("/tags", repo.TagsList, repo.MustBeNotEmpty,
reqRepoCodeReader, context.RepoRefByType(context.RepoRefTag))
m.Group("/releases", func() {
m.Get("/", repo.Releases)
m.Get("/tag/*", repo.SingleRelease)
m.Get("/latest", repo.LatestRelease)
m.Get("/attachments/:uuid", repo.GetAttachment)
m.Get("/attachments/{uuid}", repo.GetAttachment)
}, repo.MustBeNotEmpty, reqRepoReleaseReader, context.RepoRefByType(context.RepoRefTag))
m.Group("/releases", func() {
m.Get("/new", repo.NewRelease)
@@ -772,56 +830,57 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
})
}, ignSignIn, context.RepoAssignment(), context.UnitTypes(), reqRepoReleaseReader)
m.Group("/:username/:reponame", func() {
m.Group("/{username}/{reponame}", func() {
m.Post("/topics", repo.TopicsPost)
}, context.RepoAssignment(), context.RepoMustNotBeArchived(), reqRepoAdmin)
m.Group("/:username/:reponame", func() {
m.Group("/{username}/{reponame}", func() {
m.Group("", func() {
m.Get("/^:type(issues|pulls)$", repo.Issues)
m.Get("/^:type(issues|pulls)$/:index", repo.ViewIssue)
m.Get("/labels/", reqRepoIssuesOrPullsReader, repo.RetrieveLabels, repo.Labels)
m.Get("/{type:issues|pulls}", repo.Issues)
m.Get("/{type:issues|pulls}/{index}", repo.ViewIssue)
m.Get("/labels", reqRepoIssuesOrPullsReader, repo.RetrieveLabels, repo.Labels)
m.Get("/milestones", reqRepoIssuesOrPullsReader, repo.Milestones)
}, context.RepoRef())
m.Group("/projects", func() {
m.Get("", repo.Projects)
m.Get("/:id", repo.ViewProject)
m.Get("/{id}", repo.ViewProject)
m.Group("", func() {
m.Get("/new", repo.NewProject)
m.Post("/new", bindIgnErr(auth.CreateProjectForm{}), repo.NewProjectPost)
m.Group("/:id", func() {
m.Group("/{id}", func() {
m.Post("", bindIgnErr(auth.EditProjectBoardTitleForm{}), repo.AddBoardToProjectPost)
m.Post("/delete", repo.DeleteProject)
m.Get("/edit", repo.EditProject)
m.Post("/edit", bindIgnErr(auth.CreateProjectForm{}), repo.EditProjectPost)
m.Post("/^:action(open|close)$", repo.ChangeProjectStatus)
m.Post("/{action:open|close}", repo.ChangeProjectStatus)
m.Group("/:boardID", func() {
m.Group("/{boardID}", func() {
m.Put("", bindIgnErr(auth.EditProjectBoardTitleForm{}), repo.EditProjectBoardTitle)
m.Delete("", repo.DeleteProjectBoard)
m.Post("/default", repo.SetDefaultProjectBoard)
m.Post("/:index", repo.MoveIssueAcrossBoards)
m.Post("/{index}", repo.MoveIssueAcrossBoards)
})
})
}, reqRepoProjectsWriter, context.RepoMustNotBeArchived())
}, reqRepoProjectsReader, repo.MustEnableProjects)
m.Group("/wiki", func() {
m.Get("/?:page", repo.Wiki)
m.Get("/", repo.Wiki)
m.Get("/{page}", repo.Wiki)
m.Get("/_pages", repo.WikiPages)
m.Get("/:page/_revision", repo.WikiRevision)
m.Get("/commit/:sha([a-f0-9]{7,40})$", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.Diff)
m.Get("/commit/:sha([a-f0-9]{7,40})\\.:ext(patch|diff)", repo.RawDiff)
m.Get("/{page}/_revision", repo.WikiRevision)
m.Get("/commit/{sha:[a-f0-9]{7,40}}", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.Diff)
m.Get("/commit/{sha:[a-f0-9]{7,40}}.{:patch|diff}", repo.RawDiff)
m.Group("", func() {
m.Combo("/_new").Get(repo.NewWiki).
Post(bindIgnErr(auth.NewWikiForm{}), repo.NewWikiPost)
m.Combo("/:page/_edit").Get(repo.EditWiki).
m.Combo("/{page}/_edit").Get(repo.EditWiki).
Post(bindIgnErr(auth.NewWikiForm{}), repo.EditWikiPost)
m.Post("/:page/delete", repo.DeleteWikiPagePost)
m.Post("/{page}/delete", repo.DeleteWikiPagePost)
}, context.RepoMustNotBeArchived(), reqSignIn, reqRepoWikiWriter)
}, repo.MustEnableWiki, context.RepoRef(), func(ctx *context.Context) {
ctx.Data["PageIsWiki"] = true
@@ -833,12 +892,12 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
m.Group("/activity", func() {
m.Get("", repo.Activity)
m.Get("/:period", repo.Activity)
m.Get("/{period}", repo.Activity)
}, context.RepoRef(), repo.MustBeNotEmpty, context.RequireRepoReaderOr(models.UnitTypePullRequests, models.UnitTypeIssues, models.UnitTypeReleases))
m.Group("/activity_author_data", func() {
m.Get("", repo.ActivityAuthors)
m.Get("/:period", repo.ActivityAuthors)
m.Get("/{period}", repo.ActivityAuthors)
}, context.RepoRef(), repo.MustBeNotEmpty, context.RequireRepoReaderOr(models.UnitTypeCode))
m.Group("/archive", func() {
@@ -851,10 +910,10 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
}, repo.MustBeNotEmpty, context.RepoRef(), reqRepoCodeReader)
m.Group("/blob_excerpt", func() {
m.Get("/:sha", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.ExcerptBlob)
m.Get("/{sha}", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.ExcerptBlob)
}, repo.MustBeNotEmpty, context.RepoRef(), reqRepoCodeReader)
m.Group("/pulls/:index", func() {
m.Group("/pulls/{index}", func() {
m.Get(".diff", repo.DownloadPullDiff)
m.Get(".patch", repo.DownloadPullPatch)
m.Get("/commits", context.RepoRef(), repo.ViewPullCommits)
@@ -875,7 +934,7 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.SingleDownloadOrLFS)
m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.SingleDownloadOrLFS)
m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.SingleDownloadOrLFS)
m.Get("/blob/:sha", context.RepoRefByType(context.RepoRefBlob), repo.DownloadByIDOrLFS)
m.Get("/blob/{sha}", context.RepoRefByType(context.RepoRefBlob), repo.DownloadByIDOrLFS)
// "/*" route is deprecated, and kept for backward compatibility
m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.SingleDownloadOrLFS)
}, repo.MustBeNotEmpty, reqRepoCodeReader)
@@ -884,7 +943,7 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.SingleDownload)
m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.SingleDownload)
m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.SingleDownload)
m.Get("/blob/:sha", context.RepoRefByType(context.RepoRefBlob), repo.DownloadByID)
m.Get("/blob/{sha}", context.RepoRefByType(context.RepoRefBlob), repo.DownloadByID)
// "/*" route is deprecated, and kept for backward compatibility
m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.SingleDownload)
}, repo.MustBeNotEmpty, reqRepoCodeReader)
@@ -905,7 +964,7 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
m.Group("", func() {
m.Get("/graph", repo.Graph)
m.Get("/commit/:sha([a-f0-9]{7,40})$", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.Diff)
m.Get("/commit/{sha:([a-f0-9]{7,40})$}", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.Diff)
}, repo.MustBeNotEmpty, context.RepoRef(), reqRepoCodeReader)
m.Group("/src", func() {
@@ -919,39 +978,52 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
m.Group("", func() {
m.Get("/forks", repo.Forks)
}, context.RepoRef(), reqRepoCodeReader)
m.Get("/commit/:sha([a-f0-9]{7,40})\\.:ext(patch|diff)",
m.Get("/commit/{sha:([a-f0-9]{7,40})}.{ext:patch|diff}",
repo.MustBeNotEmpty, reqRepoCodeReader, repo.RawDiff)
}, ignSignIn, context.RepoAssignment(), context.UnitTypes())
m.Group("/:username/:reponame", func() {
m.Group("/{username}/{reponame}", func() {
m.Get("/stars", repo.Stars)
m.Get("/watchers", repo.Watchers)
m.Get("/search", reqRepoCodeReader, repo.Search)
}, ignSignIn, context.RepoAssignment(), context.RepoRef(), context.UnitTypes())
m.Group("/:username", func() {
m.Group("/:reponame", func() {
m.Group("/{username}", func() {
m.Group("/{reponame}", func() {
m.Get("", repo.SetEditorconfigIfExists, repo.Home)
m.Get("\\.git$", repo.SetEditorconfigIfExists, repo.Home)
}, ignSignIn, context.RepoAssignment(), context.RepoRef(), context.UnitTypes())
m.Group("/:reponame", func() {
m.Group("\\.git/info/lfs", func() {
m.Group("/{reponame}", func() {
m.Group("/info/lfs", func() {
m.Post("/objects/batch", lfs.BatchHandler)
m.Get("/objects/:oid/:filename", lfs.ObjectOidHandler)
m.Any("/objects/:oid", lfs.ObjectOidHandler)
m.Get("/objects/{oid}/{filename}", lfs.ObjectOidHandler)
m.Any("/objects/{oid}", lfs.ObjectOidHandler)
m.Post("/objects", lfs.PostHandler)
m.Post("/verify", lfs.VerifyHandler)
m.Group("/locks", func() {
m.Get("/", lfs.GetListLockHandler)
m.Post("/", lfs.PostLockHandler)
m.Post("/verify", lfs.VerifyLockHandler)
m.Post("/:lid/unlock", lfs.UnLockHandler)
m.Post("/{lid}/unlock", lfs.UnLockHandler)
})
m.Any("/*", func(ctx *context.Context) {
ctx.NotFound("", nil)
})
}, ignSignInAndCsrf)
m.Any("/*", ignSignInAndCsrf, repo.HTTP)
m.Group("", func() {
m.Post("/git-upload-pack", repo.ServiceUploadPack)
m.Post("/git-receive-pack", repo.ServiceReceivePack)
m.Get("/info/refs", repo.GetInfoRefs)
m.Get("/HEAD", repo.GetTextFile("HEAD"))
m.Get("/objects/info/alternates", repo.GetTextFile("objects/info/alternates"))
m.Get("/objects/info/http-alternates", repo.GetTextFile("objects/info/http-alternates"))
m.Get("/objects/info/packs", repo.GetInfoPacks)
m.Get("/objects/info/{file:[^/]*}", repo.GetTextFile(""))
m.Get("/objects/{head:[0-9a-f]{2}}/{hash:[0-9a-f]{38}}", repo.GetLooseObject)
m.Get("/objects/pack/pack-{file:[0-9a-f]{40}}.pack", repo.GetPackFile)
m.Get("/objects/pack/pack-{file:[0-9a-f]{40}}.idx", repo.GetIdxFile)
}, ignSignInAndCsrf)
m.Head("/tasks/trigger", repo.TriggerTask)
})
})
@@ -964,30 +1036,9 @@ func RegisterMacaronRoutes(m *macaron.Macaron) {
}, reqSignIn)
if setting.API.EnableSwagger {
m.Get("/swagger.v1.json", templates.JSONRenderer(), routers.SwaggerV1Json)
m.Get("/swagger.v1.json", routers.SwaggerV1Json)
}
var handlers []macaron.Handler
if setting.CORSConfig.Enabled {
handlers = append(handlers, cors.CORS(cors.Options{
Scheme: setting.CORSConfig.Scheme,
AllowDomain: setting.CORSConfig.AllowDomain,
AllowSubdomain: setting.CORSConfig.AllowSubdomain,
Methods: setting.CORSConfig.Methods,
MaxAgeSeconds: int(setting.CORSConfig.MaxAge.Seconds()),
AllowCredentials: setting.CORSConfig.AllowCredentials,
}))
}
handlers = append(handlers, ignSignIn)
m.Group("/api", func() {
apiv1.RegisterRoutes(m)
}, handlers...)
m.Group("/api/internal", func() {
// package name internal is ideal but Golang is not allowed, so we use private as package name.
private.RegisterRoutes(m)
})
// Not found handler.
m.NotFound(routers.NotFound)
m.NotFound(web.Wrap(routers.NotFound))
}