more error handling

This commit is contained in:
2023-04-04 08:31:19 +10:00
parent ad58d84396
commit ab60f8796a

View File

@@ -24,6 +24,7 @@ func GenerateToken(user_id uint) (string, error) {
claims["authorized"] = true claims["authorized"] = true
claims["user_id"] = user_id claims["user_id"] = user_id
claims["exp"] = time.Now().Add(time.Hour * time.Duration(token_lifespan)).Unix() claims["exp"] = time.Now().Add(time.Hour * time.Duration(token_lifespan)).Unix()
// https://pkg.go.dev/github.com/golang-jwt/jwt/v5#New
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(os.Getenv("API_SECRET"))) return token.SignedString([]byte(os.Getenv("API_SECRET")))
@@ -36,8 +37,8 @@ func TokenValid(c *gin.Context) error {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
} }
//return []byte(os.Getenv("API_SECRET")), nil // This code says signature is invalid if we return an empty []byte but I don't know why
return []byte(""), nil return []byte(os.Getenv("API_SECRET")), nil
}) })
if err != nil { if err != nil {
return err return err
@@ -64,9 +65,8 @@ func ExtractTokenID(c *gin.Context) (uint, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
} }
// Why return the secret?? // Why return the secret?? Code doesn't work if we don't return the secret
//return []byte(os.Getenv("API_SECRET")), nil return []byte(os.Getenv("API_SECRET")), nil
return 0, nil
}) })
if err != nil { if err != nil {
return 0, err return 0, err