예제 #1
0
파일: oauth2.go 프로젝트: speedland/service
func registerViewHelpers() {
	wcg.AddViewHelper("oauth2_by", func(v *wcg.View) string {
		switch v.Request.User.(type) {
		case *OAuth2User:
			return v.Request.User.AuthProvider()
		default:
			return ""
		}
	})
}
예제 #2
0
// CSRFSupport to add a helper method csrf() to generate a hidden input for CSRF, and
// returns validator handler
func CSRFSupport() wcg.Handler {
	wcg.AddViewHelper("csrf", func(req *wcg.Request) template.HTML {
		if s := req.Session; s != nil {
			tok, _ := s.CSRFToken()
			return template.HTML("<input type=\"hidden\" name=\"" + CSRFTokenParamName + "\" value=\"" + tok + "\"></input>")
		}
		return ""
	})
	wcg.AddViewHelper("csrf_token", func(req *wcg.Request) string {
		if s := req.Session; s != nil {
			tok, salt := s.CSRFToken()
			req.Logger.Debugf(
				"Generating CSRF Token: salt=%q, secret=%q, tok=%q",
				salt, s.CSRFSecret, tok,
			)
			return tok
		}
		return ""
	})

	var csrferror = map[string]string{
		"error":       "CSRF error",
		"description": "An invalid CSRF token was passed to the server.",
	}
	return wcg.NewNamedHandler("csrf", func(res *wcg.Response, req *wcg.Request) {
		if res.IsClosed() {
			return
		}

		token := req.Form(CSRFTokenParamName)
		if token == "" {
			// try to seek header
			token = req.Header(CSRFTokenHeaderName)
		}
		if err := req.Session.ValidateToken(token); err != nil {
			res.WriteJSONWithStatus(403, nil, csrferror)
		}
	})
}