本文整理匯總了Golang中github.com/go-macaron/session.Sessioner函數的典型用法代碼示例。如果您正苦於以下問題:Golang Sessioner函數的具體用法?Golang Sessioner怎麽用?Golang Sessioner使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Sessioner函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: Test_GenerateToken
func Test_GenerateToken(t *testing.T) {
Convey("Generate token", t, func() {
m := macaron.New()
m.Use(session.Sessioner())
m.Use(Csrfer())
// Simulate login.
m.Get("/login", func(sess session.Store, x CSRF) {
sess.Set("uid", "123456")
})
// Generate token.
m.Get("/private", func() {})
resp := httptest.NewRecorder()
req, err := http.NewRequest("GET", "/login", nil)
So(err, ShouldBeNil)
m.ServeHTTP(resp, req)
cookie := resp.Header().Get("Set-Cookie")
resp = httptest.NewRecorder()
req, err = http.NewRequest("GET", "/private", nil)
So(err, ShouldBeNil)
req.Header.Set("Cookie", cookie)
m.ServeHTTP(resp, req)
})
}
示例2: main
func main() {
log.Printf("Orbiter %s", APP_VER)
m := macaron.Classic()
m.Use(macaron.Renderer(macaron.RenderOptions{
Funcs: template.NewFuncMap(),
IndentJSON: macaron.Env != macaron.PROD,
}))
m.Use(session.Sessioner())
m.Use(context.Contexter())
bindIgnErr := binding.BindIgnErr
m.Group("", func() {
m.Get("/", routers.Dashboard)
m.Group("/collectors", func() {
m.Get("", routers.Collectors)
m.Combo("/new").Get(routers.NewCollector).
Post(bindIgnErr(routers.NewCollectorForm{}), routers.NewCollectorPost)
m.Group("/:id", func() {
m.Combo("").Get(routers.EditCollector).
Post(bindIgnErr(routers.NewCollectorForm{}), routers.EditCollectorPost)
m.Post("/regenerate_token", routers.RegenerateCollectorSecret)
m.Post("/delete", routers.DeleteCollector)
})
})
m.Group("/applications", func() {
m.Get("", routers.Applications)
m.Combo("/new").Get(routers.NewApplication).
Post(bindIgnErr(routers.NewApplicationForm{}), routers.NewApplicationPost)
m.Group("/:id", func() {
m.Combo("").Get(routers.EditApplication).
Post(bindIgnErr(routers.NewApplicationForm{}), routers.EditApplicationPost)
m.Post("/regenerate_token", routers.RegenerateApplicationSecret)
m.Post("/delete", routers.DeleteApplication)
})
})
m.Group("/webhooks", func() {
m.Get("", routers.Webhooks)
m.Get("/:id", routers.ViewWebhook)
})
m.Get("/config", routers.Config)
}, context.BasicAuth())
m.Post("/hook", routers.Hook)
m.Group("/api", func() {
apiv1.RegisterRoutes(m)
})
listenAddr := fmt.Sprintf("0.0.0.0:%d", setting.HTTPPort)
log.Println("Listening on", listenAddr)
log.Fatal(http.ListenAndServe(listenAddr, m))
}
示例3: main
func main() {
m := macaron.Classic()
m.Use(cache.Cacher())
// m.Use(session.Sessioner())
m.Use(session.Sessioner(session.Options{
Provider: "memory",
ProviderConfig: "",
CookieName: "Kfx",
CookiePath: "/",
Gclifetime: 3600,
Maxlifetime: 3600,
Secure: false,
CookieLifeTime: 0,
Domain: "/",
IDLength: 16,
Section: "session",
}))
m.Use(csrf.Csrfer())
m.Use(captcha.Captchaer(captcha.Options{
// 獲取驗證碼圖片的 URL 前綴,默認為 "/captcha/"
URLPrefix: "/captcha/",
// 表單隱藏元素的 ID 名稱,默認為 "captcha_id"
FieldIdName: "captcha_id",
// 用戶輸入驗證碼值的元素 ID,默認為 "captcha"
FieldCaptchaName: "captcha",
// 驗證字符的個數,默認為 6
ChallengeNums: 6,
// 驗證碼圖片的寬度,默認為 240 像素
Width: 240,
// 驗證碼圖片的高度,默認為 80 像素
Height: 80,
// 驗證碼過期時間,默認為 600 秒
Expiration: 600,
// 用於存儲驗證碼正確值的 Cache 鍵名,默認為 "captcha_"
CachePrefix: "captcha_",
}))
m.Use(renders.Renderer(renders.Options{
Directory: "templates",
Extensions: []string{".html"},
Charset: "UTF-8",
IndentJSON: true,
IndentXML: true,
HTMLContentType: "text/html",
}))
m.Get("/", index.Index)
m.NotFound(func(r renders.Render) {
r.HTML(200, "404.html", map[string]interface{}{"Title": "Home"})
})
m.Run()
}
示例4: App
func App() *macaron.Macaron {
m := macaron.Classic()
DBOpen()
if Config.Development == true {
macaron.Env = "development"
} else {
macaron.Env = "production"
}
m.Use(session.Sessioner())
m.Use(csrf.Csrfer())
m.Use(pongo2.Pongoer(pongo2.Options{
Directory: "templates",
Extensions: []string{".htm"},
}))
// Serve static files from /assets
m.Use(macaron.Static("assets", macaron.StaticOptions{Prefix: "assets"}))
m.Use(func(c *macaron.Context) {
c.Data["SiteTitle"] = Config.SiteTitle
c.Data["Development"] = Config.Development
c.Next()
})
// Routes
m.Get("/favicon.ico", func(c *macaron.Context) {
c.ServeFileContent("favicon.ico")
})
m.Get("/", func(c *macaron.Context) {
c.Redirect("/habits")
})
init := func(x string, r func(m *macaron.Macaron)) { m.Group(x, func() { r(m) }) }
init("/habits", habitsInit)
init("/journal", journalInit)
init("/log", logInit)
return m
}
示例5: newMacaron
func newMacaron() *macaron.Macaron {
m := macaron.New()
m.Use(macaron.Renderer(macaron.RenderOptions{Layout: "layout",
Funcs: []template.FuncMap{{
"markdown": base.Markdown,
"raw": func(s string) template.HTML { return template.HTML(s) },
"momentDiff": func(t time.Time) string {
return since.Since(t)
},
}}}))
/* m.Use(func(c *macaron.Context) {
if strings.HasSuffix(c.Req.URL.Path, ".json") {
color.Green("JSON")
c.Req.Request.URL
c.Req.URL.Path = strings.TrimSuffix(c.Req.URL.Path, ".json")
c.Req.URL.RawPath = strings.TrimSuffix(c.Req.URL.RawPath, ".json")
c.Req.RequestURI = c.Req.URL.RequestURI()
c.Data["json"] = true
}
c.Next()
})*/
m.Use(cache.Cacher())
m.Use(session.Sessioner())
m.Use(csrf.Csrfer())
m.Use(macaron.Static("static"))
m.Use(macaron.Static("data/uploads"))
m.Use(macaron.Static("data/public", macaron.StaticOptions{Prefix: "public"}))
m.Use(i18n.I18n(i18n.Options{
Langs: []string{"en-US", "ru-RU"},
Names: []string{"English", "Русский"},
}))
m.Use(middleware.Contexter())
return m
}
示例6: newMacaron
// newMacaron initializes Macaron instance.
func newMacaron() *macaron.Macaron {
m := macaron.New()
m.Use(macaron.Logger())
m.Use(macaron.Recovery())
m.Use(macaron.Static("public",
macaron.StaticOptions{
SkipLogging: setting.ProdMode,
},
))
m.Use(macaron.Static("raw",
macaron.StaticOptions{
Prefix: "raw",
SkipLogging: setting.ProdMode,
}))
m.Use(pongo2.Pongoer(pongo2.Options{
IndentJSON: !setting.ProdMode,
}))
m.Use(i18n.I18n())
m.Use(session.Sessioner())
m.Use(middleware.Contexter())
return m
}
示例7: main
func main() {
log.Debug("Starting server...")
m := macaron.New()
m.Use(macaron.Logger())
m.Use(macaron.Recovery())
m.Use(cache.Cacher())
m.Use(session.Sessioner(session.Options{CookieName: "s"}))
m.Use(captcha.Captchaer(captcha.Options{Width: 120, Height: 40}))
m.Use(macaron.Static("static", macaron.StaticOptions{Prefix: "/static"}))
m.Use(pongo2.Pongoer())
//m.Use(i18n.I18n(i18n.Options{
// Langs: []string{"en-US", "zh-CN"},
// Names: []string{"English", "簡體中文"},
//}))
m.Use(spider.SpiderFunc())
m.Use(token.Tokener())
boot.BootStrap()
router.Route(m)
m.Run(boot.WebListenIP, boot.WebPort)
}
示例8: newMacaron
// newMacaron initializes Macaron instance.
func newMacaron() *macaron.Macaron {
m := macaron.New()
if !setting.DisableRouterLog {
m.Use(macaron.Logger())
}
m.Use(macaron.Recovery())
if setting.EnableGzip {
m.Use(gzip.Gziper())
}
if setting.Protocol == setting.FCGI {
m.SetURLPrefix(setting.AppSubUrl)
}
m.Use(macaron.Static(
path.Join(setting.StaticRootPath, "public"),
macaron.StaticOptions{
SkipLogging: setting.DisableRouterLog,
},
))
m.Use(macaron.Static(
setting.AvatarUploadPath,
macaron.StaticOptions{
Prefix: "avatars",
SkipLogging: setting.DisableRouterLog,
},
))
m.Use(macaron.Renderer(macaron.RenderOptions{
Directory: path.Join(setting.StaticRootPath, "templates"),
Funcs: []gotmpl.FuncMap{template.Funcs},
IndentJSON: macaron.Env != macaron.PROD,
}))
localeNames, err := bindata.AssetDir("conf/locale")
if err != nil {
log.Fatal(4, "Fail to list locale files: %v", err)
}
localFiles := make(map[string][]byte)
for _, name := range localeNames {
localFiles[name] = bindata.MustAsset("conf/locale/" + name)
}
m.Use(i18n.I18n(i18n.Options{
SubURL: setting.AppSubUrl,
Files: localFiles,
CustomDirectory: path.Join(setting.CustomPath, "conf/locale"),
Langs: setting.Langs,
Names: setting.Names,
DefaultLang: "en-US",
Redirect: true,
}))
m.Use(cache.Cacher(cache.Options{
Adapter: setting.CacheAdapter,
AdapterConfig: setting.CacheConn,
Interval: setting.CacheInternal,
}))
m.Use(captcha.Captchaer(captcha.Options{
SubURL: setting.AppSubUrl,
}))
m.Use(session.Sessioner(setting.SessionConfig))
m.Use(csrf.Csrfer(csrf.Options{
Secret: setting.SecretKey,
SetCookie: true,
Header: "X-Csrf-Token",
CookiePath: setting.AppSubUrl,
}))
m.Use(toolbox.Toolboxer(m, toolbox.Options{
HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{
&toolbox.HealthCheckFuncDesc{
Desc: "Database connection",
Func: models.Ping,
},
},
}))
m.Use(middleware.Contexter())
return m
}
示例9: newMacaron
func newMacaron() *macaron.Macaron {
m := macaron.New()
// DISABLE_ROUTER_LOG: 激活該選項來禁止打印路由日誌
// 判斷是否禁用,如果禁用則引入macaron日誌
if !setting.DisableRouterLog {
m.Use(macaron.Logger())
}
// 引入macaron恢複機製
m.Use(macaron.Recovery())
if setting.Protocol == setting.FCGI {
m.SetURLPrefix(setting.AppSubUrl)
}
// 設定靜態資源路徑
m.Use(macaron.Static(
path.Join(setting.StaticRootPath, "public"),
macaron.StaticOptions{
SkipLogging: setting.DisableRouterLog,
},
))
m.Use(macaron.Static(
setting.AvatarUploadPath,
macaron.StaticOptions{
Prefix: "avatars",
SkipLogging: setting.DisableRouterLog,
},
))
// 設置渲染模板
m.Use(macaron.Renderer(macaron.RenderOptions{
Directory: path.Join(setting.StaticRootPath, "templates"),
AppendDirectories: []string{path.Join(setting.CustomPath, "templates")},
Funcs: template.NewFuncMap(),
IndentJSON: macaron.Env != macaron.PROD,
}))
// 指定國際化目錄
localeNames, err := bindata.AssetDir("conf/locale")
if err != nil {
log.Fatal(4, "Fail to list locale files: %v", err)
}
localFiles := make(map[string][]byte)
for _, name := range localeNames {
localFiles[name] = bindata.MustAsset("conf/locale/" + name)
}
m.Use(i18n.I18n(i18n.Options{
SubURL: setting.AppSubUrl,
Files: localFiles,
CustomDirectory: path.Join(setting.CustomPath, "conf/locale"),
Langs: setting.Langs,
Names: setting.Names,
DefaultLang: "en-US",
Redirect: true,
}))
m.Use(cache.Cacher(cache.Options{
Adapter: setting.CacheAdapter,
AdapterConfig: setting.CacheConn,
Interval: setting.CacheInternal,
}))
m.Use(captcha.Captchaer(captcha.Options{
SubURL: setting.AppSubUrl,
}))
m.Use(session.Sessioner(setting.SessionConfig))
m.Use(csrf.Csrfer(csrf.Options{
Secret: setting.SecretKey,
Cookie: setting.CSRFCookieName,
SetCookie: true,
Header: "X-Csrf-Token",
CookiePath: setting.AppSubUrl,
}))
m.Use(toolbox.Toolboxer(m, toolbox.Options{
HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{
&toolbox.HealthCheckFuncDesc{
Desc: "Database connection",
Func: models.Ping,
},
},
}))
//m.Use(context.Contexter())
return m
}
示例10: Test_PostgresProvider
func Test_PostgresProvider(t *testing.T) {
Convey("Test postgres session provider", t, func() {
opt := session.Options{
Provider: "postgres",
ProviderConfig: "user=jiahuachen dbname=macaron port=5432 sslmode=disable",
}
Convey("Basic operation", func() {
m := macaron.New()
m.Use(session.Sessioner(opt))
m.Get("/", func(ctx *macaron.Context, sess session.Store) {
sess.Set("uname", "unknwon")
})
m.Get("/reg", func(ctx *macaron.Context, sess session.Store) {
raw, err := sess.RegenerateId(ctx)
So(err, ShouldBeNil)
So(raw, ShouldNotBeNil)
uname := raw.Get("uname")
So(uname, ShouldNotBeNil)
So(uname, ShouldEqual, "unknwon")
})
m.Get("/get", func(ctx *macaron.Context, sess session.Store) {
sid := sess.ID()
So(sid, ShouldNotBeEmpty)
raw, err := sess.Read(sid)
So(err, ShouldBeNil)
So(raw, ShouldNotBeNil)
So(raw.Release(), ShouldBeNil)
uname := sess.Get("uname")
So(uname, ShouldNotBeNil)
So(uname, ShouldEqual, "unknwon")
So(sess.Delete("uname"), ShouldBeNil)
So(sess.Get("uname"), ShouldBeNil)
So(sess.Destory(ctx), ShouldBeNil)
})
resp := httptest.NewRecorder()
req, err := http.NewRequest("GET", "/", nil)
So(err, ShouldBeNil)
m.ServeHTTP(resp, req)
cookie := resp.Header().Get("Set-Cookie")
resp = httptest.NewRecorder()
req, err = http.NewRequest("GET", "/reg", nil)
So(err, ShouldBeNil)
req.Header.Set("Cookie", cookie)
m.ServeHTTP(resp, req)
cookie = resp.Header().Get("Set-Cookie")
resp = httptest.NewRecorder()
req, err = http.NewRequest("GET", "/get", nil)
So(err, ShouldBeNil)
req.Header.Set("Cookie", cookie)
m.ServeHTTP(resp, req)
})
Convey("Regenrate empty session", func() {
m := macaron.New()
m.Use(session.Sessioner(opt))
m.Get("/", func(ctx *macaron.Context, sess session.Store) {
raw, err := sess.RegenerateId(ctx)
So(err, ShouldBeNil)
So(raw, ShouldNotBeNil)
So(sess.Destory(ctx), ShouldBeNil)
})
resp := httptest.NewRecorder()
req, err := http.NewRequest("GET", "/", nil)
So(err, ShouldBeNil)
req.Header.Set("Cookie", "MacaronSession=ad2c7e3cbecfcf48; Path=/;")
m.ServeHTTP(resp, req)
})
Convey("GC session", func() {
m := macaron.New()
opt2 := opt
opt2.Gclifetime = 1
m.Use(session.Sessioner(opt2))
m.Get("/", func(sess session.Store) {
sess.Set("uname", "unknwon")
So(sess.ID(), ShouldNotBeEmpty)
uname := sess.Get("uname")
So(uname, ShouldNotBeNil)
So(uname, ShouldEqual, "unknwon")
So(sess.Flush(), ShouldBeNil)
So(sess.Get("uname"), ShouldBeNil)
time.Sleep(2 * time.Second)
sess.GC()
//.........這裏部分代碼省略.........
示例11: Test_LedisProvider
func Test_LedisProvider(t *testing.T) {
Convey("Test nodb session provider", t, func() {
opt := session.Options{
Provider: "nodb",
ProviderConfig: "./tmp.db",
}
Convey("Basic operation", func() {
m := macaron.New()
m.Use(session.Sessioner(opt))
m.Get("/", func(ctx *macaron.Context, sess session.Store) {
sess.Set("uname", "unknwon")
})
m.Get("/reg", func(ctx *macaron.Context, sess session.Store) {
raw, err := sess.RegenerateId(ctx)
So(err, ShouldBeNil)
So(raw, ShouldNotBeNil)
uname := raw.Get("uname")
So(uname, ShouldNotBeNil)
So(uname, ShouldEqual, "unknwon")
})
m.Get("/get", func(ctx *macaron.Context, sess session.Store) {
sid := sess.ID()
So(sid, ShouldNotBeEmpty)
raw, err := sess.Read(sid)
So(err, ShouldBeNil)
So(raw, ShouldNotBeNil)
uname := sess.Get("uname")
So(uname, ShouldNotBeNil)
So(uname, ShouldEqual, "unknwon")
So(sess.Delete("uname"), ShouldBeNil)
So(sess.Get("uname"), ShouldBeNil)
So(sess.Destory(ctx), ShouldBeNil)
})
resp := httptest.NewRecorder()
req, err := http.NewRequest("GET", "/", nil)
So(err, ShouldBeNil)
m.ServeHTTP(resp, req)
cookie := resp.Header().Get("Set-Cookie")
resp = httptest.NewRecorder()
req, err = http.NewRequest("GET", "/reg", nil)
So(err, ShouldBeNil)
req.Header.Set("Cookie", cookie)
m.ServeHTTP(resp, req)
cookie = resp.Header().Get("Set-Cookie")
resp = httptest.NewRecorder()
req, err = http.NewRequest("GET", "/get", nil)
So(err, ShouldBeNil)
req.Header.Set("Cookie", cookie)
m.ServeHTTP(resp, req)
Convey("Regenrate empty session", func() {
m.Get("/empty", func(ctx *macaron.Context, sess session.Store) {
raw, err := sess.RegenerateId(ctx)
So(err, ShouldBeNil)
So(raw, ShouldNotBeNil)
})
resp = httptest.NewRecorder()
req, err = http.NewRequest("GET", "/empty", nil)
So(err, ShouldBeNil)
req.Header.Set("Cookie", "MacaronSession=ad2c7e3cbecfcf486; Path=/;")
m.ServeHTTP(resp, req)
})
})
})
}
示例12: Test_GenerateCookie
func Test_GenerateCookie(t *testing.T) {
Convey("Generate token to Cookie", t, func() {
m := macaron.New()
m.Use(session.Sessioner())
m.Use(Csrfer(Options{
SetCookie: true,
}))
// Simulate login.
m.Get("/login", func(sess session.Store) {
sess.Set("uid", 123456)
})
// Generate cookie.
m.Get("/private", func() {})
resp := httptest.NewRecorder()
req, err := http.NewRequest("GET", "/login", nil)
So(err, ShouldBeNil)
m.ServeHTTP(resp, req)
cookie := resp.Header().Get("Set-Cookie")
resp = httptest.NewRecorder()
req, err = http.NewRequest("GET", "/private", nil)
So(err, ShouldBeNil)
req.Header.Set("Cookie", cookie)
m.ServeHTTP(resp, req)
So(resp.Header().Get("Set-Cookie"), ShouldContainSubstring, "_csrf")
})
Convey("Generate token to custom Cookie", t, func() {
m := macaron.New()
m.Use(session.Sessioner())
m.Use(Csrfer(Options{
Cookie: "custom",
SetCookie: true,
}))
// Simulate login.
m.Get("/login", func(sess session.Store) {
sess.Set("uid", int64(123456))
})
// Generate cookie.
m.Get("/private", func() {})
resp := httptest.NewRecorder()
req, err := http.NewRequest("GET", "/login", nil)
So(err, ShouldBeNil)
m.ServeHTTP(resp, req)
cookie := resp.Header().Get("Set-Cookie")
resp = httptest.NewRecorder()
req, err = http.NewRequest("GET", "/private", nil)
So(err, ShouldBeNil)
req.Header.Set("Cookie", cookie)
m.ServeHTTP(resp, req)
So(resp.Header().Get("Set-Cookie"), ShouldContainSubstring, "custom")
})
}
示例13: Test_Invalid
func Test_Invalid(t *testing.T) {
Convey("Invalid session data type", t, func() {
m := macaron.New()
m.Use(session.Sessioner())
m.Use(Csrfer())
// Simulate login.
m.Get("/login", func(sess session.Store, x CSRF) {
sess.Set("uid", true)
})
// Generate token.
m.Get("/private", func() {})
resp := httptest.NewRecorder()
req, err := http.NewRequest("GET", "/login", nil)
So(err, ShouldBeNil)
m.ServeHTTP(resp, req)
cookie := resp.Header().Get("Set-Cookie")
resp = httptest.NewRecorder()
req, err = http.NewRequest("GET", "/private", nil)
So(err, ShouldBeNil)
req.Header.Set("Cookie", cookie)
m.ServeHTTP(resp, req)
})
Convey("Invalid request", t, func() {
m := macaron.New()
m.Use(session.Sessioner())
m.Use(Csrfer())
// Simulate login.
m.Get("/login", Validate, func() {})
resp := httptest.NewRecorder()
req, err := http.NewRequest("GET", "/login", nil)
So(err, ShouldBeNil)
m.ServeHTTP(resp, req)
So(resp.Code, ShouldEqual, http.StatusBadRequest)
})
Convey("Invalid token", t, func() {
m := macaron.New()
m.Use(session.Sessioner())
m.Use(Csrfer())
// Simulate login.
m.Get("/login", Validate, func() {})
resp := httptest.NewRecorder()
req, err := http.NewRequest("GET", "/login", nil)
So(err, ShouldBeNil)
req.Header.Set("X-CSRFToken", "invalid")
m.ServeHTTP(resp, req)
So(resp.Code, ShouldEqual, http.StatusBadRequest)
})
}
示例14: Test_Validate
func Test_Validate(t *testing.T) {
Convey("Validate token", t, func() {
m := macaron.New()
m.Use(session.Sessioner())
m.Use(Csrfer())
// Simulate login.
m.Get("/login", func(sess session.Store) {
sess.Set("uid", 123456)
})
// Generate token.
m.Get("/private", func(x CSRF) string {
return x.GetToken()
})
m.Post("/private", Validate, func() {})
// Login to set session.
resp := httptest.NewRecorder()
req, err := http.NewRequest("GET", "/login", nil)
So(err, ShouldBeNil)
m.ServeHTTP(resp, req)
cookie := resp.Header().Get("Set-Cookie")
// Get a new token.
resp = httptest.NewRecorder()
req, err = http.NewRequest("GET", "/private", nil)
So(err, ShouldBeNil)
req.Header.Set("Cookie", cookie)
m.ServeHTTP(resp, req)
token := resp.Body.String()
// Post using _csrf form value.
data := url.Values{}
data.Set("_csrf", token)
resp = httptest.NewRecorder()
req, err = http.NewRequest("POST", "/private", bytes.NewBufferString(data.Encode()))
So(err, ShouldBeNil)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Content-Length", com.ToStr(len(data.Encode())))
req.Header.Set("Cookie", cookie)
m.ServeHTTP(resp, req)
So(resp.Code, ShouldNotEqual, http.StatusBadRequest)
// Post using X-CSRFToken HTTP header.
resp = httptest.NewRecorder()
req, err = http.NewRequest("POST", "/private", nil)
So(err, ShouldBeNil)
req.Header.Set("X-CSRFToken", token)
req.Header.Set("Cookie", cookie)
m.ServeHTTP(resp, req)
So(resp.Code, ShouldNotEqual, http.StatusBadRequest)
})
Convey("Validate custom token", t, func() {
m := macaron.New()
m.Use(session.Sessioner())
m.Use(Csrfer(Options{
Header: "X-Custom",
Form: "_custom",
}))
// Simulate login.
m.Get("/login", func(sess session.Store) {
sess.Set("uid", 123456)
})
// Generate token.
m.Get("/private", func(x CSRF) string {
return x.GetToken()
})
m.Post("/private", Validate, func() {})
// Login to set session.
resp := httptest.NewRecorder()
req, err := http.NewRequest("GET", "/login", nil)
So(err, ShouldBeNil)
m.ServeHTTP(resp, req)
cookie := resp.Header().Get("Set-Cookie")
// Get a new token.
resp = httptest.NewRecorder()
req, err = http.NewRequest("GET", "/private", nil)
So(err, ShouldBeNil)
req.Header.Set("Cookie", cookie)
m.ServeHTTP(resp, req)
token := resp.Body.String()
//.........這裏部分代碼省略.........
示例15: Test_GenerateHeader
func Test_GenerateHeader(t *testing.T) {
Convey("Generate token to header", t, func() {
m := macaron.New()
m.Use(session.Sessioner())
m.Use(Csrfer(Options{
SetHeader: true,
}))
// Simulate login.
m.Get("/login", func(sess session.Store) {
sess.Set("uid", "123456")
})
// Generate HTTP header.
m.Get("/private", func() {})
resp := httptest.NewRecorder()
req, err := http.NewRequest("GET", "/login", nil)
So(err, ShouldBeNil)
m.ServeHTTP(resp, req)
cookie := resp.Header().Get("Set-Cookie")
resp = httptest.NewRecorder()
req, err = http.NewRequest("GET", "/private", nil)
So(err, ShouldBeNil)
req.Header.Set("Cookie", cookie)
m.ServeHTTP(resp, req)
So(resp.Header().Get("X-CSRFToken"), ShouldNotBeEmpty)
})
Convey("Generate token to header with origin", t, func() {
m := macaron.New()
m.Use(session.Sessioner())
m.Use(Csrfer(Options{
SetHeader: true,
Origin: true,
}))
// Simulate login.
m.Get("/login", func(sess session.Store) {
sess.Set("uid", "123456")
})
// Generate HTTP header.
m.Get("/private", func() {})
resp := httptest.NewRecorder()
req, err := http.NewRequest("GET", "/login", nil)
So(err, ShouldBeNil)
m.ServeHTTP(resp, req)
cookie := resp.Header().Get("Set-Cookie")
resp = httptest.NewRecorder()
req, err = http.NewRequest("GET", "/private", nil)
So(err, ShouldBeNil)
req.Header.Set("Cookie", cookie)
req.Header.Set("Origin", "https://www.example.com")
m.ServeHTTP(resp, req)
So(resp.Header().Get("X-CSRFToken"), ShouldBeEmpty)
})
Convey("Generate token to custom header", t, func() {
m := macaron.New()
m.Use(session.Sessioner())
m.Use(Csrfer(Options{
Header: "X-Custom",
SetHeader: true,
}))
// Simulate login.
m.Get("/login", func(sess session.Store) {
sess.Set("uid", "123456")
})
// Generate HTTP header.
m.Get("/private", func() {})
resp := httptest.NewRecorder()
req, err := http.NewRequest("GET", "/login", nil)
So(err, ShouldBeNil)
m.ServeHTTP(resp, req)
cookie := resp.Header().Get("Set-Cookie")
resp = httptest.NewRecorder()
req, err = http.NewRequest("GET", "/private", nil)
So(err, ShouldBeNil)
req.Header.Set("Cookie", cookie)
m.ServeHTTP(resp, req)
So(resp.Header().Get("X-Custom"), ShouldNotBeEmpty)
})
}