Skip to content

Commit

Permalink
Update project!
Browse files Browse the repository at this point in the history
  • Loading branch information
devluanpereira committed Oct 6, 2024
1 parent dddbcff commit b81042e
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 7 deletions.
4 changes: 3 additions & 1 deletion .env
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,6 @@ DB_USER=root
DB_NAME=teste
DB_PASSWORD=luan
DB_HOST=localhost
DB_PORT=3306
DB_PORT=3306

JWT_SECRET=lpkgSpxZw3jf2gmri/obJUry5QW7NZlC4QStyc0Cd/E=
3 changes: 2 additions & 1 deletion internal/handlers/auth_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"database/sql"
"html/template"
"net/http"
"os"
"time"

"github.com/golang-jwt/jwt/v5"
Expand Down Expand Up @@ -54,7 +55,7 @@ func Login(db *sql.DB) http.HandlerFunc {
"exp": time.Now().Add(time.Hour * 1).Unix(),
})

tokenString, err := token.SignedString([]byte("lpkgSpxZw3jf2gmri/obJUry5QW7NZlC4QStyc0Cd/E="))
tokenString, err := token.SignedString([]byte(os.Getenv("JWT_SECRET"))) // Usa a variável do .env
if err != nil {
http.Error(w, "Error generating token", http.StatusInternalServerError)
return
Expand Down
7 changes: 2 additions & 5 deletions internal/services/auth_middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package services
import (
"fmt"
"net/http"
"os"
"time"

"github.com/golang-jwt/jwt/v5"
Expand All @@ -14,7 +15,6 @@ func Protected(next http.HandlerFunc) http.HandlerFunc {
// Busca o cookie com o token
cookie, err := r.Cookie("token")
if err != nil || cookie.Value == "" {
// Se o cookie não existir ou estiver vazio, redireciona para login
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
Expand All @@ -27,24 +27,21 @@ func Protected(next http.HandlerFunc) http.HandlerFunc {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("algoritmo inesperado: %v", token.Header["alg"])
}
return []byte("lpkgSpxZw3jf2gmri/obJUry5QW7NZlC4QStyc0Cd/E="), nil
return []byte(os.Getenv("JWT_SECRET")), nil // Lê o segredo do .env
})

if err != nil {
// Se o token for inválido, redireciona para login
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}

if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
exp, ok := claims["exp"].(float64)
if !ok || int64(exp) < time.Now().Unix() {
// Se o token estiver expirado, redireciona para login
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
} else {
// Se o token for inválido, redireciona para login
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
Expand Down

0 comments on commit b81042e

Please sign in to comment.