http response tooling written
This commit is contained in:
+12
-16
@@ -9,24 +9,24 @@ import (
|
||||
|
||||
"ruben/inventory2/internal/consts"
|
||||
"ruben/inventory2/internal/domains/authentication"
|
||||
"ruben/inventory2/internal/site/response"
|
||||
)
|
||||
|
||||
// just keep this around long enough for testing auth middleware..
|
||||
func (s *Server) testAuthEndpoint(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Println("SUCCESS:", getAccessTokenClaims(r.Context()))
|
||||
func (s *Server) testAuthEndpoint(r *http.Request) (response.Response, error) {
|
||||
fmt.Println("AUTH TEST SUCCESS:", getAccessTokenClaims(r.Context()))
|
||||
|
||||
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
|
||||
return response.TemporaryRedirect("/"), nil
|
||||
}
|
||||
|
||||
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) {
|
||||
func (s *Server) authenticate(f response.HandlerFunc) response.HandlerFunc {
|
||||
return func(r *http.Request) (response.Response, error) {
|
||||
ck, err := r.Cookie("access_token")
|
||||
if err != nil {
|
||||
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
|
||||
return
|
||||
return response.TemporaryRedirect("/"), nil
|
||||
}
|
||||
|
||||
ctx := r.Context()
|
||||
@@ -34,22 +34,18 @@ func (s *Server) authenticate(h http.Handler) http.Handler {
|
||||
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
|
||||
return response.TemporaryRedirect("/"), nil
|
||||
}
|
||||
|
||||
http.Error(w, fmt.Sprintf("failed to authenticate: %v", err), http.StatusInternalServerError)
|
||||
return
|
||||
return nil, response.Errorf("failed to authenticate: %w", err)
|
||||
}
|
||||
|
||||
if expiration.Before(time.Now()) {
|
||||
deleteCookieInResponse(w, "access_token")
|
||||
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
|
||||
return
|
||||
return response.TemporaryRedirect("/").Cookie(getExpiredCookie("access_token")), nil
|
||||
}
|
||||
|
||||
h.ServeHTTP(w, r.WithContext(setAccessTokenClaims(ctx, claims)))
|
||||
})
|
||||
return f(r.WithContext(setAccessTokenClaims(ctx, claims)))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) getAccessTokenClaims(r *http.Request) (authentication.AccessTokenClaims, bool) {
|
||||
|
||||
Reference in New Issue
Block a user