package handlers import ( "context" "encoding/json" "fmt" "net/http" "github.com/labstack/echo/v5" "trankilou.fr/lassistanoque/backend/internal/domain" "trankilou.fr/lassistanoque/backend/internal/service/auth" ) func NewAuthGroup(prefix string, e *echo.Group, service *auth.Service) *echo.Group { authHandler := &AuthHandler{ authService: service, } auth := e.Group(prefix) auth.POST("/login", authHandler.Login) auth.GET("/oidc/callback", authHandler.OIDCCallback) auth.POST("/register", authHandler.Register) return auth } type AuthHandler struct { authService *auth.Service } type loginRequest struct { Email string `json:"email" validate:"required,email"` Password string `json:"password" validate:"required"` } type loginResponse struct { AccessToken string `json:"accessToken"` RefreshToken string `json:"refreshToken"` ExpiresAt string `json:"expiresAt"` User *domain.User `json:"user"` } func (h AuthHandler) Login(c *echo.Context) error { var req loginRequest if err := c.Bind(&req); err != nil { return echo.NewHTTPError(http.StatusBadRequest, "invalid request") } if req.Email == "" || req.Password == "" { return echo.NewHTTPError(http.StatusBadRequest, "email and password are required") } creds := auth.Credentials{ Method: "password", Email: req.Email, Password: req.Password, } session, err := h.authService.Login(context.Background(), creds) if err != nil { c.Logger().Error(fmt.Sprintf("error while login: %s", err)) return echo.NewHTTPError(http.StatusUnauthorized, "login error") } resp := loginResponse{ AccessToken: session.AccessToken, RefreshToken: session.RefreshToken, ExpiresAt: session.ExpiresAt.Format("2006-01-02T15:04:05Z07:00"), } resp.User = session.User return c.JSON(http.StatusOK, resp) } func (h AuthHandler) OIDCCallback(c *echo.Context) error { return nil } func (h AuthHandler) Register(c *echo.Context) error { reader := c.Request().Body var registration auth.Registration decoder := json.NewDecoder(reader) err := decoder.Decode(®istration) if err != nil { return c.String(http.StatusBadRequest, "malformatted registration") } user, err := h.authService.Register(registration) if err != nil { return c.String(http.StatusBadRequest, err.Error()) } return c.JSON(http.StatusCreated, user) }