@defikitdotnet/education-module-ai
Version:
AI Education Module using Agent Framework
700 lines (699 loc) • 39.2 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AuthController = void 0;
var bcrypt_1 = __importDefault(require("bcrypt"));
var jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
var errorHandler_1 = require("../middleware/errorHandler");
var AuthController = /** @class */ (function () {
function AuthController(studentRepository, teacherRepository) {
var _this = this;
this.studentRepository = studentRepository;
/**
* Register a new teacher
*/
this.registerTeacher = function (req, res, next) { return __awaiter(_this, void 0, void 0, function () {
var _a, name, email, password, existingTeacher, teacher, _, safeTeacher, error_1;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
// Ensure teacher repository is available
if (!this.teacherRepository) {
console.error("Teacher repository not initialized");
return [2 /*return*/, next(new errorHandler_1.ApiError("Server configuration error", 500))];
}
_a = req.body, name = _a.name, email = _a.email, password = _a.password;
// Validate required fields
if (!name || !email || !password) {
return [2 /*return*/, next(new errorHandler_1.ApiError("Name, email, and password are required", 400))];
}
_b.label = 1;
case 1:
_b.trys.push([1, 4, , 5]);
return [4 /*yield*/, this.teacherRepository.findByEmail(email)];
case 2:
existingTeacher = _b.sent();
if (existingTeacher) {
return [2 /*return*/, next(new errorHandler_1.ApiError("A teacher with this email already exists", 400))];
}
return [4 /*yield*/, this.teacherRepository.create({
name: name,
email: email,
password: password,
isActive: true
})];
case 3:
teacher = _b.sent();
_ = teacher.password, safeTeacher = __rest(teacher, ["password"]);
res.status(201).json({
message: "Teacher registered successfully",
teacher: safeTeacher
});
return [3 /*break*/, 5];
case 4:
error_1 = _b.sent();
console.error("Teacher registration error:", error_1);
next(new errorHandler_1.ApiError("Failed to register teacher", 500));
return [3 /*break*/, 5];
case 5: return [2 /*return*/];
}
});
}); };
/**
* Login a student using email and password
*/
this.loginStudent = function (req, res, next) { return __awaiter(_this, void 0, void 0, function () {
var _a, email, password, secret, cookieName, student, isPasswordValid, tokenPayload, token, error_2;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_a = req.body, email = _a.email, password = _a.password;
secret = process.env.JWT_SECRET;
cookieName = "studentAuthToken";
if (!email || !password) {
return [2 /*return*/, next(new errorHandler_1.ApiError("Email and password are required", 400))];
}
if (!secret) {
console.error("JWT_SECRET is not set in environment variables");
return [2 /*return*/, next(new errorHandler_1.ApiError("Server configuration error", 500))];
}
_b.label = 1;
case 1:
_b.trys.push([1, 4, , 5]);
return [4 /*yield*/, this.studentRepository.findByEmail(email)];
case 2:
student = _b.sent();
if (!student) {
return [2 /*return*/, next(new errorHandler_1.ApiError("Invalid credentials", 401))];
}
return [4 /*yield*/, bcrypt_1.default.compare(password, student.passwordHash)];
case 3:
isPasswordValid = _b.sent();
if (!isPasswordValid) {
return [2 /*return*/, next(new errorHandler_1.ApiError("Invalid credentials", 401))];
}
tokenPayload = { studentId: student.id };
token = jsonwebtoken_1.default.sign(tokenPayload, secret, { expiresIn: "1h" });
// Set HTTP-only cookie
res.cookie(cookieName, token, {
httpOnly: true, // Prevent client-side JS access
secure: process.env.NODE_ENV === "production", // Use secure cookies in production
sameSite: "lax", // Adjust as needed for your cross-origin setup ('none' requires secure)
maxAge: 3600000, // 1 hour in milliseconds
path: "/", // Make accessible across the site
});
// Send success response with student ID and basic info
res.status(200).json({
message: "Login successful",
student: {
id: student.id, // Send the correct UUID
email: student.email,
name: student.name,
},
});
return [3 /*break*/, 5];
case 4:
error_2 = _b.sent();
console.error("Student login error:", error_2);
next(new errorHandler_1.ApiError("Internal server error during login", 500));
return [3 /*break*/, 5];
case 5: return [2 /*return*/];
}
});
}); };
/**
* Login a teacher using email and password
*/
this.loginTeacher = function (req, res, next) { return __awaiter(_this, void 0, void 0, function () {
var _a, email, password, secret, cookieName, teacher, isPasswordValid, tokenPayload, token, error_3;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
// Ensure teacher repository is available
if (!this.teacherRepository) {
console.error("Teacher repository not initialized");
return [2 /*return*/, next(new errorHandler_1.ApiError("Server configuration error", 500))];
}
_a = req.body, email = _a.email, password = _a.password;
secret = process.env.JWT_SECRET;
cookieName = "teacherAuthToken";
if (!email || !password) {
return [2 /*return*/, next(new errorHandler_1.ApiError("Email and password are required", 400))];
}
if (!secret) {
console.error("JWT_SECRET is not set in environment variables");
return [2 /*return*/, next(new errorHandler_1.ApiError("Server configuration error", 500))];
}
_b.label = 1;
case 1:
_b.trys.push([1, 4, , 5]);
return [4 /*yield*/, this.teacherRepository.findByEmail(email)];
case 2:
teacher = _b.sent();
if (!teacher) {
return [2 /*return*/, next(new errorHandler_1.ApiError("Invalid credentials", 401))];
}
return [4 /*yield*/, bcrypt_1.default.compare(password, teacher.passwordHash)];
case 3:
isPasswordValid = _b.sent();
if (!isPasswordValid) {
return [2 /*return*/, next(new errorHandler_1.ApiError("Invalid credentials", 401))];
}
tokenPayload = { teacherId: teacher.id };
token = jsonwebtoken_1.default.sign(tokenPayload, secret, { expiresIn: "1h" });
// Set HTTP-only cookie
res.cookie(cookieName, token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
maxAge: 3600000, // 1 hour in milliseconds
path: "/",
});
// Send success response with teacher ID and basic info
res.status(200).json({
message: "Login successful",
teacher: {
id: teacher.id,
email: teacher.email,
name: teacher.name,
},
});
return [3 /*break*/, 5];
case 4:
error_3 = _b.sent();
console.error("Teacher login error:", error_3);
next(new errorHandler_1.ApiError("Internal server error during login", 500));
return [3 /*break*/, 5];
case 5: return [2 /*return*/];
}
});
}); };
/**
* Get the profile of the currently authenticated student
*/
this.getStudentProfile = function (req, res, next) { return __awaiter(_this, void 0, void 0, function () {
var studentId, student, passwordHash, safeStudent, error_4;
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
studentId = (_a = req.student) === null || _a === void 0 ? void 0 : _a.id;
if (!studentId) {
// This shouldn't happen if authenticateStudent ran correctly
return [2 /*return*/, next(new errorHandler_1.ApiError("Authentication failed", 401))];
}
_b.label = 1;
case 1:
_b.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.studentRepository.findById(studentId)];
case 2:
student = _b.sent();
if (!student) {
// Should not happen if JWT studentId is valid
// Log the specific ID that wasn't found
console.error("Student profile not found in repository for authenticated student ID: ".concat(studentId));
return [2 /*return*/, next(new errorHandler_1.ApiError("Student profile not found", 404))];
}
passwordHash = student.passwordHash, safeStudent = __rest(student, ["passwordHash"]);
res.status(200).json({ data: safeStudent });
return [3 /*break*/, 4];
case 3:
error_4 = _b.sent();
console.error("Error fetching student profile:", error_4);
next(new errorHandler_1.ApiError("Failed to retrieve profile", 500));
return [3 /*break*/, 4];
case 4: return [2 /*return*/];
}
});
}); };
/**
* Get the profile of the currently authenticated teacher
*/
this.getTeacherProfile = function (req, res, next) { return __awaiter(_this, void 0, void 0, function () {
var teacherId, teacher, passwordHash, safeTeacher, error_5;
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
// Ensure teacher repository is available
if (!this.teacherRepository) {
console.error("Teacher repository not initialized");
return [2 /*return*/, next(new errorHandler_1.ApiError("Server configuration error", 500))];
}
teacherId = (_a = req.teacher) === null || _a === void 0 ? void 0 : _a.id;
if (!teacherId) {
// This shouldn't happen if authenticateTeacher ran correctly
return [2 /*return*/, next(new errorHandler_1.ApiError("Authentication failed", 401))];
}
_b.label = 1;
case 1:
_b.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.teacherRepository.findById(teacherId)];
case 2:
teacher = _b.sent();
if (!teacher) {
console.error("Teacher profile not found in repository for authenticated teacher ID: ".concat(teacherId));
return [2 /*return*/, next(new errorHandler_1.ApiError("Teacher profile not found", 404))];
}
passwordHash = teacher.passwordHash, safeTeacher = __rest(teacher, ["passwordHash"]);
res.status(200).json({ data: safeTeacher });
return [3 /*break*/, 4];
case 3:
error_5 = _b.sent();
console.error("Error fetching teacher profile:", error_5);
next(new errorHandler_1.ApiError("Failed to retrieve profile", 500));
return [3 /*break*/, 4];
case 4: return [2 /*return*/];
}
});
}); };
/**
* Update the profile of the currently authenticated student
*/
this.updateStudentProfile = function (req, res, next) { return __awaiter(_this, void 0, void 0, function () {
var studentId, updateData, existingStudentByEmail, updatedStudent, passwordHash, safeStudent, error_6;
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
studentId = (_a = req.student) === null || _a === void 0 ? void 0 : _a.id;
updateData = req.body;
if (!studentId) {
return [2 /*return*/, next(new errorHandler_1.ApiError("Authentication failed", 401))];
}
// Basic validation (add more as needed)
if (updateData.id || updateData.passwordHash || updateData.createdAt) {
return [2 /*return*/, next(new errorHandler_1.ApiError("Cannot update ID, password hash, or creation date", 400))];
}
_b.label = 1;
case 1:
_b.trys.push([1, 5, , 6]);
if (!updateData.email) return [3 /*break*/, 3];
return [4 /*yield*/, this.studentRepository.findByEmail(updateData.email)];
case 2:
existingStudentByEmail = _b.sent();
if (existingStudentByEmail &&
existingStudentByEmail.id !== studentId) {
return [2 /*return*/, next(new errorHandler_1.ApiError("Email already in use", 400))];
}
_b.label = 3;
case 3: return [4 /*yield*/, this.studentRepository.update(studentId, updateData)];
case 4:
updatedStudent = _b.sent();
if (!updatedStudent) {
// Should only happen if the student was deleted between auth check and update
return [2 /*return*/, next(new errorHandler_1.ApiError("Failed to update profile", 500))];
}
passwordHash = updatedStudent.passwordHash, safeStudent = __rest(updatedStudent, ["passwordHash"]);
res.status(200).json({ data: safeStudent });
return [3 /*break*/, 6];
case 5:
error_6 = _b.sent();
console.error("Error updating student profile:", error_6);
next(new errorHandler_1.ApiError("Failed to update profile", 500));
return [3 /*break*/, 6];
case 6: return [2 /*return*/];
}
});
}); };
/**
* Update the profile of the currently authenticated teacher
*/
this.updateTeacherProfile = function (req, res, next) { return __awaiter(_this, void 0, void 0, function () {
var teacherId, updateData, existingTeacherByEmail, updatedTeacher, passwordHash, safeTeacher, error_7;
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
// Ensure teacher repository is available
if (!this.teacherRepository) {
console.error("Teacher repository not initialized");
return [2 /*return*/, next(new errorHandler_1.ApiError("Server configuration error", 500))];
}
teacherId = (_a = req.teacher) === null || _a === void 0 ? void 0 : _a.id;
updateData = req.body;
if (!teacherId) {
return [2 /*return*/, next(new errorHandler_1.ApiError("Authentication failed", 401))];
}
// Basic validation
if (updateData.id || updateData.passwordHash || updateData.createdAt) {
return [2 /*return*/, next(new errorHandler_1.ApiError("Cannot update ID, password hash, or creation date", 400))];
}
_b.label = 1;
case 1:
_b.trys.push([1, 5, , 6]);
if (!updateData.email) return [3 /*break*/, 3];
return [4 /*yield*/, this.teacherRepository.findByEmail(updateData.email)];
case 2:
existingTeacherByEmail = _b.sent();
if (existingTeacherByEmail &&
existingTeacherByEmail.id !== teacherId) {
return [2 /*return*/, next(new errorHandler_1.ApiError("Email already in use", 400))];
}
_b.label = 3;
case 3: return [4 /*yield*/, this.teacherRepository.update(teacherId, updateData)];
case 4:
updatedTeacher = _b.sent();
if (!updatedTeacher) {
return [2 /*return*/, next(new errorHandler_1.ApiError("Failed to update profile", 500))];
}
passwordHash = updatedTeacher.passwordHash, safeTeacher = __rest(updatedTeacher, ["passwordHash"]);
res.status(200).json({ data: safeTeacher });
return [3 /*break*/, 6];
case 5:
error_7 = _b.sent();
console.error("Error updating teacher profile:", error_7);
next(new errorHandler_1.ApiError("Failed to update profile", 500));
return [3 /*break*/, 6];
case 6: return [2 /*return*/];
}
});
}); };
/**
* Check the authentication status of the student based on the JWT cookie.
*/
this.checkStudentStatus = function (req, res, next) { return __awaiter(_this, void 0, void 0, function () {
var token, secret, decoded, studentId, student, error_8;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
token = req.cookies.studentAuthToken;
secret = process.env.JWT_SECRET;
if (!token || !secret) {
// No token or secret, user is not authenticated
res.json({ isAuthenticated: false, student: null });
return [2 /*return*/];
}
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
decoded = jsonwebtoken_1.default.verify(token, secret);
studentId = decoded.studentId;
return [4 /*yield*/, this.studentRepository.findById(studentId)];
case 2:
student = _a.sent();
if (!student) {
// Token is valid, but student doesn't exist in DB (e.g., deleted)
// Clear the potentially invalid cookie
res.clearCookie("studentAuthToken", { path: "/" });
res.json({ isAuthenticated: false, student: null });
return [2 /*return*/];
}
// User is authenticated
res.json({
isAuthenticated: true,
student: {
id: student.id,
name: student.name,
email: student.email,
// Add other relevant, non-sensitive fields if needed
},
});
return [3 /*break*/, 4];
case 3:
error_8 = _a.sent();
// Token verification failed (expired, invalid signature, etc.)
// Clear the invalid cookie
res.clearCookie("studentAuthToken", { path: "/" });
res.json({ isAuthenticated: false, student: null });
return [3 /*break*/, 4];
case 4: return [2 /*return*/];
}
});
}); };
/**
* Check the authentication status of the teacher based on the JWT cookie.
*/
this.checkTeacherStatus = function (req, res, next) { return __awaiter(_this, void 0, void 0, function () {
var token, secret, decoded, teacherId, teacher, error_9;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
// Ensure teacher repository is available
if (!this.teacherRepository) {
console.error("Teacher repository not initialized");
return [2 /*return*/, next(new errorHandler_1.ApiError("Server configuration error", 500))];
}
token = req.cookies.teacherAuthToken;
secret = process.env.JWT_SECRET;
if (!token || !secret) {
// No token or secret, user is not authenticated
res.json({ isAuthenticated: false, teacher: null });
return [2 /*return*/];
}
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
decoded = jsonwebtoken_1.default.verify(token, secret);
teacherId = decoded.teacherId;
return [4 /*yield*/, this.teacherRepository.findById(teacherId)];
case 2:
teacher = _a.sent();
if (!teacher) {
// Token is valid, but teacher doesn't exist in DB (e.g., deleted)
// Clear the potentially invalid cookie
res.clearCookie("teacherAuthToken", { path: "/" });
res.json({ isAuthenticated: false, teacher: null });
return [2 /*return*/];
}
// User is authenticated
res.json({
isAuthenticated: true,
teacher: {
id: teacher.id,
name: teacher.name,
email: teacher.email,
},
});
return [3 /*break*/, 4];
case 3:
error_9 = _a.sent();
// Token verification failed (expired, invalid signature, etc.)
// Clear the invalid cookie
res.clearCookie("teacherAuthToken", { path: "/" });
res.json({ isAuthenticated: false, teacher: null });
return [3 /*break*/, 4];
case 4: return [2 /*return*/];
}
});
}); };
/**
* Logout a student by clearing the authentication cookie.
*/
this.logoutStudent = function (req, res) {
var cookieName = "studentAuthToken";
// Clear the cookie
res.clearCookie(cookieName, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
});
res.status(200).json({ message: "Logout successful" });
};
/**
* Logout a teacher by clearing the authentication cookie.
*/
this.logoutTeacher = function (req, res) {
var cookieName = "teacherAuthToken";
// Clear the cookie
res.clearCookie(cookieName, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
});
res.status(200).json({ message: "Logout successful" });
};
/**
* Direct login a student (potentially for specific scenarios like admin access or testing)
* Uses a longer expiry time for the token.
*/
this.directLoginStudent = function (req, res, next) { return __awaiter(_this, void 0, void 0, function () {
var _a, email, password, secret, cookieName, expiresIn, student, isPasswordValid, tokenPayload, token, error_10;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_a = req.body, email = _a.email, password = _a.password;
secret = process.env.JWT_SECRET;
cookieName = "studentAuthToken";
expiresIn = "7d";
if (!email || !password) {
return [2 /*return*/, next(new errorHandler_1.ApiError("Email and password are required", 400))];
}
if (!secret) {
console.error("JWT_SECRET is not set in environment variables");
return [2 /*return*/, next(new errorHandler_1.ApiError("Server configuration error", 500))];
}
_b.label = 1;
case 1:
_b.trys.push([1, 4, , 5]);
return [4 /*yield*/, this.studentRepository.findByEmail(email)];
case 2:
student = _b.sent();
if (!student) {
console.log("[DIRECT LOGIN] Student not found for email: ".concat(email));
return [2 /*return*/, next(new errorHandler_1.ApiError("Invalid email or password", 401))];
}
return [4 /*yield*/, bcrypt_1.default.compare(password, student.passwordHash // Use correct property name
)];
case 3:
isPasswordValid = _b.sent();
if (!isPasswordValid) {
console.log("[DIRECT LOGIN] Password did not match for email: ".concat(email));
return [2 /*return*/, next(new errorHandler_1.ApiError("Invalid email or password", 401))];
}
tokenPayload = { studentId: student.id };
token = jsonwebtoken_1.default.sign(tokenPayload, secret, { expiresIn: expiresIn });
// Set HTTP-only cookie (same way as regular login, just different expiry)
res.cookie(cookieName, token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
maxAge: 60 * 60 * 24 * 7 * 1000, // 7 days in milliseconds
path: "/",
});
// Send success response
console.log("[DIRECT LOGIN] Login successful for email: ".concat(email, "."));
res.status(200).json({
message: "Direct login successful",
student: {
id: student.id,
email: student.email,
name: student.name,
},
});
return [3 /*break*/, 5];
case 4:
error_10 = _b.sent();
console.error("[DIRECT LOGIN] Login error:", error_10);
next(new errorHandler_1.ApiError("Internal server error during direct login", 500));
return [3 /*break*/, 5];
case 5: return [2 /*return*/];
}
});
}); };
/**
* Direct login a teacher with longer expiry time for the token
*/
this.directLoginTeacher = function (req, res, next) { return __awaiter(_this, void 0, void 0, function () {
var _a, email, password, secret, cookieName, expiresIn, teacher, isPasswordValid, tokenPayload, token, error_11;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
// Ensure teacher repository is available
if (!this.teacherRepository) {
console.error("Teacher repository not initialized");
return [2 /*return*/, next(new errorHandler_1.ApiError("Server configuration error", 500))];
}
_a = req.body, email = _a.email, password = _a.password;
secret = process.env.JWT_SECRET;
cookieName = "teacherAuthToken";
expiresIn = "7d";
if (!email || !password) {
return [2 /*return*/, next(new errorHandler_1.ApiError("Email and password are required", 400))];
}
if (!secret) {
console.error("JWT_SECRET is not set in environment variables");
return [2 /*return*/, next(new errorHandler_1.ApiError("Server configuration error", 500))];
}
_b.label = 1;
case 1:
_b.trys.push([1, 4, , 5]);
return [4 /*yield*/, this.teacherRepository.findByEmail(email)];
case 2:
teacher = _b.sent();
if (!teacher) {
console.log("[DIRECT LOGIN] Teacher not found for email: ".concat(email));
return [2 /*return*/, next(new errorHandler_1.ApiError("Invalid email or password", 401))];
}
return [4 /*yield*/, bcrypt_1.default.compare(password, teacher.passwordHash)];
case 3:
isPasswordValid = _b.sent();
if (!isPasswordValid) {
console.log("[DIRECT LOGIN] Password did not match for email: ".concat(email));
return [2 /*return*/, next(new errorHandler_1.ApiError("Invalid email or password", 401))];
}
tokenPayload = { teacherId: teacher.id };
token = jsonwebtoken_1.default.sign(tokenPayload, secret, { expiresIn: expiresIn });
// Set HTTP-only cookie
res.cookie(cookieName, token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
maxAge: 60 * 60 * 24 * 7 * 1000, // 7 days in milliseconds
path: "/",
});
console.log("[DIRECT LOGIN] Teacher login successful for email: ".concat(email, "."));
res.status(200).json({
message: "Direct login successful",
teacher: {
id: teacher.id,
email: teacher.email,
name: teacher.name,
},
});
return [3 /*break*/, 5];
case 4:
error_11 = _b.sent();
console.error("[DIRECT LOGIN] Teacher login error:", error_11);
next(new errorHandler_1.ApiError("Internal server error during direct login", 500));
return [3 /*break*/, 5];
case 5: return [2 /*return*/];
}
});
}); };
this.teacherRepository = teacherRepository;
}
return AuthController;
}());
exports.AuthController = AuthController;