fix login functionality

This commit is contained in:
Thomas Peetz
2025-12-04 17:23:59 +01:00
parent 46bca919d7
commit a5393f471f
6 changed files with 131 additions and 16 deletions
+20 -16
View File
@@ -1,38 +1,42 @@
package handler
import (
"time"
"context"
"kontor-api-go/pkg/schema"
"kontor-api-go/pkg/utils"
"github.com/gofiber/fiber/v2"
"github.com/golang-jwt/jwt/v5"
"github.com/uptrace/bun"
)
func Login(c *fiber.Ctx) error {
user := c.FormValue("user")
pass := c.FormValue("pass")
// Throws Unauthorized error
if user != "john" || pass != "doe" {
var profile schema.Profile
var err error
var db *bun.DB
ctx := context.Background()
db, _ = schema.GetDatabase()
err = db.NewSelect().Model(&profile).Where("email = ?", user).Scan(ctx)
if err != nil {
return c.Status(400).JSON(fiber.Map{
"message": err.Error(),
})
}
if !utils.ComparePassword(profile.Password, pass) {
return c.SendStatus(fiber.StatusUnauthorized)
}
// Create the Claims
claims := jwt.MapClaims{
"name": "John Doe",
"admin": true,
"exp": time.Now().Add(time.Hour * 72).Unix(),
}
// Create token
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// Generate encoded token and send it as response.
t, err := token.SignedString([]byte("secret"))
token, err := utils.GenerateToken(profile)
if err != nil {
return c.SendStatus(fiber.StatusInternalServerError)
}
return c.JSON(fiber.Map{"token": t})
return c.JSON(fiber.Map{"token": token})
}
func Restricted(c *fiber.Ctx) error {