Esempio n. 1
0
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)
	})
}
Esempio n. 2
0
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))
}
Esempio n. 3
0
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()
}
Esempio n. 4
0
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
}
Esempio n. 5
0
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
}
Esempio n. 6
0
// 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
}
Esempio n. 7
0
File: app.go Progetto: xtfly/goman
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)
}
Esempio n. 8
0
// 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
}
Esempio n. 9
0
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
}
Esempio n. 10
0
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()
				So(sess.Count(), ShouldEqual, 0)
			})

			resp := httptest.NewRecorder()
			req, err := http.NewRequest("GET", "/", nil)
			So(err, ShouldBeNil)
			m.ServeHTTP(resp, req)
		})
	})
}
Esempio n. 11
0
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)
			})
		})
	})
}
Esempio n. 12
0
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")
	})
}
Esempio n. 13
0
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)
	})
}
Esempio n. 14
0
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()

		// Post using _csrf form value.
		data := url.Values{}
		data.Set("_custom", 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-Custom HTTP header.
		resp = httptest.NewRecorder()
		req, err = http.NewRequest("POST", "/private", nil)
		So(err, ShouldBeNil)

		req.Header.Set("X-Custom", token)
		req.Header.Set("Cookie", cookie)
		m.ServeHTTP(resp, req)

		So(resp.Code, ShouldNotEqual, http.StatusBadRequest)
	})

	Convey("Validate token with custom error func", t, func() {
		m := macaron.New()
		m.Use(session.Sessioner())
		m.Use(Csrfer(Options{
			ErrorFunc: func(w http.ResponseWriter) {
				http.Error(w, "custom error", 422)
			},
		}))

		// 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)

		// Post using _csrf form value.
		data := url.Values{}
		data.Set("_csrf", "invalid")

		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, ShouldEqual, 422)
		So(resp.Body.String(), ShouldEqual, "custom error\n")

		// Post using X-CSRFToken HTTP header.
		resp = httptest.NewRecorder()
		req, err = http.NewRequest("POST", "/private", nil)
		So(err, ShouldBeNil)

		req.Header.Set("X-CSRFToken", "invalid")
		req.Header.Set("Cookie", cookie)
		m.ServeHTTP(resp, req)

		So(resp.Code, ShouldEqual, 422)
		So(resp.Body.String(), ShouldEqual, "custom error\n")
	})
}
Esempio n. 15
0
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)
	})
}