4f3113199b
- JWT: validate signing algorithm (prevent alg confusion) - Login: rate limiting (10 attempts per 5 min per IP) - Request body: 10MB size limit (prevent DoS) - WebSocket: require JWT auth (token query param or cookie) - Daemon endpoints: require admin role (not just any user) - io.LimitReader on all request body decoding
45 lines
1.2 KiB
Go
45 lines
1.2 KiB
Go
package auth
|
|
|
|
import (
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
func HashPassword(password string) (string, error) {
|
|
b, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
|
return string(b), err
|
|
}
|
|
|
|
func CheckPassword(hash, password string) bool {
|
|
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil
|
|
}
|
|
|
|
func CreateToken(userID string, isAdmin bool, secret string) (string, error) {
|
|
claims := jwt.MapClaims{
|
|
"sub": userID,
|
|
"admin": isAdmin,
|
|
"exp": time.Now().Add(72 * time.Hour).Unix(),
|
|
}
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
return token.SignedString([]byte(secret))
|
|
}
|
|
|
|
func ValidateToken(tokenStr, secret string) (userID string, isAdmin bool, err error) {
|
|
token, err := jwt.Parse(tokenStr, func(t *jwt.Token) (interface{}, error) {
|
|
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
|
return nil, fmt.Errorf("unexpected signing method")
|
|
}
|
|
return []byte(secret), nil
|
|
})
|
|
if err != nil || !token.Valid {
|
|
return "", false, err
|
|
}
|
|
claims := token.Claims.(jwt.MapClaims)
|
|
userID, _ = claims["sub"].(string)
|
|
isAdmin, _ = claims["admin"].(bool)
|
|
return userID, isAdmin, nil
|
|
}
|