forked from mtusi2026/mtusi2026lab3
81 lines
1.7 KiB
Go
81 lines
1.7 KiB
Go
package handlers
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
"unicode/utf8"
|
|
|
|
"mtusi2026lab3/internal/application"
|
|
"mtusi2026lab3/internal/transport/http/dto"
|
|
"mtusi2026lab3/internal/transport/http/middleware"
|
|
"mtusi2026lab3/internal/transport/http/response"
|
|
)
|
|
|
|
const basicChallenge = `Basic realm="messenger", charset="UTF-8"`
|
|
|
|
func (h *Handler) CreateSession(
|
|
w http.ResponseWriter,
|
|
r *http.Request,
|
|
) {
|
|
requestID := middleware.GetRequestID(r.Context())
|
|
|
|
username, password, ok := r.BasicAuth()
|
|
if !ok || username == "" ||
|
|
!utf8.ValidString(username) || !utf8.ValidString(password) {
|
|
writeBasicUnauthorized(w, requestID)
|
|
return
|
|
}
|
|
|
|
session, err := h.service.CreateSession(r.Context(), application.CreateSessionCommand{
|
|
Username: username,
|
|
Password: password,
|
|
})
|
|
if errors.Is(err, application.ErrCredentialState) {
|
|
response.WriteError(
|
|
w,
|
|
http.StatusInternalServerError,
|
|
response.CodeInternalError,
|
|
"stored password hash is invalid",
|
|
requestID,
|
|
)
|
|
return
|
|
}
|
|
if errors.Is(err, application.ErrInvalidCredentials) {
|
|
writeBasicUnauthorized(w, requestID)
|
|
return
|
|
}
|
|
if err != nil {
|
|
response.WriteError(
|
|
w,
|
|
http.StatusServiceUnavailable,
|
|
response.CodeUnavailable,
|
|
"service is temporarily unavailable",
|
|
requestID,
|
|
)
|
|
return
|
|
}
|
|
|
|
h.setSessionCookie(w, session.Token, session.ExpiresAt)
|
|
|
|
response.WriteJSON(
|
|
w,
|
|
http.StatusCreated,
|
|
dto.SessionFromDomain(session),
|
|
requestID,
|
|
)
|
|
}
|
|
func writeBasicUnauthorized(
|
|
w http.ResponseWriter,
|
|
requestID string,
|
|
) {
|
|
w.Header().Set("WWW-Authenticate", basicChallenge)
|
|
|
|
response.WriteError(
|
|
w,
|
|
http.StatusUnauthorized,
|
|
response.CodeUnauthorized,
|
|
"invalid username or password",
|
|
requestID,
|
|
)
|
|
}
|