Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Token from context #176

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion context.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@ import (
)

func contextGet(r *http.Request, key string) (interface{}, error) {
val := r.Context().Value(key)
return valueFromContext(r.Context(), key)
}

func valueFromContext(ctx context.Context, key string) (interface{}, error) {
val := ctx.Value(key)
if val == nil {
return nil, fmt.Errorf("no value exists in the context for key %q", key)
}
Expand Down
1 change: 0 additions & 1 deletion csrf.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ const (
errorKey string = "gorilla.csrf.Error"
skipCheckKey string = "gorilla.csrf.Skip"
cookieName string = "_gorilla_csrf"
errorPrefix string = "gorilla/csrf: "
)

var (
Expand Down
10 changes: 9 additions & 1 deletion helpers.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package csrf

import (
"context"
"crypto/rand"
"crypto/subtle"
"encoding/base64"
Expand All @@ -14,7 +15,14 @@ import (
// 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, err := contextGet(r, tokenKey); err == nil {
return TokenFromContext(r.Context())
}

// TokenFromContext 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 TokenFromContext(ctx context.Context) string {
if val, err := valueFromContext(ctx, tokenKey); err == nil {
if maskedToken, ok := val.(string); ok {
return maskedToken
}
Expand Down
Loading