feat: improve app security and error handling
Improve overall app security by: - using dynamic statements for all sql querries - introducing environment variables for initial admin password - introducing enironment variable for cors address - improving error handling
This commit is contained in:
parent
95057c1b8d
commit
3ac1947106
11 changed files with 1333 additions and 453 deletions
|
|
@ -1,17 +1,13 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
echojwt "github.com/labstack/echo-jwt/v4"
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/labstack/echo/v4/middleware"
|
||||
"golang.org/x/time/rate"
|
||||
|
|
@ -28,104 +24,43 @@ func init() {
|
|||
}
|
||||
|
||||
func createToken(userID int, username string, isAdmin bool) (string, error) {
|
||||
claims := Claims{
|
||||
claims := &Claims{
|
||||
UserID: userID,
|
||||
Username: username,
|
||||
IsAdmin: isAdmin,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(2 * time.Hour)),
|
||||
},
|
||||
}
|
||||
|
||||
header := base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"HS256","typ":"JWT"}`))
|
||||
|
||||
claimsWithExp := map[string]any{
|
||||
"user_id": claims.UserID,
|
||||
"username": claims.Username,
|
||||
"is_admin": claims.IsAdmin,
|
||||
"exp": time.Now().Add(2 * time.Hour).Unix(),
|
||||
}
|
||||
|
||||
payload, _ := json.Marshal(claimsWithExp)
|
||||
payloadEncoded := base64.RawURLEncoding.EncodeToString(payload)
|
||||
|
||||
message := header + "." + payloadEncoded
|
||||
|
||||
h := hmac.New(sha256.New, jwtSecret)
|
||||
h.Write([]byte(message))
|
||||
signature := base64.RawURLEncoding.EncodeToString(h.Sum(nil))
|
||||
|
||||
return message + "." + signature, nil
|
||||
}
|
||||
|
||||
func verifyToken(tokenString string) (*Claims, error) {
|
||||
parts := strings.Split(tokenString, ".")
|
||||
if len(parts) != 3 {
|
||||
return nil, fmt.Errorf("invalid token format")
|
||||
}
|
||||
|
||||
message := parts[0] + "." + parts[1]
|
||||
h := hmac.New(sha256.New, jwtSecret)
|
||||
h.Write([]byte(message))
|
||||
expectedSignature := base64.RawURLEncoding.EncodeToString(h.Sum(nil))
|
||||
|
||||
if parts[2] != expectedSignature {
|
||||
return nil, fmt.Errorf("invalid signature")
|
||||
}
|
||||
|
||||
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var claimsMap map[string]any
|
||||
if err := json.Unmarshal(payload, &claimsMap); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if exp, ok := claimsMap["exp"].(float64); ok {
|
||||
if time.Now().Unix() > int64(exp) {
|
||||
return nil, fmt.Errorf("token expired")
|
||||
}
|
||||
}
|
||||
|
||||
claims := &Claims{
|
||||
UserID: int(claimsMap["user_id"].(float64)),
|
||||
Username: claimsMap["username"].(string),
|
||||
IsAdmin: claimsMap["is_admin"].(bool),
|
||||
}
|
||||
|
||||
return claims, nil
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return token.SignedString(jwtSecret)
|
||||
}
|
||||
|
||||
func JWTMiddleware() echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
authHeader := c.Request().Header.Get("Authorization")
|
||||
if authHeader == "" {
|
||||
return echo.NewHTTPError(http.StatusUnauthorized, "Unauthorized")
|
||||
}
|
||||
|
||||
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
|
||||
claims, err := verifyToken(tokenString)
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusUnauthorized, "Unauthorized")
|
||||
}
|
||||
|
||||
c.Set("user_id", claims.UserID)
|
||||
c.Set("username", claims.Username)
|
||||
c.Set("is_admin", claims.IsAdmin)
|
||||
|
||||
c.Logger().Infof("Authenticated user: ID=%d, Username=%s", claims.UserID, claims.Username)
|
||||
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
return echojwt.WithConfig(echojwt.Config{
|
||||
NewClaimsFunc: func(c echo.Context) jwt.Claims {
|
||||
return new(Claims)
|
||||
},
|
||||
SigningKey: jwtSecret,
|
||||
})
|
||||
}
|
||||
|
||||
func AdminMiddleware() echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
isAdmin, ok := c.Get("is_admin").(bool)
|
||||
if !ok || !isAdmin {
|
||||
return echo.NewHTTPError(http.StatusForbidden, "Access denied")
|
||||
user, ok := c.Get("user").(*jwt.Token)
|
||||
if !ok {
|
||||
return echo.NewHTTPError(http.StatusUnauthorized, "JWT token missing or invalid")
|
||||
}
|
||||
|
||||
claims, ok := user.Claims.(*Claims)
|
||||
if !ok {
|
||||
return echo.NewHTTPError(http.StatusUnauthorized, "Failed to parse JWT claims")
|
||||
}
|
||||
|
||||
if !claims.IsAdmin {
|
||||
return echo.NewHTTPError(http.StatusForbidden, "Access denied: admin rights required")
|
||||
}
|
||||
return next(c)
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue