forked from mtusi2026/mtusi2026lab2
feat: persist data in PostgreSQL and add Basic/Bearer sessions in Redis
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user