Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 9 additions & 23 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,34 +1,20 @@
FROM node:20-bookworm-slim AS deps
WORKDIR /app

# TODO(deployment): This image currently installs full dependency sets and the
# runtime entrypoint uses dev tooling (ts-node + vite preview). For production,
# split build/runtime deps: keep dev deps in builder stages only, then use
# `npm ci --omit=dev` in the runtime stage and run compiled server JS.
COPY package*.json ./
RUN npm ci

FROM node:20-bookworm-slim AS builder
WORKDIR /app/server

COPY server/package*.json ./
RUN npm ci

FROM node:20-bookworm-slim AS frontend-builder
WORKDIR /app

COPY --from=deps /app/node_modules ./node_modules
COPY . .
COPY server/ ./
RUN npm run build
RUN npm prune --omit=dev

FROM node:20-bookworm-slim AS runtime
WORKDIR /app
WORKDIR /app/server

COPY --from=deps /app/node_modules ./node_modules
COPY --from=deps /app/server/node_modules ./server/node_modules
COPY . .
COPY --from=frontend-builder /app/dist ./dist
ENV NODE_ENV=production

RUN chmod +x /app/scripts/start.sh
COPY --from=builder /app/server /app/server

EXPOSE 4000 5173
EXPOSE 8080

CMD ["/app/scripts/start.sh"]
CMD ["node", "index.js"]
2 changes: 1 addition & 1 deletion server/auth/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ router.get('/google', passport_1.default.authenticate('google', {
// 2. Google OAuth callback
// Google redirects here after the user grants permission
router.get('/google/callback', passport_1.default.authenticate('google', { failureMessage: true }), (req, res) => {
res.redirect('http://localhost:5173');
res.redirect(process.env.CLIENT_URL || 'http://localhost:5173');
});
router.get('/me', (req, res) => {
if (req.isAuthenticated && req.isAuthenticated()) {
Expand Down
2 changes: 1 addition & 1 deletion server/config/passport.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ passport_1.default.deserializeUser((id, done) => __awaiter(void 0, void 0, void
passport_1.default.use(new passport_google_oauth20_1.Strategy({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: 'http://localhost:4000/auth/google/callback',
callbackURL: process.env.GOOGLE_CALLBACK_URL || `${process.env.SERVER_PUBLIC_URL || 'http://localhost:4000'}/auth/google/callback`,
}, (accessToken, refreshToken, profile, done) => __awaiter(void 0, void 0, void 0, function* () {
var _a, _b;
try {
Expand Down
3 changes: 2 additions & 1 deletion server/controllers/authController.js
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,8 @@ exports.login = login;
* Redirect the user to your frontend app.
*/
const googleAuthCallback = (res) => {
return res.redirect('http://localhost:5173');
const clientUrl = process.env.CLIENT_URL || 'http://localhost:5173';
return res.redirect(clientUrl);
};
exports.googleAuthCallback = googleAuthCallback;
const checkAuth = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
Expand Down
20 changes: 10 additions & 10 deletions server/controllers/graphController.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.semanticSearchGraph = exports.searchGraph = exports.getNodeMetadata = exports.getUserProfile = exports.generateConversationResponse = exports.verifyAnswer = exports.generateQuestionsWithAnswers = exports.viewGraph = void 0;
const axios_1 = __importDefault(require("axios"));
const openai_1 = __importDefault(require("openai"));
const dotenv_1 = __importDefault(require("dotenv"));
const path_1 = __importDefault(require("path"));
const ConceptProgress_1 = __importDefault(require("../models/ConceptProgress"));
const axiosConfig_1 = require("../utils/axiosConfig");
// Load environment variables
dotenv_1.default.config({ path: path_1.default.resolve(__dirname, '../.env') });
// Initialize OpenAI with explicit API key
const openai = new openai_1.default({
apiKey: process.env.OPENAI_API_KEY || '' // Provide empty string as fallback
Expand Down Expand Up @@ -56,7 +51,9 @@ const viewGraph = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
if (!graph_id) {
return res.status(400).json({ error: 'graph_id is required' });
}
const response = yield axios_1.default.get(`http://localhost:8000/view-graph?graph_id=${graph_id}`);
const response = yield axiosConfig_1.pythonServiceClient.get('/view-graph', {
params: { graph_id: String(graph_id) }
});
res.json(response.data);
}
catch (error) {
Expand Down Expand Up @@ -312,9 +309,11 @@ const getUserProfile = (req, res) => __awaiter(void 0, void 0, void 0, function*
return res.status(400).json({ error: 'graph_id is required' });
}
try {
const url = `http://localhost:8000/user/${userId}/profile?graph_id=${graph_id}`;
const url = `/user/${userId}/profile`;
console.log(`Fetching user profile from AI server: ${url}`);
const response = yield axios_1.default.get(url);
const response = yield axiosConfig_1.pythonServiceClient.get(url, {
params: { graph_id: String(graph_id) }
});
// Forward the data from the AI server directly to the frontend
res.json(response.data);
}
Expand All @@ -337,8 +336,9 @@ const getNodeMetadata = (req, res) => __awaiter(void 0, void 0, void 0, function
if (!conceptIdsRaw)
return res.status(400).json({ error: 'concept_ids or concept_id is required' });
const wanted = String(conceptIdsRaw).split(',').map(s => s.trim()).filter(Boolean);
const url = `http://localhost:8000/view-graph?graph_id=${encodeURIComponent(String(graph_id))}`;
const response = yield axios_1.default.get(url);
const response = yield axiosConfig_1.pythonServiceClient.get('/view-graph', {
params: { graph_id: String(graph_id) }
});
const nodes = ((_b = (_a = response.data) === null || _a === void 0 ? void 0 : _a.graph) === null || _b === void 0 ? void 0 : _b.nodes) || [];
const matches = nodes.filter((node) => {
const props = node.properties || {};
Expand Down
6 changes: 4 additions & 2 deletions server/controllers/uploadController.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const axios_1 = __importDefault(require("axios"));
const multer_1 = __importDefault(require("multer"));
const form_data_1 = __importDefault(require("form-data"));
const crypto_1 = require("crypto");
const axiosConfig_1 = require("../utils/axiosConfig");
// Configure multer for handling file uploads
exports.upload = (0, multer_1.default)({
storage: multer_1.default.memoryStorage(),
Expand Down Expand Up @@ -167,8 +168,9 @@ const processPdf = (req, res) => __awaiter(void 0, void 0, void 0, function* ()
sendEvent({ type: 'progress', percent: rounded, message: getProgressMessage(rounded) });
}
}, 1500);
// Send to processing server, passing the abort signal so we can cancel mid-flight
const response = yield axios_1.default.post(`${PYTHON_SERVICE_URL}/process-pdf`, formData, {
// Send to processing server
const response = yield axiosConfig_1.pythonServiceClient.post('/process-pdf', formData, {
params: req.query,
headers: Object.assign({}, formData.getHeaders()),
maxBodyLength: Infinity,
maxContentLength: Infinity,
Expand Down
36 changes: 31 additions & 5 deletions server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,19 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
Object.defineProperty(exports, "__esModule", { value: true });
const dotenv_1 = __importDefault(require("dotenv"));
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
// Load environment variables before any other imports
dotenv_1.default.config({ path: path_1.default.resolve(__dirname, '.env') });
const envCandidates = [
path_1.default.resolve(__dirname, '.env'),
path_1.default.resolve(__dirname, '../.env'),
];
const resolvedEnvPath = envCandidates.find((candidate) => fs_1.default.existsSync(candidate));
if (resolvedEnvPath) {
dotenv_1.default.config({ path: resolvedEnvPath });
}
else {
dotenv_1.default.config();
}
const mongoose_1 = __importDefault(require("mongoose"));
const express_1 = __importDefault(require("express"));
const passport_1 = __importDefault(require("passport"));
Expand All @@ -27,10 +38,17 @@ const chatRoutes_1 = __importDefault(require("./routes/chatRoutes"));
const progressRoutes_1 = __importDefault(require("./routes/progressRoutes"));
const quizHistoryRoutes_1 = __importDefault(require("./routes/quizHistoryRoutes"));
const express_session_1 = __importDefault(require("express-session"));
const connect_mongo_1 = __importDefault(require("connect-mongo"));
const axios_1 = __importDefault(require("axios"));
const User_1 = __importDefault(require("./models/User"));
require("./config/passport");
const app = (0, express_1.default)();
const rawPort = process.env.PORT;
const parsedPort = rawPort ? parseInt(rawPort, 10) : 4000;
const port = Number.isNaN(parsedPort) ? 4000 : parsedPort;
const corsOriginConfig = process.env.CORS_ORIGINS || process.env.CLIENT_URL || 'http://localhost:5173';
const corsOrigins = corsOriginConfig.split(',').map((origin) => origin.trim()).filter(Boolean);
const isProduction = process.env.NODE_ENV === 'production' || Boolean(process.env.K_SERVICE);
// Connect to Mongo
const connectDB = () => __awaiter(void 0, void 0, void 0, function* () {
try {
Expand All @@ -45,17 +63,25 @@ const connectDB = () => __awaiter(void 0, void 0, void 0, function* () {
connectDB();
// CORS
app.use((0, cors_1.default)({
origin: 'http://localhost:5173',
origin: corsOrigins.length <= 1 ? corsOrigins[0] : corsOrigins,
credentials: true,
}));
app.use(express_1.default.json());
// Session middleware (before passport middleware)
app.set('trust proxy', 1);
app.use((0, express_session_1.default)({
secret: process.env.SESSION_SECRET || 'your-secret-key',
proxy: isProduction,
resave: false,
saveUninitialized: false,
store: connect_mongo_1.default.create({
mongoUrl: process.env.MONGO_URI,
collectionName: 'sessions',
ttl: 14 * 24 * 60 * 60,
}),
cookie: {
secure: process.env.NODE_ENV === 'production', // Only use secure in production
secure: isProduction,
sameSite: isProduction ? 'none' : 'lax',
httpOnly: true,
maxAge: 24 * 60 * 60 * 1000 // 24 hours
}
Expand Down Expand Up @@ -105,6 +131,6 @@ app.get('/flask/hi', (req, res) => __awaiter(void 0, void 0, void 0, function* (
}
}));
// Start server
app.listen(4000, () => {
console.log('Server running on http://localhost:4000');
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});
12 changes: 11 additions & 1 deletion server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import chatRoutes from './routes/chatRoutes';
import progressRoutes from './routes/progressRoutes';
import quizHistoryRoutes from './routes/quizHistoryRoutes';
import session from 'express-session';
import MongoStore from 'connect-mongo';
import axios from 'axios';
import User from './models/User';

Expand All @@ -36,6 +37,7 @@ const parsedPort = rawPort ? parseInt(rawPort, 10) : 4000;
const port = Number.isNaN(parsedPort) ? 4000 : parsedPort;
const corsOriginConfig = process.env.CORS_ORIGINS || process.env.CLIENT_URL || 'http://localhost:5173';
const corsOrigins = corsOriginConfig.split(',').map((origin) => origin.trim()).filter(Boolean);
const isProduction = process.env.NODE_ENV === 'production' || Boolean(process.env.K_SERVICE);

// Connect to Mongo
const connectDB = async () => {
Expand All @@ -58,12 +60,20 @@ app.use(cors({
app.use(express.json());

// Session middleware (before passport middleware)
app.set('trust proxy', 1);
app.use(session({
secret: process.env.SESSION_SECRET || 'your-secret-key',
proxy: isProduction,
resave: false,
saveUninitialized: false,
store: MongoStore.create({
mongoUrl: process.env.MONGO_URI!,
collectionName: 'sessions',
ttl: 14 * 24 * 60 * 60,
}),
cookie: {
secure: process.env.NODE_ENV === 'production', // Only use secure in production
secure: isProduction,
sameSite: isProduction ? 'none' : 'lax',
httpOnly: true,
maxAge: 24 * 60 * 60 * 1000 // 24 hours
}
Expand Down
Loading