forked from mtusi2026/mtusi2026lab2
44 lines
1.5 KiB
Go
44 lines
1.5 KiB
Go
package handler
|
|
|
|
import (
|
|
"backend/internal/domain/model"
|
|
"context"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
"unicode/utf8"
|
|
)
|
|
|
|
type sessionRequestKey struct{}
|
|
|
|
func (h *API) CreateSession(ctx context.Context, _ CreateSessionRequestObject) (CreateSessionResponseObject, error) {
|
|
r := ctx.Value(sessionRequestKey{}).(*http.Request)
|
|
username, password, ok := r.BasicAuth()
|
|
if !ok || len(username) > 32 || len(password) > 512 || utf8.RuneCountInString(password) > 128 {
|
|
return nil, model.ErrUnauthorized
|
|
}
|
|
s, err := h.auth.Login(ctx, username, password)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return CreateSession201JSONResponse{Body: Session{Token: s.Token, TokenType: Bearer, ExpiresAt: Timestamp(s.ExpiresAt), User: toUser(s.User)}}, nil
|
|
}
|
|
func (h *API) RevokeSession(ctx context.Context, _ RevokeSessionRequestObject) (RevokeSessionResponseObject, error) {
|
|
r := ctx.Value(sessionRequestKey{}).(*http.Request)
|
|
parts := strings.Fields(r.Header.Get("Authorization"))
|
|
if err := h.auth.Logout(ctx, parts[1]); err != nil {
|
|
return nil, err
|
|
}
|
|
return RevokeSession204Response{}, nil
|
|
}
|
|
func (h *API) requestContext(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
|
|
defer cancel()
|
|
if r.URL.Path == "/api/v1/auth/sessions" {
|
|
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
|
}
|
|
next.ServeHTTP(w, r.WithContext(context.WithValue(ctx, sessionRequestKey{}, r)))
|
|
})
|
|
}
|