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 }