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
3 changes: 2 additions & 1 deletion server/controller/Auth/forgotPassword.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,10 @@ const forgotPasswordLogic = async (req, res) => {

// Generate 32-byte secure token
const token = crypto.randomBytes(32).toString("hex");
const hashedToken = crypto.createHash("sha256").update(token).digest("hex");
const expiry = Date.now() + 15 * 60 * 1000; // 15 min validity

user.resetToken = token;
user.resetToken = hashedToken;
user.resetTokenExpiry = expiry;
await user.save();

Expand Down
9 changes: 6 additions & 3 deletions server/controller/Auth/resetPassword.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// controller/Auth/resetPassword.js
const bcrypt = require("bcryptjs");
const UserModel = require("../../models/user.models");
const crypto = require("crypto");
const { validatePassword } = require("../../utils/passwordValidator");

const resetPassword = async (req, res) => {
Expand All @@ -24,8 +24,11 @@ const resetPassword = async (req, res) => {
});
}

// Find user by token
const user = await UserModel.findOne({ resetToken: token });
// Hash incoming token to match the database stored token
const hashedToken = crypto.createHash("sha256").update(token).digest("hex");

// Find user by hashed token
const user = await UserModel.findOne({ resetToken: hashedToken });

if (!user) {
return res.status(400).json({
Expand Down
153 changes: 14 additions & 139 deletions server/controller/Lesson/lessoncontroller.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
const Lesson = require('../../models/lesson');
const Progress = require('../../models/progress');
const User = require('../../models/user.models');
const Analytics = require('../../models/analytics');
const Notification = require('../../models/notification');
const { recordLessonCompletion } = require('../../services/progressService');

const LESSON_ID_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/i;
const MAX_LESSON_ID_LENGTH = 80;
Expand All @@ -24,10 +21,7 @@ const STATIC_LESSON_LIMITS = {
};
const STATIC_LESSON_ID_RE = /^(html|css|js|c|dbms|dsa|express|mongo|node|oop|react)-lesson-?(\d+)$/i;

const getSubjectFromLessonId = (lessonId) => {
if (!lessonId || typeof lessonId !== 'string') return 'Other';
return lessonId.split('-')[0].replace(/\d+$/, '') || lessonId;
};


const parseFiniteNumber = (value) => {
if (typeof value === 'number') return Number.isFinite(value) ? value : null;
Expand Down Expand Up @@ -196,140 +190,21 @@ exports.completeLesson = async (req, res) => {

const { score, coins, learningTime, type } = payload.value;

const existingProgress = await Progress.findOne({ email });

const today = new Date();
today.setHours(0, 0, 0, 0);

// Single source of truth for streak: date-diff logic based on lastActiveDate.
// This value is used BOTH for the XP multiplier below AND for the DB write,
// so the reward and the persisted/displayed streak can never diverge.
let currentStreak = existingProgress?.currentStreak || 0;
let longestStreak = existingProgress?.longestStreak || 0;

if (!existingProgress?.lastActiveDate) {
currentStreak = 1;
} else {
const lastDate = new Date(existingProgress.lastActiveDate);
lastDate.setHours(0, 0, 0, 0);
const diffDays = Math.floor(
(today - lastDate) / (1000 * 60 * 60 * 24)
);
if (diffDays === 1) {
currentStreak += 1;
} else if (diffDays > 1) {
currentStreak = 1;
}
// diffDays === 0 -> same day, don't change streak
}

longestStreak = Math.max(longestStreak, currentStreak);

let progress = await Progress.findOne({ email });
const isNewCompletion = !progress || !progress.completedLessons.includes(lessonId);

let earnedXp = 0;
let earnedBadges = progress?.badges || [];

if (isNewCompletion) {
const baseXp = Math.round(score * 0.5);

const events = await Analytics.find({ email }).sort({ createdAt: 1 }).lean();

// Multiplier now reuses the single `currentStreak` computed above
// instead of a second, separately-derived (and previously shadowed)
// analytics-based streak. This keeps the XP reward and the persisted
// streak consistent with each other.
let multiplier = 1.0;
if (currentStreak >= 7) multiplier = 1.5;
else if (currentStreak >= 3) multiplier = 1.2;

earnedXp = Math.round(baseXp * multiplier);

const { checkAndAwardBadges } = require('../../config/badges');
const progressData = progress ? { ...progress.toObject(), badges: earnedBadges } : { completedLessons: [], scores: {}, badges: [], currentStreak: 0 };
const result = checkAndAwardBadges(
progressData,
{ score, analyticsEvents: events }
);
earnedBadges = result.earnedBadgeIds;
}

const currentXp = progress?.xp || 0;
const newTotalXp = currentXp + earnedXp;
const newLevel = Math.floor(newTotalXp / 100) + 1;

progress = await Progress.findOneAndUpdate(
{ email },
{
$addToSet: { completedLessons: lessonId },
$set: {
[`scores.${lessonId}`]: score,
xp: newTotalXp,
level: newLevel,
badges: earnedBadges,
currentStreak,
longestStreak,
lastActiveDate: today,
}
},
{
new: true,
upsert: true,
}
);

const user = await User.findOne({ email }).lean();

try {
await Analytics.create({
userId: user?._id || null,
email,
username: user?.username || progress.username || '',
lessonId,
subject: getSubjectFromLessonId(lessonId),
score,
completed: true,
points: score,
coins,
learningTime,
type,
});
} catch (analyticsErr) {
console.error('Analytics event creation failed:', analyticsErr);
}

try {
await Notification.create({
email,
type: 'lesson_complete',
message: `You completed the lesson "${lessonId}" with a score of ${score}!`,
relatedEntity: lessonId,
});
} catch (notifErr) {
console.error('Notification creation failed:', notifErr);
}

if (currentStreak > 1 && currentStreak % 5 === 0) {
try {
await Notification.create({
email,
type: 'streak_milestone',
message: `You've reached a ${currentStreak}-day learning streak! Keep it up!`,
relatedEntity: '',
});
} catch (notifErr) {
console.error('Streak notification creation failed:', notifErr);
}
}
// Delegate all DB writes to the transactional service. All related
// documents (Progress, Analytics, Notification) commit atomically or
// are rolled back together via a Mongoose session transaction.
const result = await recordLessonCompletion({
email,
lessonId,
score,
coins,
learningTime,
type,
});

res.json({
message: 'Lesson marked as completed',
completedLessons: progress.completedLessons,
scores: progress.scores,
currentStreak: progress.currentStreak,
longestStreak: progress.longestStreak,
dailyGoal: progress.dailyGoal,
...result,
});
} catch (err) {
console.error(err);
Expand Down
2 changes: 1 addition & 1 deletion server/middleware/rateLimiter.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const compilerLimiter = rateLimit({
keyGenerator: (req) => req.user?.id || req.ip,
});

router.post('/execute', authenticateToken, compilerLimiter, async (req, res) => { ... });


// 1 minute window, max 5 feedback submissions per IP
const feedbackLimiter = rateLimit({
Expand Down
Loading
Loading