add auth to backend and frontend
This commit is contained in:
+3
-5
@@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"go-weather/services"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type contextKey string
|
||||
@@ -14,14 +13,13 @@ const ClaimsKey contextKey = "claims"
|
||||
func AuthMiddleware(authService *services.AuthService) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
authHeader := r.Header.Get("Authorization")
|
||||
if authHeader == "" {
|
||||
cookie, err := r.Cookie("token")
|
||||
if err != nil {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
|
||||
claims, err := authService.ValidateToken(tokenString)
|
||||
claims, err := authService.ValidateToken(cookie.Value)
|
||||
if err != nil {
|
||||
http.Error(w, "invalid token", http.StatusUnauthorized)
|
||||
return
|
||||
|
||||
Reference in New Issue
Block a user