-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession.go
More file actions
302 lines (249 loc) · 7.26 KB
/
session.go
File metadata and controls
302 lines (249 loc) · 7.26 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
package auth0
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"sync"
"time"
)
// SessionManager handles user sessions
type SessionManager struct {
mu sync.RWMutex
sessions map[string]*Session
config *SessionConfig
secret []byte
}
// Session represents a user session
type Session struct {
ID string `json:"id"`
UserID string `json:"user_id"`
Profile map[string]interface{} `json:"profile"`
Claims map[string]interface{} `json:"claims"`
State string `json:"state,omitempty"`
CreatedAt time.Time `json:"created_at"`
ExpiresAt time.Time `json:"expires_at"`
}
// NewSessionManager creates a new session manager
func NewSessionManager(config *SessionConfig) *SessionManager {
return &SessionManager{
sessions: make(map[string]*Session),
config: config,
secret: []byte(config.SecretKey),
}
}
// CreateSession creates a new session
func (sm *SessionManager) CreateSession(userID string, profile, claims map[string]interface{}) (*Session, error) {
sm.mu.Lock()
defer sm.mu.Unlock()
sessionID, err := generateSessionID()
if err != nil {
return nil, fmt.Errorf("failed to generate session ID: %w", err)
}
now := time.Now()
session := &Session{
ID: sessionID,
UserID: userID,
Profile: profile,
Claims: claims,
CreatedAt: now,
ExpiresAt: now.Add(sm.config.GetMaxAgeDuration()),
}
sm.sessions[sessionID] = session
return session, nil
}
// GetSession retrieves a session by ID
func (sm *SessionManager) GetSession(sessionID string) (*Session, bool) {
sm.mu.RLock()
defer sm.mu.RUnlock()
session, exists := sm.sessions[sessionID]
if !exists {
return nil, false
}
// Check if session is expired
if time.Now().After(session.ExpiresAt) {
// Clean up expired session
go sm.DeleteSession(sessionID)
return nil, false
}
return session, true
}
// UpdateSession updates an existing session
func (sm *SessionManager) UpdateSession(sessionID string, profile, claims map[string]interface{}) error {
sm.mu.Lock()
defer sm.mu.Unlock()
session, exists := sm.sessions[sessionID]
if !exists {
return fmt.Errorf("session not found")
}
session.Profile = profile
session.Claims = claims
// Extend expiration
session.ExpiresAt = time.Now().Add(sm.config.GetMaxAgeDuration())
return nil
}
// DeleteSession removes a session
func (sm *SessionManager) DeleteSession(sessionID string) {
sm.mu.Lock()
defer sm.mu.Unlock()
delete(sm.sessions, sessionID)
}
// CreateTempSession creates a temporary session for state storage during OAuth flow
func (sm *SessionManager) CreateTempSession(state string) (*Session, error) {
sm.mu.Lock()
defer sm.mu.Unlock()
sessionID, err := generateSessionID()
if err != nil {
return nil, fmt.Errorf("failed to generate temp session ID: %w", err)
}
now := time.Now()
session := &Session{
ID: sessionID,
State: state,
CreatedAt: now,
ExpiresAt: now.Add(10 * time.Minute), // Short expiration for temp sessions
}
sm.sessions[sessionID] = session
return session, nil
}
// ValidateState validates the OAuth state parameter
func (sm *SessionManager) ValidateState(sessionID, state string) bool {
sm.mu.RLock()
defer sm.mu.RUnlock()
session, exists := sm.sessions[sessionID]
if !exists {
return false
}
return session.State == state
}
// SetSessionCookie sets the session cookie on the response
func (sm *SessionManager) SetSessionCookie(w http.ResponseWriter, session *Session) error {
// Create signed cookie value
cookieValue, err := sm.signValue(session.ID)
if err != nil {
return fmt.Errorf("failed to sign cookie value: %w", err)
}
cookie := &http.Cookie{
Name: sm.config.CookieName,
Value: cookieValue,
Path: "/",
MaxAge: sm.config.MaxAge,
Secure: sm.config.Secure,
HttpOnly: sm.config.HTTPOnly,
SameSite: sm.parseSameSite(sm.config.SameSite),
}
http.SetCookie(w, cookie)
return nil
}
// GetSessionFromCookie extracts session ID from cookie and retrieves session
func (sm *SessionManager) GetSessionFromCookie(r *http.Request) (*Session, error) {
cookie, err := r.Cookie(sm.config.CookieName)
if err != nil {
return nil, fmt.Errorf("session cookie not found: %w", err)
}
// Verify and extract session ID
sessionID, err := sm.verifyValue(cookie.Value)
if err != nil {
return nil, fmt.Errorf("invalid session cookie: %w", err)
}
session, exists := sm.GetSession(sessionID)
if !exists {
return nil, fmt.Errorf("session not found or expired")
}
return session, nil
}
// ClearSessionCookie clears the session cookie
func (sm *SessionManager) ClearSessionCookie(w http.ResponseWriter) {
cookie := &http.Cookie{
Name: sm.config.CookieName,
Value: "",
Path: "/",
MaxAge: -1,
Secure: sm.config.Secure,
HttpOnly: sm.config.HTTPOnly,
SameSite: sm.parseSameSite(sm.config.SameSite),
}
http.SetCookie(w, cookie)
}
// CleanupExpiredSessions removes expired sessions (should be called periodically)
func (sm *SessionManager) CleanupExpiredSessions() {
sm.mu.Lock()
defer sm.mu.Unlock()
now := time.Now()
for id, session := range sm.sessions {
if now.After(session.ExpiresAt) {
delete(sm.sessions, id)
}
}
}
// GetSessionCount returns the number of active sessions
func (sm *SessionManager) GetSessionCount() int {
sm.mu.RLock()
defer sm.mu.RUnlock()
return len(sm.sessions)
}
// signValue creates a signed value using HMAC
func (sm *SessionManager) signValue(value string) (string, error) {
mac := hmac.New(sha256.New, sm.secret)
mac.Write([]byte(value))
signature := mac.Sum(nil)
data := map[string]string{
"value": value,
"signature": base64.URLEncoding.EncodeToString(signature),
}
jsonData, err := json.Marshal(data)
if err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(jsonData), nil
}
// verifyValue verifies a signed value
func (sm *SessionManager) verifyValue(signedValue string) (string, error) {
jsonData, err := base64.URLEncoding.DecodeString(signedValue)
if err != nil {
return "", fmt.Errorf("invalid base64 encoding: %w", err)
}
var data map[string]string
if err := json.Unmarshal(jsonData, &data); err != nil {
return "", fmt.Errorf("invalid JSON data: %w", err)
}
value, ok := data["value"]
if !ok {
return "", fmt.Errorf("missing value field")
}
signature, ok := data["signature"]
if !ok {
return "", fmt.Errorf("missing signature field")
}
// Verify signature
mac := hmac.New(sha256.New, sm.secret)
mac.Write([]byte(value))
expectedSignature := mac.Sum(nil)
decodedSignature, err := base64.URLEncoding.DecodeString(signature)
if err != nil {
return "", fmt.Errorf("invalid signature encoding: %w", err)
}
if !hmac.Equal(decodedSignature, expectedSignature) {
return "", fmt.Errorf("signature verification failed")
}
return value, nil
}
// parseSameSite converts string to http.SameSite
func (sm *SessionManager) parseSameSite(sameSite string) http.SameSite {
switch sameSite {
case "strict":
return http.SameSiteStrictMode
case "none":
return http.SameSiteNoneMode
case "lax":
fallthrough
default:
return http.SameSiteLaxMode
}
}
// generateSessionID generates a cryptographically secure session ID
func generateSessionID() (string, error) {
return GenerateState() // Reuse the state generation function
}