add rate limiting and 2fa hardening
This commit is contained in:
52
auth/jwt.go
52
auth/jwt.go
@@ -7,6 +7,11 @@ import (
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
const (
|
||||
PurposeTwoFactorLogin = "2fa_login"
|
||||
PurposeTwoFactorSetup = "2fa_setup"
|
||||
)
|
||||
|
||||
type Claims struct {
|
||||
UserID string `json:"user_id"`
|
||||
Role string `json:"role"`
|
||||
@@ -19,6 +24,13 @@ type PurposeClaims struct {
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
type TwoFactorSetupClaims struct {
|
||||
UserID string `json:"user_id"`
|
||||
Purpose string `json:"purpose"`
|
||||
Secret string `json:"secret"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
func GenerateJWT(userID, role string, secret []byte) (string, error) {
|
||||
claims := Claims{
|
||||
UserID: userID,
|
||||
@@ -47,6 +59,21 @@ func GeneratePurposeJWT(userID, purpose string, secret []byte, ttl time.Duration
|
||||
return token.SignedString(secret)
|
||||
}
|
||||
|
||||
func GenerateTwoFactorSetupJWT(userID, twoFactorSecret string, secret []byte, ttl time.Duration) (string, error) {
|
||||
claims := TwoFactorSetupClaims{
|
||||
UserID: userID,
|
||||
Purpose: PurposeTwoFactorSetup,
|
||||
Secret: twoFactorSecret,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(ttl)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
},
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return token.SignedString(secret)
|
||||
}
|
||||
|
||||
func ValidateJWT(tokenStr string, secret []byte) (*Claims, error) {
|
||||
token, err := jwt.ParseWithClaims(tokenStr, &Claims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
if token.Method != jwt.SigningMethodHS256 {
|
||||
@@ -87,3 +114,28 @@ func ValidatePurposeJWT(tokenStr, expectedPurpose string, secret []byte) (*Purpo
|
||||
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
func ValidateTwoFactorSetupJWT(tokenStr string, secret []byte) (*TwoFactorSetupClaims, error) {
|
||||
token, err := jwt.ParseWithClaims(tokenStr, &TwoFactorSetupClaims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
if token.Method != jwt.SigningMethodHS256 {
|
||||
return nil, errors.New("unexpected signing method")
|
||||
}
|
||||
return secret, nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(*TwoFactorSetupClaims)
|
||||
if !ok || !token.Valid {
|
||||
return nil, errors.New("invalid token")
|
||||
}
|
||||
if claims.Purpose != PurposeTwoFactorSetup {
|
||||
return nil, errors.New("invalid token purpose")
|
||||
}
|
||||
if claims.Secret == "" {
|
||||
return nil, errors.New("missing 2FA setup secret")
|
||||
}
|
||||
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user