cauth/middleware.go

78 lines
1.6 KiB
Go

package cauth
import (
"context"
"fmt"
"github.com/lestrrat-go/jwx/jwk"
"log"
"net/http"
)
type contextKey string
const userContextKey = contextKey("user")
type Middleware struct {
s SessionStorer
ck jwk.Set
}
func NewMiddleware(s SessionStorer, cognitoUrl string) *Middleware {
cognitoKeySet, err := jwk.Fetch(context.Background(), cognitoUrl)
if err != nil {
log.Fatal(err)
}
return &Middleware{s, cognitoKeySet}
}
func (m *Middleware) AddUserInfo(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session, err := m.s.Get(r)
if err != nil {
next.ServeHTTP(w, r)
return
}
token := session.Values["access_token"]
if token == "" || token == nil {
next.ServeHTTP(w, r)
return
}
userInfo := session.Values["user_info"]
fmt.Println(userInfo)
ctx := context.WithValue(r.Context(), userContextKey, userInfo)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func (m *Middleware) ProtectedRoute(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session, err := m.s.Get(r)
if err != nil {
http.Redirect(w, r, "/signin", http.StatusSeeOther)
return
}
token := session.Values["access_token"]
if token == "" || token == nil {
http.Redirect(w, r, "/signin", http.StatusSeeOther)
return
}
next.ServeHTTP(w, r)
})
}
func GetUserFromContext(r *http.Request) *UserClaims {
userOptional := r.Context().Value(userContextKey)
if userOptional != nil {
user := userOptional.(UserClaims)
return &user
}
return &UserClaims{}
}