forked from mtusi2026/mtusi2026lab3
feat: implement lab3 load balancing and idempotency
This commit is contained in:
@@ -0,0 +1,156 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab2/internal/storage"
|
||||
)
|
||||
|
||||
type SessionHandler struct {
|
||||
users *storage.AuthStore
|
||||
sessions *storage.SessionService
|
||||
}
|
||||
|
||||
func NewSessionHandler(
|
||||
users *storage.AuthStore,
|
||||
sessions *storage.SessionService,
|
||||
) *SessionHandler {
|
||||
return &SessionHandler{
|
||||
users: users,
|
||||
sessions: sessions,
|
||||
}
|
||||
}
|
||||
|
||||
type sessionResponse struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
User interface{} `json:"user"`
|
||||
}
|
||||
|
||||
func sessionTTL() time.Duration {
|
||||
seconds := 3600
|
||||
|
||||
if raw := os.Getenv("SESSION_TTL_SECONDS"); raw != "" {
|
||||
if n, err := strconv.Atoi(raw); err == nil && n > 0 {
|
||||
seconds = n
|
||||
}
|
||||
}
|
||||
|
||||
return time.Duration(seconds) * time.Second
|
||||
}
|
||||
|
||||
func (h *SessionHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set(
|
||||
"WWW-Authenticate",
|
||||
`Basic realm="messenger", charset="UTF-8"`,
|
||||
)
|
||||
|
||||
if err := requireEmptyBody(r); err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "request body must be empty")
|
||||
return
|
||||
}
|
||||
|
||||
username, password, ok := r.BasicAuth()
|
||||
if !ok || username == "" || password == "" {
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "invalid credentials")
|
||||
return
|
||||
}
|
||||
|
||||
user, passwordHash, err := h.users.GetUserByUsername(
|
||||
r.Context(), username,
|
||||
)
|
||||
|
||||
if errors.Is(err, storage.ErrUserNotFound) {
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "invalid credentials")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
if !VerifyPassword(password, passwordHash) {
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "invalid credentials")
|
||||
return
|
||||
}
|
||||
|
||||
randomBytes := make([]byte, 32)
|
||||
if _, err := rand.Read(randomBytes); err != nil {
|
||||
writeError(w, r, http.StatusInternalServerError,
|
||||
"internal_error", "internal server error")
|
||||
return
|
||||
}
|
||||
|
||||
token := base64.RawURLEncoding.EncodeToString(randomBytes)
|
||||
createdAt := time.Now().UTC().Truncate(time.Microsecond)
|
||||
expiresAt := createdAt.Add(sessionTTL())
|
||||
|
||||
err = h.sessions.CreateSession(
|
||||
r.Context(),
|
||||
token,
|
||||
user.ID,
|
||||
createdAt,
|
||||
expiresAt,
|
||||
)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Del("WWW-Authenticate")
|
||||
|
||||
writeJSON(w, http.StatusCreated, sessionResponse{
|
||||
Token: token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: expiresAt,
|
||||
User: user,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *SessionHandler) Delete(w http.ResponseWriter, r *http.Request) {
|
||||
authorization := r.Header.Get("Authorization")
|
||||
|
||||
if !strings.HasPrefix(authorization, "Bearer ") {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
|
||||
token := strings.TrimPrefix(authorization, "Bearer ")
|
||||
if token == "" || strings.ContainsAny(token, " \t\r\n") {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
|
||||
err := h.sessions.RevokeSession(r.Context(), token)
|
||||
|
||||
if errors.Is(err, storage.ErrSessionNotFound) {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
writeError(w, r, http.StatusUnauthorized,
|
||||
"unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable,
|
||||
"unavailable", "service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
Reference in New Issue
Block a user