add project kontor-api-echo
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"kontor-api-fiber/pkg/schema"
|
||||
"kontor-api-fiber/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)
|
||||
}
|
||||
Reference in New Issue
Block a user