updated for using .env

This commit is contained in:
Mann Patel
2025-08-27 17:54:45 -06:00
parent 09093aa70a
commit 9f260c3821
11 changed files with 83 additions and 32 deletions

View File

@@ -11,6 +11,7 @@ import (
"path/filepath"
"github.com/golang-jwt/jwt/v5"
"github.com/joho/godotenv"
"github.com/patel-mann/poll-system/app/internal/handlers"
"github.com/patel-mann/poll-system/app/internal/models"
@@ -19,8 +20,6 @@ import (
_ "github.com/lib/pq" // use PostgreSQL
)
var jwtSecret = []byte("your-secret-key")
// Custom file server with logging
func loggingFileServer(dir string) http.Handler {
fs := http.FileServer(http.Dir(dir))
@@ -71,6 +70,18 @@ func createTemplateData(title, activeSection string, role int, isAuthenticated b
}
func authMiddleware(next http.HandlerFunc) http.HandlerFunc {
err := godotenv.Load() // or specify path: godotenv.Load("/path/to/.env")
if err != nil {
log.Fatalf("Error loading .env file: %v", err)
}
// Get individual components from environment variables
jwtSecret := os.Getenv("JWT_SECRET")
var jwtKey = []byte(jwtSecret)
return func(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("session")
if err != nil {
@@ -80,7 +91,7 @@ func authMiddleware(next http.HandlerFunc) http.HandlerFunc {
claims := &models.Claims{}
token, err := jwt.ParseWithClaims(cookie.Value, claims, func(token *jwt.Token) (interface{}, error) {
return jwtSecret, nil
return jwtKey, nil
})
if err != nil || !token.Valid {
http.Redirect(w, r, "/login", http.StatusSeeOther)