From 34ddcef1dc16f49c3d8fd3453e3d332c31e7f54c Mon Sep 17 00:00:00 2001 From: astaxie Date: Sat, 17 May 2014 00:12:25 +0800 Subject: [PATCH] beego: XSRF support Controller level fix #610 default value is true when you Enable Global XSRF, also can control in the prepare function to change the value. --- controller.go | 5 +++++ router.go | 6 +++--- templatefunc.go | 7 ++++++- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/controller.go b/controller.go index 13acbbff..7098c1b5 100644 --- a/controller.go +++ b/controller.go @@ -47,6 +47,7 @@ type Controller struct { XSRFExpire int AppController interface{} EnableRender bool + EnableXSRF bool } // ControllerInterface is an interface to uniform all controller handler. @@ -76,6 +77,7 @@ func (c *Controller) Init(ctx *context.Context, controllerName, actionName strin c.TplExt = "tpl" c.AppController = app c.EnableRender = true + c.EnableXSRF = true c.Data = ctx.Input.Data } @@ -441,6 +443,9 @@ func (c *Controller) XsrfToken() string { // the token can provided in request header "X-Xsrftoken" and "X-CsrfToken" // or in form field value named as "_xsrf". func (c *Controller) CheckXsrfCookie() bool { + if !c.EnableXSRF { + return true + } token := c.GetString("_xsrf") if token == "" { token = c.Ctx.Request.Header.Get("X-Xsrftoken") diff --git a/router.go b/router.go index 3d6c1664..9220234f 100644 --- a/router.go +++ b/router.go @@ -906,6 +906,9 @@ func (p *ControllerRegistor) ServeHTTP(rw http.ResponseWriter, r *http.Request) //call the controller init function execController.Init(context, runrouter.Name(), runMethod, vc.Interface()) + //call prepare function + execController.Prepare() + //if XSRF is Enable then check cookie where there has any cookie in the request's cookie _csrf if EnableXSRF { execController.XsrfToken() @@ -915,9 +918,6 @@ func (p *ControllerRegistor) ServeHTTP(rw http.ResponseWriter, r *http.Request) } } - //call prepare function - execController.Prepare() - if !w.started { //exec main logic switch runMethod { diff --git a/templatefunc.go b/templatefunc.go index c7bd9238..62584781 100644 --- a/templatefunc.go +++ b/templatefunc.go @@ -186,16 +186,21 @@ func Htmlunquote(src string) string { // UrlFor returns url string with another registered controller handler with params. // usage: +// // UrlFor(".index") // print UrlFor("index") +// router /login // print UrlFor("login") // print UrlFor("login", "next","/"") -// print UrlFor("profile", "username","John Doe") +// router /profile/:username +// print UrlFor("profile", ":username","John Doe") // result: // / // /login // /login?next=/ // /user/John%20Doe +// +// more detail http://beego.me/docs/mvc/controller/urlbuilding.md func UrlFor(endpoint string, values ...string) string { return BeeApp.UrlFor(endpoint, values...) }