Files
kontor/kontor-echo/pkg/handler/auth.go
T
2026-01-03 04:07:42 +01:00

67 lines
1.4 KiB
Go

package handler
import (
"context"
"kontor-api-echo/pkg/schema"
"kontor-api-echo/pkg/utils"
"net/http"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/labstack/echo/v4"
"github.com/uptrace/bun"
)
type jwtCustomClaims struct {
Name string `json:"name"`
Admin bool `json:"admin"`
jwt.RegisteredClaims
}
func Login(c echo.Context) 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.String(http.StatusInternalServerError, err.Error())
}
if !utils.ComparePassword(profile.Password, pass) {
return echo.ErrUnauthorized
}
// Set custom claims
claims := &jwtCustomClaims{
"Jon Snow",
true,
jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * 72)),
},
}
// Create token with claims
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// Generate encoded token and send it as response.
t, err := token.SignedString([]byte("secret"))
if err != nil {
return err
}
return c.JSON(http.StatusOK, echo.Map{"token": t})
}
func restricted(c echo.Context) error {
user := c.Get("user").(*jwt.Token)
claims := user.Claims.(*jwtCustomClaims)
name := claims.Name
return c.String(http.StatusOK, "Welcome "+name+"!")
}