-
Notifications
You must be signed in to change notification settings - Fork 404
/
Copy pathmiddleware-aal.go
56 lines (46 loc) · 1.6 KB
/
middleware-aal.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
// middleware.go
package main
import (
"context"
"errors"
"log"
"net/http"
ory "github.com/ory/client-go"
)
func (app *App) sessionMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(writer http.ResponseWriter, request *http.Request) {
log.Printf("Checking authentication status\n")
// Pass cookies to Ory's ToSession endpoint
cookies := request.Header.Get("Cookie")
// Verify session with Ory
session, _, err := app.ory.FrontendAPI.ToSession(request.Context()).Cookie(cookies).Execute()
// Redirect to login if session doesn't exist or is inactive
if err != nil || (err == nil && !*session.Active) {
log.Printf("No active session, redirecting to login\n")
// Redirect to the login page
http.Redirect(writer, request, "/self-service/login/browser", http.StatusSeeOther)
return
}
// highlight-start
if *session.AuthenticatorAssuranceLevel != "aal2" {
http.Redirect(writer, request, "/self-service/login/browser?aal=aal2", http.StatusSeeOther)
return
}
// highlight-end
// Add session to context for the handler
ctx := withSession(request.Context(), session)
next.ServeHTTP(writer, request.WithContext(ctx))
}
}
func withSession(ctx context.Context, v *ory.Session) context.Context {
return context.WithValue(ctx, "req.session", v)
}
func getSession(ctx context.Context) (*ory.Session, error) {
session, ok := ctx.Value("req.session").(*ory.Session)
if !ok || session == nil {
return nil, errors.New("session not found in context")
}
return session, nil
}
// Dashboard page protected by middleware
mux.Handle("/", app.sessionMiddleware(app.dashboardHandler))