forked from mtusi2026/mtusi2026lab3
71 lines
2.1 KiB
Go
71 lines
2.1 KiB
Go
package http
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"errors"
|
|
"net/http"
|
|
"strings"
|
|
"unicode/utf8"
|
|
|
|
"github.com/labstack/echo/v4"
|
|
|
|
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
|
|
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware"
|
|
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
|
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
|
|
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
|
|
)
|
|
|
|
type authHandler struct {
|
|
auth service.AuthService
|
|
}
|
|
|
|
func (h *authHandler) createSession(c echo.Context) error {
|
|
if c.Request().ContentLength > 0 {
|
|
return WriteError(c, &validate.Error{Field: "body", Reason: "must be empty, credentials go in Authorization: Basic"})
|
|
}
|
|
username, password, ok := parseBasic(c.Request().Header.Get(echo.HeaderAuthorization))
|
|
if !ok {
|
|
return middleware.Unauthorized(c, middleware.BasicChallenge, "Invalid credentials")
|
|
}
|
|
|
|
s, err := h.auth.Login(c.Request().Context(), username, password)
|
|
if err != nil {
|
|
if errors.Is(err, domain.ErrUnauthorized) {
|
|
return middleware.Unauthorized(c, middleware.BasicChallenge, "Invalid credentials")
|
|
}
|
|
return WriteError(c, err)
|
|
}
|
|
return c.JSON(http.StatusCreated, dto.SessionResponse{
|
|
Token: s.Token,
|
|
TokenType: "Bearer",
|
|
ExpiresAt: dto.NewTimestamp(s.ExpiresAt),
|
|
User: toUserResponse(s.User),
|
|
})
|
|
}
|
|
|
|
func (h *authHandler) revokeSession(c echo.Context) error {
|
|
tok := c.Get(middleware.AuthTokenKey).(string)
|
|
if err := h.auth.Logout(c.Request().Context(), tok); err != nil {
|
|
return WriteError(c, err)
|
|
}
|
|
return c.NoContent(http.StatusNoContent)
|
|
}
|
|
|
|
|
|
func parseBasic(header string) (username, password string, ok bool) {
|
|
scheme, encoded, found := strings.Cut(header, " ")
|
|
if !found || !strings.EqualFold(scheme, "Basic") {
|
|
return "", "", false
|
|
}
|
|
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(encoded))
|
|
if err != nil || !utf8.Valid(raw) {
|
|
return "", "", false
|
|
}
|
|
username, password, found = strings.Cut(string(raw), ":")
|
|
if !found || username == "" || password == "" {
|
|
return "", "", false
|
|
}
|
|
return username, password, true
|
|
}
|