feat(handler): lab2 AuthHandler.CreateSession с Basic
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
"high-loud-apps-labs/internal/httpapi/dto"
|
||||
"high-loud-apps-labs/internal/service"
|
||||
)
|
||||
|
||||
type AuthHandler struct {
|
||||
sessions *service.SessionService
|
||||
}
|
||||
|
||||
func NewAuthHandler(sessions *service.SessionService) *AuthHandler {
|
||||
return &AuthHandler{sessions: sessions}
|
||||
}
|
||||
|
||||
func (h *AuthHandler) CreateSession(c *gin.Context) {
|
||||
username, password, err := parseBasicAuth(c)
|
||||
if err != nil {
|
||||
respondBasicChallenge(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
session, token, user, err := h.sessions.Login(c.Request.Context(), username, password)
|
||||
if err != nil {
|
||||
respondBasicChallenge(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, dto.SessionResponseFromDomain(session, token, user))
|
||||
}
|
||||
|
||||
// parseBasicAuth читает Authorization: Basic base64(username:password).
|
||||
func parseBasicAuth(c *gin.Context) (string, string, error) {
|
||||
const prefix = "Basic "
|
||||
|
||||
auth := c.GetHeader("Authorization")
|
||||
if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
|
||||
return "", "", &domain.UnauthorizedError{Reason: "требуется Basic"}
|
||||
}
|
||||
|
||||
decoded, err := base64.StdEncoding.DecodeString(auth[len(prefix):])
|
||||
if err != nil {
|
||||
return "", "", &domain.UnauthorizedError{Reason: "некорректный Base64"}
|
||||
}
|
||||
|
||||
username, password, ok := strings.Cut(string(decoded), ":")
|
||||
if !ok || username == "" {
|
||||
return "", "", &domain.UnauthorizedError{Reason: "некорректный Basic-формат"}
|
||||
}
|
||||
|
||||
return username, password, nil
|
||||
}
|
||||
@@ -33,3 +33,12 @@ func respondError(c *gin.Context, err error) {
|
||||
reqID := middleware.GetRequestID(c)
|
||||
c.JSON(dto.StatusFromError(err), dto.ErrorFromDomain(err, reqID))
|
||||
}
|
||||
|
||||
// respondBasicChallenge выставляет WWW-Authenticate для 401 на /auth/sessions.
|
||||
// На не-401 ответах заголовок не ставится как по контракту нужно
|
||||
func respondBasicChallenge(c *gin.Context, err error) {
|
||||
if dto.StatusFromError(err) == 401 {
|
||||
c.Header("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
}
|
||||
respondError(c, err)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user