forked from mtusi2026/mtusi2026lab2
424 lines
12 KiB
Go
424 lines
12 KiB
Go
package handler
|
|
|
|
import (
|
|
_ "embed"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
"unicode/utf8"
|
|
|
|
"github.com/google/uuid"
|
|
"messenger/internal/model"
|
|
"messenger/internal/store"
|
|
)
|
|
|
|
//go:embed openapi.json
|
|
var openAPISpec []byte
|
|
|
|
const swaggerUIHTML = `<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title>MTUCI Messenger API (Lab 2) - Swagger UI</title>
|
|
<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css" />
|
|
<style>
|
|
body { margin: 0; background: #fafafa; }
|
|
.swagger-ui .topbar { display: none; }
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<div id="swagger-ui"></div>
|
|
<script src="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js"></script>
|
|
<script>
|
|
window.onload = function() {
|
|
SwaggerUIBundle({
|
|
url: "/openapi.json",
|
|
dom_id: '#swagger-ui',
|
|
deepLinking: true,
|
|
presets: [
|
|
SwaggerUIBundle.presets.apis,
|
|
SwaggerUIBundle.SwaggerUIStandalonePreset
|
|
],
|
|
layout: "BaseLayout"
|
|
});
|
|
};
|
|
</script>
|
|
</body>
|
|
</html>`
|
|
|
|
type APIHandler struct {
|
|
store store.Store
|
|
sessionTTL int
|
|
}
|
|
|
|
func NewAPIHandler(st store.Store, sessionTTL int) *APIHandler {
|
|
if sessionTTL <= 0 {
|
|
sessionTTL = 3600
|
|
}
|
|
return &APIHandler{
|
|
store: st,
|
|
sessionTTL: sessionTTL,
|
|
}
|
|
}
|
|
|
|
func decodeJSON(r *http.Request, dst interface{}) error {
|
|
if r.Body == nil {
|
|
return errors.New("request body is missing")
|
|
}
|
|
defer r.Body.Close()
|
|
|
|
dec := json.NewDecoder(r.Body)
|
|
dec.DisallowUnknownFields()
|
|
|
|
if err := dec.Decode(dst); err != nil {
|
|
if errors.Is(err, io.EOF) {
|
|
return errors.New("request body is empty")
|
|
}
|
|
var unmarshalTypeError *json.UnmarshalTypeError
|
|
if errors.As(err, &unmarshalTypeError) {
|
|
return fmt.Errorf("field '%s' has incorrect type (expected %s)", unmarshalTypeError.Field, unmarshalTypeError.Type)
|
|
}
|
|
return fmt.Errorf("malformed JSON or unexpected field: %v", err)
|
|
}
|
|
|
|
if dec.More() {
|
|
return errors.New("request body contains multiple JSON values")
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func writeStoreError(w http.ResponseWriter, r *http.Request, err error) {
|
|
switch {
|
|
case errors.Is(err, store.ErrConflict):
|
|
WriteError(w, r, http.StatusConflict, "conflict", "resource conflict")
|
|
case errors.Is(err, store.ErrNotFound):
|
|
WriteError(w, r, http.StatusNotFound, "not_found", "resource not found or access denied")
|
|
case errors.Is(err, store.ErrUnauthorized):
|
|
WriteBearerUnauthorized(w, r, "unauthorized")
|
|
case errors.Is(err, store.ErrUnavailable):
|
|
WriteError(w, r, http.StatusServiceUnavailable, "unavailable", "storage dependency is temporarily unavailable")
|
|
case errors.Is(err, store.ErrBadRequest):
|
|
WriteError(w, r, http.StatusBadRequest, "invalid_request", err.Error())
|
|
default:
|
|
WriteError(w, r, http.StatusInternalServerError, "internal_error", "internal server error")
|
|
}
|
|
}
|
|
|
|
func (h *APIHandler) HandleLiveness(w http.ResponseWriter, r *http.Request) {
|
|
WriteJSON(w, r, http.StatusOK, model.HealthResponse{Status: "ok"})
|
|
}
|
|
|
|
func (h *APIHandler) HandleReadiness(w http.ResponseWriter, r *http.Request) {
|
|
if err := h.store.Ready(r.Context()); err != nil {
|
|
WriteError(w, r, http.StatusServiceUnavailable, "unavailable", "database dependency is not ready")
|
|
return
|
|
}
|
|
WriteJSON(w, r, http.StatusOK, model.HealthResponse{Status: "ok"})
|
|
}
|
|
|
|
func (h *APIHandler) HandleRegisterUser(w http.ResponseWriter, r *http.Request) {
|
|
var req model.CreateUserRequest
|
|
if err := decodeJSON(r, &req); err != nil {
|
|
WriteError(w, r, http.StatusBadRequest, "invalid_request", err.Error())
|
|
return
|
|
}
|
|
|
|
user, err := h.store.CreateUser(r.Context(), req)
|
|
if err != nil {
|
|
writeStoreError(w, r, err)
|
|
return
|
|
}
|
|
|
|
WriteJSON(w, r, http.StatusCreated, user)
|
|
}
|
|
|
|
func (h *APIHandler) HandleCreateSession(w http.ResponseWriter, r *http.Request) {
|
|
// Contract: POST /auth/sessions accepts ONLY Authorization: Basic <base64(username:password)>, without JSON body.
|
|
if r.Body != nil {
|
|
defer r.Body.Close()
|
|
var buf [1]byte
|
|
n, _ := r.Body.Read(buf[:])
|
|
if n > 0 {
|
|
WriteError(w, r, http.StatusBadRequest, "invalid_request", "POST /api/v1/auth/sessions must not include a request body")
|
|
return
|
|
}
|
|
}
|
|
|
|
authHeader := strings.TrimSpace(r.Header.Get("Authorization"))
|
|
if authHeader == "" {
|
|
WriteBasicUnauthorized(w, r, "invalid credentials")
|
|
return
|
|
}
|
|
|
|
parts := strings.SplitN(authHeader, " ", 2)
|
|
if len(parts) != 2 || !strings.EqualFold(parts[0], "Basic") {
|
|
WriteBasicUnauthorized(w, r, "invalid credentials")
|
|
return
|
|
}
|
|
|
|
b64Payload := strings.TrimSpace(parts[1])
|
|
decoded, err := base64.StdEncoding.DecodeString(b64Payload)
|
|
if err != nil || !utf8.Valid(decoded) {
|
|
WriteBasicUnauthorized(w, r, "invalid credentials")
|
|
return
|
|
}
|
|
|
|
credParts := strings.SplitN(string(decoded), ":", 2)
|
|
if len(credParts) != 2 {
|
|
WriteBasicUnauthorized(w, r, "invalid credentials")
|
|
return
|
|
}
|
|
|
|
username := credParts[0]
|
|
password := credParts[1]
|
|
|
|
sess, err := h.store.AuthenticateAndCreateSession(r.Context(), username, password, h.sessionTTL)
|
|
if err != nil {
|
|
if errors.Is(err, store.ErrUnavailable) {
|
|
WriteError(w, r, http.StatusServiceUnavailable, "unavailable", "storage dependency is temporarily unavailable")
|
|
return
|
|
}
|
|
WriteBasicUnauthorized(w, r, "invalid credentials")
|
|
return
|
|
}
|
|
|
|
WriteJSON(w, r, http.StatusCreated, sess)
|
|
}
|
|
|
|
func (h *APIHandler) HandleRevokeSession(w http.ResponseWriter, r *http.Request) {
|
|
rawToken := GetAuthToken(r.Context())
|
|
if rawToken == "" {
|
|
WriteBearerUnauthorized(w, r, "unauthenticated")
|
|
return
|
|
}
|
|
|
|
if err := h.store.RevokeSession(r.Context(), rawToken); err != nil {
|
|
if errors.Is(err, store.ErrUnavailable) {
|
|
WriteError(w, r, http.StatusServiceUnavailable, "unavailable", "storage dependency is temporarily unavailable")
|
|
return
|
|
}
|
|
WriteBearerUnauthorized(w, r, "session already revoked or expired")
|
|
return
|
|
}
|
|
|
|
reqID := GetRequestID(r.Context())
|
|
w.Header().Set("X-Request-Id", reqID)
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
func (h *APIHandler) HandleCurrentUser(w http.ResponseWriter, r *http.Request) {
|
|
user := GetAuthUser(r.Context())
|
|
if user == nil {
|
|
WriteBearerUnauthorized(w, r, "unauthenticated")
|
|
return
|
|
}
|
|
WriteJSON(w, r, http.StatusOK, user)
|
|
}
|
|
|
|
func (h *APIHandler) HandleCreateChat(w http.ResponseWriter, r *http.Request) {
|
|
caller := GetAuthUser(r.Context())
|
|
if caller == nil {
|
|
WriteBearerUnauthorized(w, r, "unauthenticated")
|
|
return
|
|
}
|
|
|
|
var req model.CreateChatRequest
|
|
if err := decodeJSON(r, &req); err != nil {
|
|
WriteError(w, r, http.StatusBadRequest, "invalid_request", err.Error())
|
|
return
|
|
}
|
|
|
|
chat, err := h.store.CreateChat(r.Context(), caller.ID, req)
|
|
if err != nil {
|
|
writeStoreError(w, r, err)
|
|
return
|
|
}
|
|
|
|
WriteJSON(w, r, http.StatusCreated, chat)
|
|
}
|
|
|
|
func (h *APIHandler) HandleListChats(w http.ResponseWriter, r *http.Request) {
|
|
caller := GetAuthUser(r.Context())
|
|
if caller == nil {
|
|
WriteBearerUnauthorized(w, r, "unauthenticated")
|
|
return
|
|
}
|
|
|
|
limit := 50
|
|
limitStr := r.URL.Query().Get("limit")
|
|
if limitStr != "" {
|
|
l, err := strconv.Atoi(limitStr)
|
|
if err != nil || l < 1 || l > 100 {
|
|
WriteError(w, r, http.StatusBadRequest, "invalid_request", "limit must be an integer between 1 and 100")
|
|
return
|
|
}
|
|
limit = l
|
|
}
|
|
|
|
cursor := r.URL.Query().Get("cursor")
|
|
page, err := h.store.ListChats(r.Context(), caller.ID, limit, cursor)
|
|
if err != nil {
|
|
writeStoreError(w, r, err)
|
|
return
|
|
}
|
|
|
|
WriteJSON(w, r, http.StatusOK, page)
|
|
}
|
|
|
|
func (h *APIHandler) HandleGetChat(w http.ResponseWriter, r *http.Request) {
|
|
caller := GetAuthUser(r.Context())
|
|
if caller == nil {
|
|
WriteBearerUnauthorized(w, r, "unauthenticated")
|
|
return
|
|
}
|
|
|
|
chatID := r.PathValue("chat_id")
|
|
if _, err := uuid.Parse(chatID); err != nil {
|
|
WriteError(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id UUID")
|
|
return
|
|
}
|
|
|
|
chat, err := h.store.GetChat(r.Context(), caller.ID, chatID)
|
|
if err != nil {
|
|
writeStoreError(w, r, err)
|
|
return
|
|
}
|
|
|
|
WriteJSON(w, r, http.StatusOK, chat)
|
|
}
|
|
|
|
func (h *APIHandler) HandleCreateMessage(w http.ResponseWriter, r *http.Request) {
|
|
caller := GetAuthUser(r.Context())
|
|
if caller == nil {
|
|
WriteBearerUnauthorized(w, r, "unauthenticated")
|
|
return
|
|
}
|
|
|
|
chatID := r.PathValue("chat_id")
|
|
if _, err := uuid.Parse(chatID); err != nil {
|
|
WriteError(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id UUID")
|
|
return
|
|
}
|
|
|
|
var req model.CreateMessageRequest
|
|
if err := decodeJSON(r, &req); err != nil {
|
|
WriteError(w, r, http.StatusBadRequest, "invalid_request", err.Error())
|
|
return
|
|
}
|
|
|
|
msg, err := h.store.CreateMessage(r.Context(), caller.ID, chatID, req)
|
|
if err != nil {
|
|
writeStoreError(w, r, err)
|
|
return
|
|
}
|
|
|
|
WriteJSON(w, r, http.StatusCreated, msg)
|
|
}
|
|
|
|
func (h *APIHandler) HandleListMessages(w http.ResponseWriter, r *http.Request) {
|
|
caller := GetAuthUser(r.Context())
|
|
if caller == nil {
|
|
WriteBearerUnauthorized(w, r, "unauthenticated")
|
|
return
|
|
}
|
|
|
|
chatID := r.PathValue("chat_id")
|
|
if _, err := uuid.Parse(chatID); err != nil {
|
|
WriteError(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id UUID")
|
|
return
|
|
}
|
|
|
|
limit := 50
|
|
limitStr := r.URL.Query().Get("limit")
|
|
if limitStr != "" {
|
|
l, err := strconv.Atoi(limitStr)
|
|
if err != nil || l < 1 || l > 100 {
|
|
WriteError(w, r, http.StatusBadRequest, "invalid_request", "limit must be an integer between 1 and 100")
|
|
return
|
|
}
|
|
limit = l
|
|
}
|
|
|
|
cursor := r.URL.Query().Get("cursor")
|
|
page, err := h.store.ListMessages(r.Context(), caller.ID, chatID, limit, cursor)
|
|
if err != nil {
|
|
writeStoreError(w, r, err)
|
|
return
|
|
}
|
|
|
|
WriteJSON(w, r, http.StatusOK, page)
|
|
}
|
|
|
|
func (h *APIHandler) HandleInternalStats(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Query().Get("reset") == "1" {
|
|
h.store.ResetStats()
|
|
}
|
|
if mode := r.URL.Query().Get("mode"); mode != "" {
|
|
h.store.SetCacheMode(mode)
|
|
}
|
|
WriteJSON(w, r, http.StatusOK, h.store.Stats(r.Context()))
|
|
}
|
|
|
|
func (h *APIHandler) HandleOpenAPISpec(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
w.Header().Set("X-Request-Id", GetRequestID(r.Context()))
|
|
w.WriteHeader(http.StatusOK)
|
|
_, _ = w.Write(openAPISpec)
|
|
}
|
|
|
|
func (h *APIHandler) HandleSwaggerUI(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
|
w.Header().Set("X-Request-Id", GetRequestID(r.Context()))
|
|
w.WriteHeader(http.StatusOK)
|
|
_, _ = w.Write([]byte(swaggerUIHTML))
|
|
}
|
|
|
|
func (h *APIHandler) HandleNotFound(w http.ResponseWriter, r *http.Request) {
|
|
WriteError(w, r, http.StatusNotFound, "not_found", fmt.Sprintf("route %s %s not found", r.Method, r.URL.Path))
|
|
}
|
|
|
|
func RegisterRoutes(st store.Store, sessionTTL int) http.Handler {
|
|
api := NewAPIHandler(st, sessionTTL)
|
|
mux := http.NewServeMux()
|
|
|
|
// Documentation & schema
|
|
mux.HandleFunc("GET /docs", api.HandleSwaggerUI)
|
|
mux.HandleFunc("GET /docs/", api.HandleSwaggerUI)
|
|
mux.HandleFunc("GET /openapi.json", api.HandleOpenAPISpec)
|
|
|
|
// Internal diagnostics for Grade 5 cache & SQL experiments
|
|
mux.HandleFunc("GET /internal/stats", api.HandleInternalStats)
|
|
mux.HandleFunc("POST /internal/stats", api.HandleInternalStats)
|
|
|
|
// Public routes
|
|
mux.HandleFunc("GET /health/live", api.HandleLiveness)
|
|
mux.HandleFunc("GET /health/ready", api.HandleReadiness)
|
|
mux.HandleFunc("POST /api/v1/users", api.HandleRegisterUser)
|
|
mux.HandleFunc("POST /api/v1/auth/sessions", api.HandleCreateSession)
|
|
|
|
// Protected Bearer routes
|
|
mux.HandleFunc("DELETE /api/v1/auth/sessions/current", RequireBearerAuth(st, api.HandleRevokeSession))
|
|
mux.HandleFunc("GET /api/v1/users/me", RequireBearerAuth(st, api.HandleCurrentUser))
|
|
mux.HandleFunc("POST /api/v1/chats", RequireBearerAuth(st, api.HandleCreateChat))
|
|
mux.HandleFunc("GET /api/v1/chats", RequireBearerAuth(st, api.HandleListChats))
|
|
mux.HandleFunc("GET /api/v1/chats/{chat_id}", RequireBearerAuth(st, api.HandleGetChat))
|
|
mux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", RequireBearerAuth(st, api.HandleCreateMessage))
|
|
mux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", RequireBearerAuth(st, api.HandleListMessages))
|
|
|
|
// Fallback 404 handler
|
|
mux.HandleFunc("/", api.HandleNotFound)
|
|
|
|
var handler http.Handler = mux
|
|
handler = LoggingMiddleware(handler)
|
|
handler = RequestIDMiddleware(handler)
|
|
|
|
return handler
|
|
}
|