Rework request context handler

This commit is contained in:
2024-11-03 19:17:10 +01:00
parent dfd9544fba
commit c8cc854fd6
14 changed files with 217 additions and 217 deletions

View File

@@ -0,0 +1,146 @@
package handlers
import (
"encoding/json"
"net/http"
"novamd/internal/auth"
"novamd/internal/httpcontext"
"novamd/internal/models"
"golang.org/x/crypto/bcrypt"
)
type LoginRequest struct {
Email string `json:"email"`
Password string `json:"password"`
}
type LoginResponse struct {
AccessToken string `json:"accessToken"`
RefreshToken string `json:"refreshToken"`
User *models.User `json:"user"`
Session *auth.Session `json:"session"`
}
type RefreshRequest struct {
RefreshToken string `json:"refreshToken"`
}
type RefreshResponse struct {
AccessToken string `json:"accessToken"`
}
// Login handles user authentication and returns JWT tokens
func (h *Handler) Login(authService *auth.SessionService) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req LoginRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
// Validate request
if req.Email == "" || req.Password == "" {
http.Error(w, "Email and password are required", http.StatusBadRequest)
return
}
// Get user from database
user, err := h.DB.GetUserByEmail(req.Email)
if err != nil {
http.Error(w, "Invalid credentials", http.StatusUnauthorized)
return
}
// Verify password
err = bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Password))
if err != nil {
http.Error(w, "Invalid credentials", http.StatusUnauthorized)
return
}
// Create session and generate tokens
session, accessToken, err := authService.CreateSession(user.ID, string(user.Role))
if err != nil {
http.Error(w, "Failed to create session", http.StatusInternalServerError)
return
}
// Prepare response
response := LoginResponse{
AccessToken: accessToken,
RefreshToken: session.RefreshToken,
User: user,
Session: session,
}
respondJSON(w, response)
}
}
// Logout invalidates the user's session
func (h *Handler) Logout(authService *auth.SessionService) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
sessionID := r.Header.Get("X-Session-ID")
if sessionID == "" {
http.Error(w, "Session ID required", http.StatusBadRequest)
return
}
err := authService.InvalidateSession(sessionID)
if err != nil {
http.Error(w, "Failed to logout", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
}
// RefreshToken generates a new access token using a refresh token
func (h *Handler) RefreshToken(authService *auth.SessionService) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req RefreshRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
if req.RefreshToken == "" {
http.Error(w, "Refresh token required", http.StatusBadRequest)
return
}
// Generate new access token
accessToken, err := authService.RefreshSession(req.RefreshToken)
if err != nil {
http.Error(w, "Invalid refresh token", http.StatusUnauthorized)
return
}
response := RefreshResponse{
AccessToken: accessToken,
}
respondJSON(w, response)
}
}
// GetCurrentUser returns the currently authenticated user
func (h *Handler) GetCurrentUser() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx, ok := httpcontext.GetRequestContext(w, r)
if !ok {
return
}
// Get user from database
user, err := h.DB.GetUserByID(ctx.UserID)
if err != nil {
http.Error(w, "User not found", http.StatusNotFound)
return
}
respondJSON(w, user)
}
}

View File

@@ -0,0 +1,168 @@
package handlers
import (
"encoding/json"
"io"
"net/http"
"novamd/internal/httpcontext"
"github.com/go-chi/chi/v5"
)
func (h *Handler) ListFiles() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx, ok := httpcontext.GetRequestContext(w, r)
if !ok {
return
}
files, err := h.FS.ListFilesRecursively(ctx.UserID, ctx.Workspace.ID)
if err != nil {
http.Error(w, "Failed to list files", http.StatusInternalServerError)
return
}
respondJSON(w, files)
}
}
func (h *Handler) LookupFileByName() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx, ok := httpcontext.GetRequestContext(w, r)
if !ok {
return
}
filename := r.URL.Query().Get("filename")
if filename == "" {
http.Error(w, "Filename is required", http.StatusBadRequest)
return
}
filePaths, err := h.FS.FindFileByName(ctx.UserID, ctx.Workspace.ID, filename)
if err != nil {
http.Error(w, "File not found", http.StatusNotFound)
return
}
respondJSON(w, map[string][]string{"paths": filePaths})
}
}
func (h *Handler) GetFileContent() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx, ok := httpcontext.GetRequestContext(w, r)
if !ok {
return
}
filePath := chi.URLParam(r, "*")
content, err := h.FS.GetFileContent(ctx.UserID, ctx.Workspace.ID, filePath)
if err != nil {
http.Error(w, "Failed to read file", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "text/plain")
w.Write(content)
}
}
func (h *Handler) SaveFile() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx, ok := httpcontext.GetRequestContext(w, r)
if !ok {
return
}
filePath := chi.URLParam(r, "*")
content, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Failed to read request body", http.StatusBadRequest)
return
}
err = h.FS.SaveFile(ctx.UserID, ctx.Workspace.ID, filePath, content)
if err != nil {
http.Error(w, "Failed to save file", http.StatusInternalServerError)
return
}
respondJSON(w, map[string]string{"message": "File saved successfully"})
}
}
func (h *Handler) DeleteFile() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx, ok := httpcontext.GetRequestContext(w, r)
if !ok {
return
}
filePath := chi.URLParam(r, "*")
err := h.FS.DeleteFile(ctx.UserID, ctx.Workspace.ID, filePath)
if err != nil {
http.Error(w, "Failed to delete file", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("File deleted successfully"))
}
}
func (h *Handler) GetLastOpenedFile() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx, ok := httpcontext.GetRequestContext(w, r)
if !ok {
return
}
filePath, err := h.DB.GetLastOpenedFile(ctx.Workspace.ID)
if err != nil {
http.Error(w, "Failed to get last opened file", http.StatusInternalServerError)
return
}
if _, err := h.FS.ValidatePath(ctx.UserID, ctx.Workspace.ID, filePath); err != nil {
http.Error(w, "Invalid file path", http.StatusBadRequest)
return
}
respondJSON(w, map[string]string{"lastOpenedFilePath": filePath})
}
}
func (h *Handler) UpdateLastOpenedFile() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx, ok := httpcontext.GetRequestContext(w, r)
if !ok {
return
}
var requestBody struct {
FilePath string `json:"filePath"`
}
if err := json.NewDecoder(r.Body).Decode(&requestBody); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
// Validate the file path exists in the workspace
if requestBody.FilePath != "" {
if _, err := h.FS.ValidatePath(ctx.UserID, ctx.Workspace.ID, requestBody.FilePath); err != nil {
http.Error(w, "Invalid file path", http.StatusBadRequest)
return
}
}
if err := h.DB.UpdateLastOpenedFile(ctx.Workspace.ID, requestBody.FilePath); err != nil {
http.Error(w, "Failed to update last opened file", http.StatusInternalServerError)
return
}
respondJSON(w, map[string]string{"message": "Last opened file updated successfully"})
}
}

View File

@@ -0,0 +1,56 @@
package handlers
import (
"encoding/json"
"net/http"
"novamd/internal/httpcontext"
)
func (h *Handler) StageCommitAndPush() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx, ok := httpcontext.GetRequestContext(w, r)
if !ok {
return
}
var requestBody struct {
Message string `json:"message"`
}
if err := json.NewDecoder(r.Body).Decode(&requestBody); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
if requestBody.Message == "" {
http.Error(w, "Commit message is required", http.StatusBadRequest)
return
}
err := h.FS.StageCommitAndPush(ctx.UserID, ctx.Workspace.ID, requestBody.Message)
if err != nil {
http.Error(w, "Failed to stage, commit, and push changes: "+err.Error(), http.StatusInternalServerError)
return
}
respondJSON(w, map[string]string{"message": "Changes staged, committed, and pushed successfully"})
}
}
func (h *Handler) PullChanges() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx, ok := httpcontext.GetRequestContext(w, r)
if !ok {
return
}
err := h.FS.Pull(ctx.UserID, ctx.Workspace.ID)
if err != nil {
http.Error(w, "Failed to pull changes: "+err.Error(), http.StatusInternalServerError)
return
}
respondJSON(w, map[string]string{"message": "Pulled changes from remote"})
}
}

View File

@@ -0,0 +1,30 @@
package handlers
import (
"encoding/json"
"net/http"
"novamd/internal/db"
"novamd/internal/filesystem"
)
// Handler provides common functionality for all handlers
type Handler struct {
DB *db.DB
FS *filesystem.FileSystem
}
// NewHandler creates a new handler with the given dependencies
func NewHandler(db *db.DB, fs *filesystem.FileSystem) *Handler {
return &Handler{
DB: db,
FS: fs,
}
}
// respondJSON is a helper to send JSON responses
func respondJSON(w http.ResponseWriter, data interface{}) {
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(data); err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
}
}

View File

@@ -0,0 +1,70 @@
package handlers
import (
"net/http"
"os"
"path/filepath"
"strings"
)
// StaticHandler serves static files with support for SPA routing and pre-compressed files
type StaticHandler struct {
staticPath string
}
func NewStaticHandler(staticPath string) *StaticHandler {
return &StaticHandler{
staticPath: staticPath,
}
}
func (h *StaticHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Get the requested path
requestedPath := r.URL.Path
fullPath := filepath.Join(h.staticPath, requestedPath)
cleanPath := filepath.Clean(fullPath)
// Security check to prevent directory traversal
if !strings.HasPrefix(cleanPath, h.staticPath) {
http.Error(w, "Invalid path", http.StatusBadRequest)
return
}
// Set cache headers for assets
if strings.HasPrefix(requestedPath, "/assets/") {
w.Header().Set("Cache-Control", "public, max-age=31536000") // 1 year
}
// Check if file exists (not counting .gz files)
stat, err := os.Stat(cleanPath)
if err != nil || stat.IsDir() {
// Serve index.html for SPA routing
indexPath := filepath.Join(h.staticPath, "index.html")
http.ServeFile(w, r, indexPath)
return
}
// Check for pre-compressed version
if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
gzPath := cleanPath + ".gz"
if _, err := os.Stat(gzPath); err == nil {
w.Header().Set("Content-Encoding", "gzip")
// Set proper content type based on original file
switch filepath.Ext(cleanPath) {
case ".js":
w.Header().Set("Content-Type", "application/javascript")
case ".css":
w.Header().Set("Content-Type", "text/css")
case ".html":
w.Header().Set("Content-Type", "text/html")
}
http.ServeFile(w, r, gzPath)
return
}
}
// Serve original file
http.ServeFile(w, r, cleanPath)
}

View File

@@ -0,0 +1,24 @@
package handlers
import (
"net/http"
"novamd/internal/httpcontext"
)
func (h *Handler) GetUser() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx, ok := httpcontext.GetRequestContext(w, r)
if !ok {
return
}
user, err := h.DB.GetUserByID(ctx.UserID)
if err != nil {
http.Error(w, "Failed to get user", http.StatusInternalServerError)
return
}
respondJSON(w, user)
}
}

View File

@@ -0,0 +1,235 @@
package handlers
import (
"encoding/json"
"net/http"
"novamd/internal/httpcontext"
"novamd/internal/models"
)
func (h *Handler) ListWorkspaces() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx, ok := httpcontext.GetRequestContext(w, r)
if !ok {
return
}
workspaces, err := h.DB.GetWorkspacesByUserID(ctx.UserID)
if err != nil {
http.Error(w, "Failed to list workspaces", http.StatusInternalServerError)
return
}
respondJSON(w, workspaces)
}
}
func (h *Handler) CreateWorkspace() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx, ok := httpcontext.GetRequestContext(w, r)
if !ok {
return
}
var workspace models.Workspace
if err := json.NewDecoder(r.Body).Decode(&workspace); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
workspace.UserID = ctx.UserID
if err := h.DB.CreateWorkspace(&workspace); err != nil {
http.Error(w, "Failed to create workspace", http.StatusInternalServerError)
return
}
if err := h.FS.InitializeUserWorkspace(workspace.UserID, workspace.ID); err != nil {
http.Error(w, "Failed to initialize workspace directory", http.StatusInternalServerError)
return
}
respondJSON(w, workspace)
}
}
func (h *Handler) GetWorkspace() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx, ok := httpcontext.GetRequestContext(w, r)
if !ok {
return
}
respondJSON(w, ctx.Workspace)
}
}
func gitSettingsChanged(new, old *models.Workspace) bool {
// Check if Git was enabled/disabled
if new.GitEnabled != old.GitEnabled {
return true
}
// If Git is enabled, check if any settings changed
if new.GitEnabled {
return new.GitURL != old.GitURL ||
new.GitUser != old.GitUser ||
new.GitToken != old.GitToken
}
return false
}
func (h *Handler) UpdateWorkspace() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx, ok := httpcontext.GetRequestContext(w, r)
if !ok {
return
}
var workspace models.Workspace
if err := json.NewDecoder(r.Body).Decode(&workspace); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
// Set IDs from the request
workspace.ID = ctx.Workspace.ID
workspace.UserID = ctx.UserID
// Validate the workspace
if err := workspace.Validate(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Handle Git repository setup/teardown if Git settings changed
if gitSettingsChanged(&workspace, ctx.Workspace) {
if workspace.GitEnabled {
if err := h.FS.SetupGitRepo(
ctx.UserID,
ctx.Workspace.ID,
workspace.GitURL,
workspace.GitUser,
workspace.GitToken,
); err != nil {
http.Error(w, "Failed to setup git repo: "+err.Error(), http.StatusInternalServerError)
return
}
} else {
h.FS.DisableGitRepo(ctx.UserID, ctx.Workspace.ID)
}
}
if err := h.DB.UpdateWorkspace(&workspace); err != nil {
http.Error(w, "Failed to update workspace", http.StatusInternalServerError)
return
}
respondJSON(w, workspace)
}
}
func (h *Handler) DeleteWorkspace() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx, ok := httpcontext.GetRequestContext(w, r)
if !ok {
return
}
// Check if this is the user's last workspace
workspaces, err := h.DB.GetWorkspacesByUserID(ctx.UserID)
if err != nil {
http.Error(w, "Failed to get workspaces", http.StatusInternalServerError)
return
}
if len(workspaces) <= 1 {
http.Error(w, "Cannot delete the last workspace", http.StatusBadRequest)
return
}
// Find another workspace to set as last
var nextWorkspaceID int
for _, ws := range workspaces {
if ws.ID != ctx.Workspace.ID {
nextWorkspaceID = ws.ID
break
}
}
// Start transaction
tx, err := h.DB.Begin()
if err != nil {
http.Error(w, "Failed to start transaction", http.StatusInternalServerError)
return
}
defer tx.Rollback()
// Update last workspace ID first
err = h.DB.UpdateLastWorkspaceTx(tx, ctx.UserID, nextWorkspaceID)
if err != nil {
http.Error(w, "Failed to update last workspace", http.StatusInternalServerError)
return
}
// Delete the workspace
err = h.DB.DeleteWorkspaceTx(tx, ctx.Workspace.ID)
if err != nil {
http.Error(w, "Failed to delete workspace", http.StatusInternalServerError)
return
}
// Commit transaction
if err = tx.Commit(); err != nil {
http.Error(w, "Failed to commit transaction", http.StatusInternalServerError)
return
}
// Return the next workspace ID in the response so frontend knows where to redirect
respondJSON(w, map[string]int{"nextWorkspaceId": nextWorkspaceID})
}
}
func (h *Handler) GetLastWorkspace() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx, ok := httpcontext.GetRequestContext(w, r)
if !ok {
return
}
workspaceID, err := h.DB.GetLastWorkspaceID(ctx.UserID)
if err != nil {
http.Error(w, "Failed to get last workspace", http.StatusInternalServerError)
return
}
respondJSON(w, map[string]int{"lastWorkspaceId": workspaceID})
}
}
func (h *Handler) UpdateLastWorkspace() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx, ok := httpcontext.GetRequestContext(w, r)
if !ok {
return
}
var requestBody struct {
WorkspaceID int `json:"workspaceId"`
}
if err := json.NewDecoder(r.Body).Decode(&requestBody); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
if err := h.DB.UpdateLastWorkspace(ctx.UserID, requestBody.WorkspaceID); err != nil {
http.Error(w, "Failed to update last workspace", http.StatusInternalServerError)
return
}
respondJSON(w, map[string]string{"message": "Last workspace updated successfully"})
}
}