コード例 #1
0
ファイル: csrf_test.go プロジェクト: macaron-contrib/csrf
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
0
ファイル: main.go プロジェクト: zileyuan/hidog
func newInstance() *macaron.Macaron {
	m := macaron.New()
	m.Use(macaron.Logger())
	m.Use(macaron.Recovery())
	m.Use(macaron.Static("static"))
	m.Use(pongo2.Pongoer(pongo2.Options{
		Directory:  "views",
		IndentJSON: macaron.Env != macaron.PROD,
		IndentXML:  macaron.Env != macaron.PROD,
	}))
	m.Use(cache.Cacher())
	m.Use(session.Sessioner())

	//DoXXX 表示GET请求;
	//OnXXX 表示POST请求;
	//AnyXXX 表示GET、POST混合请求
	m.Any("/", AnyValidate)

	m.Get("/dogs", DoDogs)
	m.Get("/pups", DoPups)
	m.Get("/about", DoAbout)
	m.Get("/comment", DoComment)
	m.Get("/signin", DoSignin)
	m.Get("/dogDetail", DoDogDetail)
	m.Get("/pupDetail", DoPupDetail)

	m.Post("/onComment", OnComment)
	m.Post("/onSignin", OnSignin)
	return m
}
コード例 #3
0
ファイル: web.go プロジェクト: ericcapricorn/gogs
// newMacaron initializes Macaron instance.
func newMacaron() *macaron.Macaron {
	m := macaron.New()
	m.Use(macaron.Logger())
	m.Use(macaron.Recovery())
	if setting.EnableGzip {
		m.Use(macaron.Gziper())
	}
	m.Use(macaron.Static(
		path.Join(setting.StaticRootPath, "public"),
		macaron.StaticOptions{
			SkipLogging: !setting.DisableRouterLog,
		},
	))
	m.Use(macaron.Renderer(macaron.RenderOptions{
		Directory:  path.Join(setting.StaticRootPath, "templates"),
		Funcs:      []template.FuncMap{base.TemplateFuncs},
		IndentJSON: macaron.Env != macaron.PROD,
	}))
	m.Use(i18n.I18n(i18n.Options{
		SubURL:          setting.AppSubUrl,
		Directory:       path.Join(setting.ConfRootPath, "locale"),
		CustomDirectory: path.Join(setting.CustomPath, "conf/locale"),
		Langs:           setting.Langs,
		Names:           setting.Names,
		Redirect:        true,
	}))
	m.Use(cache.Cacher(cache.Options{
		Adapter:  setting.CacheAdapter,
		Interval: setting.CacheInternal,
		Conn:     setting.CacheConn,
	}))
	m.Use(captcha.Captchaer(captcha.Options{
		SubURL: setting.AppSubUrl,
	}))
	m.Use(session.Sessioner(session.Options{
		Provider: setting.SessionProvider,
		Config:   *setting.SessionConfig,
	}))
	m.Use(csrf.Generate(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
}
コード例 #4
0
ファイル: go_cas_client.go プロジェクト: henryluki/cas
func main() {
	server_root := "https://nicksite.com:3000"
	local_login_url := "http://nicksite.com:4000/login"

	m := macaron.Classic()
	m.Use(macaron.Renderer())
	m.Use(session.Sessioner())

	m.Get("/login", func(ctx *macaron.Context, s session.Store) {
		ticket := ctx.Query("ticket")
		if len(ticket) == 0 {
			ctx.Redirect(server_root + "/login?service=" + local_login_url)
			return
		} else {
			s.Set("ticket", ticket)
			ctx.Redirect("/")
		}
	})

	m.Get("/", func(ctx *macaron.Context, s session.Store) string {
		if s.Get("login") != nil {
			return "Welcome, " + s.Get("login").(string)
		}

		// Retrieve the ticket
		if s.Get("ticket") == nil {
			ctx.Redirect("/login")
			return ""
		}

		// Validate the ticket
		ticket := s.Get("ticket").(string)
		resp, err := http.Get(server_root + "/validate?ticket=" + ticket + "&service=" + local_login_url)

		if err != nil {
			log.Fatalf("ERROR: %s\n", err)
			return "Unable to validate the ticket"
		}

		bs, _ := ioutil.ReadAll(resp.Body)
		split := strings.Split(string(bs), "\n")
		ticketValid, login := split[0] == "yes", split[1]

		if ticketValid {
			s.Set("login", login)
			ctx.Redirect("/")
			return ""
		}

		return "Invalid login"
	})

	m.Run()
}
コード例 #5
0
ファイル: main.go プロジェクト: trigrass2/tech_oa
func newMacaron() *macaron.Macaron {
	m := macaron.New()
	m.Use(macaron.Logger())
	m.Use(macaron.Recovery())
	m.Use(macaron.Static("static"))
	m.Use(session.Sessioner(session.Options{
		Provider:       "mysql",
		ProviderConfig: beego.AppConfig.String("mysqlstring"),
	}))
	m.Use(middleware.Contexter())
	m.Use(pongo2.Pongoer(pongo2.Options{
		Directory: "views",
	}))
	return m

}
コード例 #6
0
ファイル: gowalker.go プロジェクト: fanbuchi/gowalker
// 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
0
ファイル: csrf_test.go プロジェクト: macaron-contrib/csrf
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)
	})
}
コード例 #8
0
ファイル: csrf_test.go プロジェクト: macaron-contrib/csrf
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")
	})
}
コード例 #9
0
ファイル: csrf_test.go プロジェクト: macaron-contrib/csrf
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")
	})
}
コード例 #10
0
ファイル: main.go プロジェクト: james2doyle/macaron-example
func main() {
	// initiate the app
	m := macaron.Classic()

	// register middleware
	m.Use(macaron.Recovery())
	m.Use(macaron.Gziper())
	m.Use(macaron.Static("public",
		macaron.StaticOptions{
			// Prefix is the optional prefix used to serve the static directory content. Default is empty string.
			Prefix: "public",
			// SkipLogging will disable [Static] log messages when a static file is served. Default is false.
			SkipLogging: true,
			// IndexFile defines which file to serve as index if it exists. Default is "index.html".
			IndexFile: "index.html",
			// Expires defines which user-defined function to use for producing a HTTP Expires Header. Default is nil.
			// https://developers.google.com/speed/docs/insights/LeverageBrowserCaching
			Expires: func() string { return "max-age=0" },
		}))
	m.Use(session.Sessioner(session.Options{
		// Name of provider. Default is "memory".
		Provider: "memory",
		// Provider configuration, it's corresponding to provider.
		ProviderConfig: "",
		// Cookie name to save session ID. Default is "MacaronSession".
		CookieName: "MacaronSession",
		// Cookie path to store. Default is "/".
		CookiePath: "/",
		// GC interval time in seconds. Default is 3600.
		Gclifetime: 3600,
		// Max life time in seconds. Default is whatever GC interval time is.
		Maxlifetime: 3600,
		// Use HTTPS only. Default is false.
		Secure: false,
		// Cookie life time. Default is 0.
		CookieLifeTime: 0,
		// Cookie domain name. Default is empty.
		Domain: "",
		// Session ID length. Default is 16.
		IDLength: 16,
		// Configuration section name. Default is "session".
		Section: "session",
	}))
	m.Use(macaron.Renderer(macaron.RenderOptions{
		// Directory to load templates. Default is "templates".
		Directory: "templates",
		// Extensions to parse template files from. Defaults are [".tmpl", ".html"].
		Extensions: []string{".tmpl", ".html"},
		// Funcs is a slice of FuncMaps to apply to the template upon compilation. Default is [].
		Funcs: []template.FuncMap{map[string]interface{}{
			"AppName": func() string {
				return "Macaron"
			},
			"AppVer": func() string {
				return "1.0.0"
			},
		}},
		// Delims sets the action delimiters to the specified strings. Defaults are ["{{", "}}"].
		Delims: macaron.Delims{"{{", "}}"},
		// Appends the given charset to the Content-Type header. Default is "UTF-8".
		Charset: "UTF-8",
		// Outputs human readable JSON. Default is false.
		IndentJSON: true,
		// Outputs human readable XML. Default is false.
		IndentXML: true,
		// Prefixes the JSON output with the given bytes. Default is no prefix.
		// PrefixJSON: []byte("macaron"),
		// Prefixes the XML output with the given bytes. Default is no prefix.
		// PrefixXML: []byte("macaron"),
		// Allows changing of output to XHTML instead of HTML. Default is "text/html".
		HTMLContentType: "text/html",
	}))
	m.Use(cache.Cacher(cache.Options{
		// Name of adapter. Default is "memory".
		Adapter: "memory",
		// Adapter configuration, it's corresponding to adapter.
		AdapterConfig: "",
		// GC interval time in seconds. Default is 60.
		Interval: 60,
		// Configuration section name. Default is "cache".
		Section: "cache",
	}))

	// setup handlers
	m.Get("/", myHandler)
	m.Get("/welcome", myOtherHandler)
	m.Get("/query", myQueryStringHandler) // /query?name=Some+Name
	m.Get("/json", myJsonHandler)
	m.Post("/contact/submit", binding.Bind(ContactForm{}), mySubmitHandler)
	m.Get("/session", mySessionHandler)
	m.Get("/set/cookie/:value", mySetCookieHandler)
	m.Get("/get/cookie", myGetCookieHandler)
	m.Get("/database", myDatabaseHandler)
	m.Get("/database/list", myDatabaseListHandler)
	m.Get("/cache/write/:key/:value", myCacheWriteHandler)
	m.Get("/cache/read/:key", myCacheReadHandler)

	log.Println("Server is running on localhost:4000...")
	log.Println(http.ListenAndServe("0.0.0.0:4000", m))
}
コード例 #11
0
func main() {
	initParse()

	err := readConfig("service.conf", &c.Config)
	if err != nil {
		glog.V(1).Infof("Read Configure file fail:%#v", err)
		return
	}

	initDB(c.Config)

	m := macaron.Classic()
	macaron.Env = macaron.PROD
	m.Use(macaron.Renderer())
	m.Use(session.Sessioner(session.Options{
		Provider:       "redis",
		ProviderConfig: "addr=127.0.0.1:6379",
	}))

	m.Use(macaron.Static("public",
		macaron.StaticOptions{
			// 请求静态资源时的 URL 前缀,默认没有前缀
			Prefix: "public",
			// 禁止记录静态资源路由日志,默认为不禁止记录
			SkipLogging: true,
			// 当请求目录时的默认索引文件,默认为 "index.html"
			IndexFile: "index.html",
			// 用于返回自定义过期响应头,不能为不设置
			// https://developers.google.com/speed/docs/insights/LeverageBrowserCaching
			Expires: func() string {
				return time.Now().Add(24 * 60 * time.Minute).UTC().Format("Mon, 02 Jan 2006 15:04:05 GMT")
			},
		}))

	m.Use(macaron.Renderer(macaron.RenderOptions{
		// 模板文件目录,默认为 "templates"
		Directory: "templates",
		// 模板文件后缀,默认为 [".tmpl", ".html"]
		Extensions: []string{".tmpl", ".html"},
		// 模板函数,默认为 []
		Funcs: []template.FuncMap{map[string]interface{}{
			"AppName": func() string {
				return "Macaron"
			},
			"AppVer": func() string {
				return "1.0.0"
			},
		}},
		// 模板语法分隔符,默认为 ["{{", "}}"]
		Delims: macaron.Delims{"{{", "}}"},
		// 追加的 Content-Type 头信息,默认为 "UTF-8"
		Charset: "UTF-8",
		// 渲染具有缩进格式的 JSON,默认为不缩进
		IndentJSON: true,
		// 渲染具有缩进格式的 XML,默认为不缩进
		IndentXML: true,
		// 渲染具有前缀的 JSON,默认为无前缀
		PrefixJSON: []byte(""),
		// 渲染具有前缀的 XML,默认为无前缀
		PrefixXML: []byte(""),
		// 允许输出格式为 XHTML 而不是 HTML,默认为 "text/html"
		HTMLContentType: "text/html",
	}))
	m.Map(x)
	m.SetDefaultCookieSecret("UYCNJSHA123JCN409")
	//	m.Post("/login",controller.Login)
	//	m.Get("/logout",controller.Logout)

	m.Group("/users", func() {
		m.Post("", binding.Bind(Customer{}), controller.PostCustomer)
		m.Get("", controller.GetCustomers)
	})

	m.Group("/goods", func() {
		m.Post("", binding.Bind(Goods{}), controller.PostGood)
		m.Get("", controller.GetGoods)
	})

	m.Group("/orders", func() {
		m.Post("/alipay", binding.Bind(Order{}), controller.PostOrder)
		m.Get("", controller.GetOrders)
	})

	m.Group("/alipay", func() {
		m.Post("/notify", controller.AlipayNotify)
		m.Get("/return", controller.AlipayReturn)
	})

	m.Run(8080)
}
コード例 #12
0
ファイル: csrf_test.go プロジェクト: macaron-contrib/csrf
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)
	})
}
コード例 #13
0
ファイル: ledis_test.go プロジェクト: mbrukman/grafana
func Test_LedisProvider(t *testing.T) {
	Convey("Test ledis session provider", t, func() {
		opt := session.Options{
			Provider:       "ledis",
			ProviderConfig: "data_dir=./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)
			})
		})
	})
}
コード例 #14
0
ファイル: web.go プロジェクト: peterhadlaw/gogs
// 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(macaron.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:      []template.FuncMap{base.TemplateFuncs},
		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,
		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,
			},
		},
	}))

	// OAuth 2.
	if setting.OauthService != nil {
		for _, info := range setting.OauthService.OauthInfos {
			m.Use(oauth2.NewOAuth2Provider(info.Options, info.AuthUrl, info.TokenUrl))
		}
	}
	m.Use(middleware.Contexter())
	return m
}
コード例 #15
0
ファイル: main.go プロジェクト: gobuild/gobuild
func InitApp() *macaron.Macaron {
	app := macaron.Classic()
	app.Use(macaron.Static("public"))
	app.Use(session.Sessioner())
	app.Use(oauth2.Github(
		&goauth2.Config{
			ClientID:     os.Getenv("GITHUB_CLIENT_ID"),
			ClientSecret: os.Getenv("GITHUB_CLIENT_SECRET"),
			// https://developer.github.com/v3/oauth/#scopes
			Scopes:      []string{"user:email", "public_repo", "write:repo_hook"},
			RedirectURL: "",
		},
	))

	app.Use(macaron.Renderer(macaron.RenderOptions{
		Delims: macaron.Delims{"{[", "]}"},
	}))

	app.Get("/", routers.Homepage)
	app.Get("/build", oauth2.LoginRequired, routers.Build)
	app.Post("/stats/:org/:name/:branch/:os/:arch", routers.DownloadStats)

	app.Get("/:org/:name", func(ctx *macaron.Context, r *http.Request) {
		org := ctx.Params(":org")
		//name := ctx.Params(":name")
		if org == "js" {
			ctx.Next()
			return
		}
		ctx.Redirect(r.RequestURI+"/"+"master", 302)
	})

	// api
	app.Group("/api", func() {
		app.Get("/repos", api.RepoList)
		app.Post("/repos", api.AnonymousTriggerBuild)
		app.Any("/user/repos", oauth2.LoginRequired, middleware.UserNeeded, api.UserRepoList)
		app.Get("/recent/repos", api.RecentBuild)
		app.Post("/builds", oauth2.LoginRequired, api.TriggerBuild)

		// accept PUT(callback), POST(trigger build)
		app.Any("/repos/:id/build", oauth2.LoginRequired, middleware.UserNeeded, api.RepoBuild)
		app.Get("/user", oauth2.LoginRequired, middleware.UserNeeded, api.UserInfo)
	})

	app.Get("/explore", func(ctx *macaron.Context) {
		ctx.HTML(200, "explore", nil)
	})
	app.Get("/repos", func(ctx *macaron.Context) {
		ctx.HTML(200, "repos", nil)
	})

	app.Get("/:org/:name/:branch", func(ctx *macaron.Context, r *http.Request) {
		org := ctx.Params(":org")
		name := ctx.Params(":name")
		branch := ctx.Params(":branch")

		// Here need redis connection
		repoPath := org + "/" + name
		domain := "dn-gobuild5.qbox.me"
		buildJson := fmt.Sprintf("//%s/gorelease/%s/%s/%s/%s", domain, org, name, branch, "builds.json")

		ctx.Data["DlCount"], _ = rdx.Get("downloads:" + repoPath).Int64()
		ctx.Data["Org"] = org
		ctx.Data["Name"] = name
		ctx.Data["Branch"] = branch
		ctx.Data["BuildJSON"] = template.URL(buildJson)
		prepo := &Repo{
			Domain: domain,
			Org:    org,
			Name:   name,
			Branch: branch,
			Ext:    "",
		}
		pubs := make([]*Publish, 0)
		pubs = append(pubs, prepo.Pub("darwin", "amd64"))
		pubs = append(pubs, prepo.Pub("linux", "amd64"))
		pubs = append(pubs, prepo.Pub("linux", "386"))
		pubs = append(pubs, prepo.Pub("linux", "arm"))
		pubs = append(pubs, prepo.Pub("windows", "amd64"))
		pubs = append(pubs, prepo.Pub("windows", "386"))
		ctx.Data["Pubs"] = pubs
		ctx.HTML(200, "release")
	})
	return app
}
コード例 #16
0
ファイル: switch.go プロジェクト: harryyeh/switch
func main() {
	log.Info("%s %s", setting.AppName, APP_VER)
	log.Info("Run Mode: %s", strings.Title(macaron.Env))

	m := macaron.New()
	m.Use(macaron.Logger())
	m.Use(macaron.Recovery())
	m.Use(macaron.Static("public", macaron.StaticOptions{
		SkipLogging: true,
	}))
	m.Use(pongo2.Pongoers(pongo2.Options{
		Directory:  "templates/web",
		IndentJSON: macaron.Env != macaron.PROD,
	}, "templates/admin"))
	m.Use(i18n.I18n())
	m.Use(session.Sessioner())
	m.Use(middleware.Contexter())

	// Routes.
	m.Get("/", routers.Home)
	m.Route("/download", "GET,POST", routers.Download)
	m.Get("/favicon.ico", func(ctx *middleware.Context) {
		ctx.Redirect("/img/favicon.png")
	})
	// m.Get("/search", routers.Search)
	// m.Get("/about", routers.About)

	// Package.
	m.Get("/*", routers.Package)
	m.Get("/badge/*", routers.Badge)

	// Admin.
	m.Post("/admin/auth", admin.AuthPost)
	m.Group("/admin", func() {
		m.Get("", admin.Dashboard)

		m.Group("/packages", func() {
			m.Get("", admin.Revisions)
			m.Get("/larges", admin.LargeRevisions)
		})

		m.Group("/blocks", func() {
			m.Get("", admin.Blocks)
			m.Combo("/new").Get(admin.BlockPackage).Post(admin.BlockPackagePost)
			m.Get("/:id:int/delete", admin.UnblockPackage)

			m.Group("/rules", func() {
				m.Get("", admin.BlockRules)
				m.Combo("/new").Get(admin.NewBlockRule).Post(admin.NewBlockRulePost)
				m.Get("/:id:int/run", admin.RunRule)
				m.Get("/:id:int/delete", admin.DeleteBlockRule)
			})
		})
	}, admin.Auth)

	// API.
	m.Group("/api", func() {
		m.Group("/v1", func() {
			m.Group("", func() {
				m.Get("/download", v1.Download)
				m.Get("/revision", v1.GetRevision)
			}, v1.PackageFilter())
		})
	})

	// Robots.txt
	m.Get("/robots.txt", func() string {
		return `User-agent: *
Disallow: /api/
Disallow: /download`
	})

	m.NotFound(routers.NotFound)

	listenAddr := fmt.Sprintf("0.0.0.0:%d", setting.HttpPort)
	log.Info("Listen: http://%s", listenAddr)
	if err := http.ListenAndServe(listenAddr, m); err != nil {
		log.Fatal(4, "Fail to start server: %v", err)
	}
}
コード例 #17
0
ファイル: mysql_test.go プロジェクト: mbrukman/grafana
func Test_MysqlProvider(t *testing.T) {
	Convey("Test mysql session provider", t, func() {
		opt := session.Options{
			Provider:       "mysql",
			ProviderConfig: "root:@tcp(localhost:3306)/macaron?charset=utf8",
		}

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