generated from datumforge/go-template
-
Notifications
You must be signed in to change notification settings - Fork 7
/
context.go
95 lines (73 loc) · 2.33 KB
/
context.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package sessions
import (
"context"
"strings"
"github.com/pkg/errors"
"golang.org/x/oauth2"
)
// SessionContextKey is the context key for the user claims
var SessionContextKey = &ContextKey{"SessionContextKey"}
// ContextKey is the key name for the additional context
type ContextKey struct {
name string
}
// OhAuthTokenFromContext returns the Token from the ctx
func OhAuthTokenFromContext(ctx context.Context) (*oauth2.Token, error) {
token, ok := ctx.Value(SessionContextKey).(*oauth2.Token)
if !ok {
return nil, errors.New("context missing Token")
}
return token, nil
}
// ContextWithToken returns a copy of ctx that stores the Token
func ContextWithToken(ctx context.Context, token *oauth2.Token) context.Context {
return context.WithValue(ctx, SessionContextKey, token)
}
// UserIDFromContext returns the user ID from the ctx
// this function assumes the session data is stored in a string map
func UserIDFromContext(ctx context.Context) (string, error) {
sessionDetails, ok := ctx.Value(SessionContextKey).(*Session[any])
if !ok {
return "", ErrInvalidSession
}
sessionID := sessionDetails.GetKey()
sessionData, ok := sessionDetails.GetOk(sessionID)
if !ok {
return "", ErrInvalidSession
}
sd, ok := sessionData.(map[string]string)
if !ok {
return "", ErrInvalidSession
}
userID, ok := sd["userID"]
if !ok {
return "", ErrInvalidSession
}
return userID, nil
}
// ContextWithUserID returns a copy of ctx that stores the user ID
func ContextWithUserID(ctx context.Context, userID string) context.Context {
if strings.TrimSpace(userID) == "" {
return ctx
}
return context.WithValue(ctx, SessionContextKey, userID)
}
// SessionToken returns the encoded session token
func SessionToken(ctx context.Context) (string, error) {
sd := getSessionDataFromContext(ctx)
sd.mu.Lock()
defer sd.mu.Unlock()
return sd.store.EncodeCookie(sd)
}
// addSessionDataToContext adds the session details to the context
func (s *Session[P]) addSessionDataToContext(ctx context.Context) context.Context {
return context.WithValue(ctx, SessionContextKey, s)
}
// getSessionDataFromContext gets the session information from the context
func getSessionDataFromContext(ctx context.Context) *Session[map[string]any] {
c, ok := ctx.Value(SessionContextKey).(*Session[map[string]any])
if !ok {
panic("no session data in context")
}
return c
}