48 lines
1022 B
Go
48 lines
1022 B
Go
package handler
|
|
|
|
import (
|
|
"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")
|
|
|
|
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)
|
|
}
|
|
|
|
token, err := utils.GenerateToken(profile)
|
|
if err != nil {
|
|
return c.SendStatus(fiber.StatusInternalServerError)
|
|
}
|
|
|
|
return c.JSON(fiber.Map{"token": token})
|
|
}
|
|
|
|
func Restricted(c *fiber.Ctx) error {
|
|
user := c.Locals("user").(*jwt.Token)
|
|
claims := user.Claims.(jwt.MapClaims)
|
|
name := claims["name"].(string)
|
|
return c.SendString("Welcome " + name)
|
|
}
|