File size: 2,688 Bytes
eb846d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import express, { Request, Response, NextFunction } from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import fs from 'fs';
import { auth } from './auth.js';
import { initializeDefaultUser } from '../models/User.js';
import config from '../config/index.js';

// Create __dirname equivalent for ES modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// Try to find the correct frontend file path
const findFrontendPath = (): string => {
  // First try development environment path
  const devPath = path.join(dirname(__dirname), 'frontend', 'dist', 'index.html');
  if (fs.existsSync(devPath)) {
    return path.join(dirname(__dirname), 'frontend', 'dist');
  }

  // Try npm/npx installed path (remove /dist directory)
  const npmPath = path.join(dirname(dirname(__dirname)), 'frontend', 'dist', 'index.html');
  if (fs.existsSync(npmPath)) {
    return path.join(dirname(dirname(__dirname)), 'frontend', 'dist');
  }

  // If none of the above paths exist, return the most reasonable default path and log a warning
  console.warn('Warning: Could not locate frontend files. Using default path.');
  return path.join(dirname(__dirname), 'frontend', 'dist');
};

const frontendPath = findFrontendPath();

export const errorHandler = (
  err: Error,
  _req: Request,
  res: Response,
  _next: NextFunction,
): void => {
  console.error('Unhandled error:', err);
  res.status(500).json({
    success: false,
    message: 'Internal server error',
  });
};

export const initMiddlewares = (app: express.Application): void => {
  // Serve static files from the dynamically determined frontend path
  // Note: Static files will be handled by the server directly, not here

  app.use((req, res, next) => {
    const basePath = config.basePath;
    // Only apply JSON parsing for API and auth routes, not for SSE or message endpoints
    if (
      req.path !== `${basePath}/sse` &&
      !req.path.startsWith(`${basePath}/sse/`) &&
      req.path !== `${basePath}/messages`
    ) {
      express.json()(req, res, next);
    } else {
      next();
    }
  });

  // Initialize default admin user if no users exist
  initializeDefaultUser().catch((err) => {
    console.error('Error initializing default user:', err);
  });

  // Protect API routes with authentication middleware, but exclude auth endpoints
  app.use(`${config.basePath}/api`, (req, res, next) => {
    // Skip authentication for login and register endpoints
    if (req.path === '/auth/login' || req.path === '/auth/register') {
      next();
    } else {
      auth(req, res, next);
    }
  });

  app.use(errorHandler);
};