diff --git a/modules/context/api.go b/modules/context/api.go index 0bf4307726e8..6a9c792370f4 100644 --- a/modules/context/api.go +++ b/modules/context/api.go @@ -8,6 +8,8 @@ import ( "fmt" "strings" + "github.com/go-macaron/csrf" + "code.gitea.io/git" "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/base" @@ -97,6 +99,17 @@ func (ctx *APIContext) SetLinkHeader(total, pageSize int) { } } +// RequireCSRF requires a validated a CSRF token +func (ctx *APIContext) RequireCSRF() { + headerToken := ctx.Req.Header.Get(ctx.csrf.GetHeaderName()) + formValueToken := ctx.Req.FormValue(ctx.csrf.GetFormName()) + if len(headerToken) > 0 || len(formValueToken) > 0 { + csrf.Validate(ctx.Context.Context, ctx.csrf) + } else { + ctx.Context.Error(401) + } +} + // APIContexter returns apicontext as macaron middleware func APIContexter() macaron.Handler { return func(c *Context) { diff --git a/public/js/index.js b/public/js/index.js index fad531cc4991..9bde52f97d1e 100644 --- a/public/js/index.js +++ b/public/js/index.js @@ -2590,6 +2590,10 @@ function updateDeadline(deadlineString) { data: JSON.stringify({ 'due_date': realDeadline, }), + headers: { + 'X-Csrf-Token': csrf, + 'X-Remote': true, + }, contentType: 'application/json', type: 'POST', success: function () { diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 23a85759c2f5..3f0e6c1fb994 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -174,11 +174,15 @@ func repoAssignment() macaron.Handler { // Contexter middleware already checks token for user sign in process. func reqToken() macaron.Handler { - return func(ctx *context.Context) { - if true != ctx.Data["IsApiToken"] { - ctx.Error(401) + return func(ctx *context.APIContext) { + if true == ctx.Data["IsApiToken"] { + return + } + if ctx.IsSigned { + ctx.RequireCSRF() return } + ctx.Context.Error(401) } }