-
Notifications
You must be signed in to change notification settings - Fork 28
/
context_keys.go
71 lines (58 loc) · 2.26 KB
/
context_keys.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package web
import (
"context"
"fmt"
)
type contextKey int
const (
userKey contextKey = iota
isAuthorizedKey
authenticationErrorKey
authorizationErrorKey
shouldStoreBindingsKey
)
// ShouldStoreBindings returns whether the request has to store bindings
func ShouldStoreBindings(ctx context.Context) bool {
shouldStoreBindings := ctx.Value(shouldStoreBindingsKey)
return shouldStoreBindings == nil || shouldStoreBindings.(bool)
}
// ContextWithStoreBindings sets the shouldStoreBindings flag in the context
func ContextWithStoreBindingsFlag(ctx context.Context, shouldStoreBindings bool) context.Context {
return context.WithValue(ctx, shouldStoreBindingsKey, shouldStoreBindings)
}
// UserFromContext gets the authenticated user from the context
func UserFromContext(ctx context.Context) (*UserContext, bool) {
userCtx, ok := ctx.Value(userKey).(*UserContext)
return userCtx, ok && userCtx != nil
}
// ContextWithUser sets the authenticated user in the context
func ContextWithUser(ctx context.Context, user *UserContext) context.Context {
return context.WithValue(ctx, userKey, user)
}
// IsAuthorized returns whether the request has been authorized
func IsAuthorized(ctx context.Context) bool {
_, ok := ctx.Value(isAuthorizedKey).(bool)
return ok
}
// ContextWithAuthorization sets the boolean flag isAuthorized in the request context
func ContextWithAuthorization(ctx context.Context) context.Context {
return context.WithValue(ctx, isAuthorizedKey, true)
}
func ContextWithAuthenticationError(ctx context.Context, authNError error) context.Context {
return context.WithValue(ctx, authenticationErrorKey, authNError)
}
func AuthenticationErrorFromContext(ctx context.Context) (bool, error) {
authnError, ok := ctx.Value(authenticationErrorKey).(error)
return ok && authnError != nil, authnError
}
func ContextWithAuthorizationError(ctx context.Context, authZError error) context.Context {
found, currentAuthZError := AuthorizationErrorFromContext(ctx)
if found {
authZError = fmt.Errorf("%s or %s", currentAuthZError, authZError)
}
return context.WithValue(ctx, authorizationErrorKey, authZError)
}
func AuthorizationErrorFromContext(ctx context.Context) (bool, error) {
authzError, ok := ctx.Value(authorizationErrorKey).(error)
return ok && authzError != nil, authzError
}