57 lines
1.6 KiB
Go
57 lines
1.6 KiB
Go
package handlers
|
|
|
|
import (
|
|
"strconv"
|
|
"time"
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
"github.com/gofiber/storage/redis/v3"
|
|
"github.com/golang-jwt/jwt/v4"
|
|
"gorm.io/gorm"
|
|
|
|
"testfb/models"
|
|
)
|
|
|
|
func Login(db *gorm.DB, redisClient *redis.Storage) fiber.Handler {
|
|
return func(c *fiber.Ctx) error {
|
|
var input struct {
|
|
Username string `json:"username"`
|
|
Password string `json:"password"`
|
|
}
|
|
|
|
if err := c.BodyParser(&input); err != nil {
|
|
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Invalid input"})
|
|
}
|
|
|
|
var user models.User
|
|
if err := db.Where("username = ?", input.Username).First(&user).Error; err != nil {
|
|
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "Invalid credentials"})
|
|
}
|
|
|
|
if err := user.ComparePassword(input.Password); err != nil {
|
|
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "Invalid credentials"})
|
|
}
|
|
|
|
token := jwt.New(jwt.SigningMethodHS256)
|
|
claims := token.Claims.(jwt.MapClaims)
|
|
claims["user_id"] = user.ID
|
|
claims["exp"] = time.Now().Add(time.Hour * 24).Unix()
|
|
|
|
t, err := token.SignedString([]byte("your-secret-key"))
|
|
if err != nil {
|
|
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "Could not login"})
|
|
}
|
|
|
|
// Convert user.ID to string before storing in Redis
|
|
userIDStr := strconv.FormatUint(uint64(user.ID), 10)
|
|
err = redisClient.Set(t, []byte(userIDStr), 24*time.Hour)
|
|
if err != nil {
|
|
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "Could not store token"})
|
|
}
|
|
|
|
return c.JSON(fiber.Map{"token": t})
|
|
}
|
|
}
|
|
|
|
// ... (rest of the file remains unchanged)
|