implement auth using Auth0
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
package site
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"ruben/inventory2/internal/consts"
|
||||
"ruben/inventory2/internal/domains/authentication"
|
||||
)
|
||||
|
||||
// just keep this around long enough for testing auth middleware..
|
||||
func (s *Server) testAuthEndpoint(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Println("SUCCESS:", getCustomClaims(r.Context()))
|
||||
|
||||
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
|
||||
}
|
||||
|
||||
type customClaimsKey struct{}
|
||||
|
||||
// auth middleware to verify access_token cookie and set custom claims in the request context
|
||||
func (s *Server) authenticate(h http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ck, err := r.Cookie("access_token")
|
||||
if err != nil {
|
||||
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := r.Context()
|
||||
|
||||
claims, expiration, err := s.auth.GetAccessTokenClaimsAndExpiration(ctx, ck.Value)
|
||||
if err != nil {
|
||||
if errors.Is(err, consts.ErrNotFound) {
|
||||
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
|
||||
return
|
||||
}
|
||||
|
||||
http.Error(w, fmt.Sprintf("failed to authenticate: %v", err), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if expiration.Before(time.Now()) {
|
||||
deleteCookieInResponse(w, "access_token")
|
||||
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
|
||||
return
|
||||
}
|
||||
|
||||
h.ServeHTTP(w, r.WithContext(context.WithValue(ctx, customClaimsKey{}, claims)))
|
||||
})
|
||||
}
|
||||
|
||||
// get custom claims from request context
|
||||
func getCustomClaims(ctx context.Context) authentication.AccessTokenClaims {
|
||||
c, _ := ctx.Value(customClaimsKey{}).(authentication.AccessTokenClaims)
|
||||
return c
|
||||
}
|
||||
Reference in New Issue
Block a user