54 lines
1.2 KiB
Go
54 lines
1.2 KiB
Go
package handler
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"errors"
|
|
"net/http"
|
|
"strings"
|
|
"unicode/utf8"
|
|
|
|
"messenger/internal/domain"
|
|
)
|
|
|
|
func (h *Handler) CreateSession(w http.ResponseWriter, r *http.Request) {
|
|
username, password, ok := basicCredentials(r)
|
|
if !ok {
|
|
h.failLogin(w, r, domain.ErrUnauthorized)
|
|
return
|
|
}
|
|
session, err := h.auth.Login(r.Context(), username, password)
|
|
if err != nil {
|
|
h.failLogin(w, r, err)
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusCreated, toSessionResponse(session))
|
|
}
|
|
|
|
func (h *Handler) failLogin(w http.ResponseWriter, r *http.Request, err error) {
|
|
if errors.Is(err, domain.ErrUnauthorized) {
|
|
w.Header().Set(headerWWWAuthenticate, basicChallenge)
|
|
}
|
|
h.fail(w, r, err)
|
|
}
|
|
|
|
func (h *Handler) DeleteSession(w http.ResponseWriter, r *http.Request) {
|
|
if err := h.auth.Logout(r.Context(), current(r).token); err != nil {
|
|
h.fail(w, r, err)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
func basicCredentials(r *http.Request) (string, string, bool) {
|
|
encoded, ok := authCredentials(r, "Basic")
|
|
if !ok {
|
|
return "", "", false
|
|
}
|
|
raw, err := base64.StdEncoding.DecodeString(encoded)
|
|
if err != nil || !utf8.Valid(raw) {
|
|
return "", "", false
|
|
}
|
|
username, password, ok := strings.Cut(string(raw), ":")
|
|
return username, password, ok
|
|
}
|