Ejemplo n.º 1
0
// FailureReason makes CSRF validation errors available in the request context.
// This is useful when you want to log the cause of the error or report it to
// client.
func FailureReason(r *http.Request) error {
	if val, ok := context.GetOk(r, ErrorKey); ok {
		if err, ok := val.(error); ok {
			return err
		}
	}

	return nil
}
Ejemplo n.º 2
0
// Token returns a masked CSRF token ready for passing into HTML template or
// a JSON response body. An empty token will be returned if the middleware
// has not been applied (which will fail subsequent validation).
func Token(r *http.Request) string {
	if val, ok := context.GetOk(r, TokenKey); ok {
		if maskedToken, ok := val.(string); ok {
			return maskedToken
		}
	}

	return ""
}
Ejemplo n.º 3
0
// TemplateField is a template helper for html/template that provides an <input> field
// populated with a CSRF token.
//
// Example:
//
//      // The following tag in our form.tmpl template:
//      {{ .csrfField }}
//
//      // ... becomes:
//      <input type="hidden" name="gorilla.csrf.Token" value="<token>">
//
func TemplateField(r *http.Request) template.HTML {
	name, ok := context.GetOk(r, FormKey)
	if ok {
		fragment := fmt.Sprintf(`<input type="hidden" name="%s" value="%s">`,
			name, Token(r))

		return template.HTML(fragment)
	}

	return template.HTML("")
}