Created response structs and a json response util.
This commit is contained in:
+13
-14
@@ -2,9 +2,9 @@ package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
@@ -32,9 +32,9 @@ func (s *Server) hasAuth(next http.Handler) http.Handler {
|
||||
}
|
||||
|
||||
if tokenString == "" {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
json.NewEncoder(w).Encode(map[string]string{"error": "unauthorized"})
|
||||
WriteJSON(w, http.StatusUnauthorized, ErrorResponse{
|
||||
Error: "unauthorized",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -54,27 +54,26 @@ func (s *Server) hasAuth(next http.Handler) http.Handler {
|
||||
/// Not Before Check: It checks if the nbf (Not Before) time has passed.
|
||||
/// Issued At Check: It ensures the iat isn't in the future.
|
||||
if err != nil || !token.Valid {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
|
||||
// Check if the error is specifically because the token expired
|
||||
if errors.Is(err, jwt.ErrTokenExpired) {
|
||||
json.NewEncoder(w).Encode(map[string]string{
|
||||
"error": "token_expired",
|
||||
"message": "Please use your refresh token to get a new session",
|
||||
WriteJSON(w, http.StatusUnauthorized, ErrorResponse{
|
||||
Error: "Token expired: Please use your refresh token to get a new session",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
json.NewEncoder(w).Encode(map[string]string{"error": "unauthorized"})
|
||||
WriteJSON(w, http.StatusUnauthorized, ErrorResponse{
|
||||
Error: "unauthorized",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Verify issuer
|
||||
if claims.Issuer != ISSUER {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
json.NewEncoder(w).Encode(map[string]string{"error": "invalid issuer"})
|
||||
log.Printf("Invalid Token, issuer incorrect or tampered with")
|
||||
WriteJSON(w, http.StatusUnauthorized, ErrorResponse{
|
||||
Error: "Invalid Token",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user