updated for using .env
This commit is contained in:
17
app/main.go
17
app/main.go
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user