Skip to content
Closed
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
30 changes: 30 additions & 0 deletions backend/data/discussions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"discussions": [
{
"id": "b3808b42-91e4-4d81-991a-07a96d7a549f",
"title": "Test discussion from shell",
"body": "This is a sufficiently long discussion body to pass validation and save.",
"category": "Help",
"tags": [
"test",
"api"
],
"authorId": "8d706914-51d9-40ca-981c-ac9dcb6a1881",
"authorName": "Guest",
"likes": [
"c8cf4cfd-145c-4950-8392-5f40f2a9ccde"
],
"comments": [
{
"id": "d1b1bcad-6989-49ff-a587-667f8426198e",
"text": "Yes",
"authorId": "c8cf4cfd-145c-4950-8392-5f40f2a9ccde",
"authorName": "arpit",
"createdAt": "2026-05-27T12:56:14.816Z"
}
],
"createdAt": "2026-05-27T11:55:11.307Z",
"updatedAt": "2026-05-27T13:00:24.816Z"
}
]
}
10 changes: 10 additions & 0 deletions backend/data/users.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"users": [
{
"id": "c8cf4cfd-145c-4950-8392-5f40f2a9ccde",
"username": "arpit",
"email": "arpitshirbhate5@gmail.com",
"password": "$2a$10$6MsaZTunN.oNj5UOHdwfrOYELPdptaMQxK5Tj4/2kFekFY/jVL4mi"
}
Comment thread
arpit2006 marked this conversation as resolved.
]
}
81 changes: 81 additions & 0 deletions backend/models/Discussion.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
const mongoose = require('mongoose');

const CommentSchema = new mongoose.Schema(
{
text: {
type: String,
required: true,
trim: true,
maxlength: 1000,
},
authorId: {
type: String,
required: true,
},
authorName: {
type: String,
required: true,
trim: true,
},
},
{ timestamps: true }
);

const DiscussionSchema = new mongoose.Schema(
{
title: {
type: String,
required: true,
trim: true,
minlength: 4,
maxlength: 140,
},
body: {
type: String,
required: true,
trim: true,
minlength: 20,
maxlength: 4000,
},
category: {
type: String,
required: true,
trim: true,
maxlength: 60,
},
tags: {
type: [
{
type: String,
trim: true,
maxlength: 30,
},
],
default: [],
},
authorId: {
type: String,
required: true,
},
authorName: {
type: String,
required: true,
trim: true,
},
likes: {
type: [
{
type: String,
},
],
default: [],
},
comments: {
type: [CommentSchema],
default: [],
},
},
{ timestamps: true }
);

module.exports = mongoose.model('Discussion', DiscussionSchema);
180 changes: 178 additions & 2 deletions backend/routes/auth.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,137 @@
const express = require("express");
const passport = require("passport");
const fs = require("fs/promises");
const path = require("path");
const bcrypt = require("bcryptjs");
const crypto = require("crypto");
const User = require("../models/User");
const { signupSchema, loginSchema } = require("../validators/authValidator");
const { validateRequest } = require("../validators/validationRequest");
const router = express.Router();

const useMongoAuth = Boolean(process.env.MONGO_URI);
const dataDir = path.join(__dirname, "..", "data");
const usersFile = path.join(dataDir, "users.json");
const usersLockFile = `${usersFile}.lock`;

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const acquireUsersLock = async () => {
const retries = 80;
const delayMs = 25;

for (let attempt = 0; attempt < retries; attempt += 1) {
try {
const handle = await fs.open(usersLockFile, "wx");
return handle;
} catch (error) {
if (error.code !== "EEXIST") {
throw error;
}

await sleep(delayMs);
}
}

throw new Error("Could not acquire users file lock");
};

const withUsersLock = async (callback) => {
const lockHandle = await acquireUsersLock();

try {
return await callback();
} finally {
await lockHandle.close();
await fs.unlink(usersLockFile).catch(() => {});
}
};

const ensureUsersFileUnlocked = async () => {
await fs.mkdir(dataDir, { recursive: true });

try {
await fs.access(usersFile);
} catch {
await fs.writeFile(usersFile, JSON.stringify({ users: [] }, null, 2), "utf8");
}
};

const readUsersUnlocked = async () => {
await ensureUsersFileUnlocked();
const raw = await fs.readFile(usersFile, "utf8");

try {
const parsed = JSON.parse(raw);
return Array.isArray(parsed.users) ? parsed.users : [];
} catch {
return [];
}
};

const writeUsersUnlocked = async (users) => {
await ensureUsersFileUnlocked();
const tempFile = `${usersFile}.${process.pid}.${Date.now()}.tmp`;

// Write to a temporary file first, then atomically replace the target file.
await fs.writeFile(tempFile, JSON.stringify({ users }, null, 2), "utf8");
await fs.rename(tempFile, usersFile);
};

const readUsersWithLock = async () => withUsersLock(readUsersUnlocked);

const createUserIfNotExistsWithLock = async (newUser) => withUsersLock(async () => {
const users = await readUsersUnlocked();
const existingUser = users.find((user) => user.email === newUser.email || user.username === newUser.username);

if (existingUser) {
return false;
}

users.push(newUser);
await writeUsersUnlocked(users);
return true;
});

const createSessionUser = (req, user) => {
req.session.authUser = {
id: user.id,
username: user.username,
email: user.email,
};

req.user = req.session.authUser;
};

// Signup route
router.post("/signup", validateRequest(signupSchema), async (req, res) => {

const { username, email, password } = req.body;

if (!useMongoAuth) {
try {
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);

const newUser = {
id: crypto.randomUUID(),
username,
email,
password: hashedPassword,
};

const created = await createUserIfNotExistsWithLock(newUser);

if (!created) {
return res.status(400).json({ message: 'User already exists' });
}

return res.status(201).json({ message: 'User created successfully' });
} catch (err) {
return res.status(500).json({ message: 'Error creating user', error: err.message });
}
}

try {
const existingUser = await User.findOne({
$or: [{ email }, { username }],
Expand All @@ -31,13 +153,67 @@ router.post("/signup", validateRequest(signupSchema), async (req, res) => {
});

// Login route
router.post("/login", validateRequest(loginSchema), passport.authenticate('local'), (req, res) => {
res.status(200).json( { message: 'Login successful', user: req.user } );
router.post("/login", validateRequest(loginSchema), async (req, res, next) => {
if (!useMongoAuth) {
try {
const { email, password } = req.body;
const users = await readUsersWithLock();
const user = users.find((item) => item.email === email);

if (!user) {
return res.status(401).json({ message: 'Email is invalid ' });
}

const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res.status(401).json({ message: 'Invalid password' });
}

createSessionUser(req, user);

return res.status(200).json({
message: 'Login successful',
user: req.user,
});
} catch (err) {
return res.status(500).json({ message: 'Login failed', error: err.message });
}
}

return passport.authenticate('local', (err, user, info) => {
if (err) {
return next(err);
}

if (!user) {
return res.status(401).json({ message: info?.message || 'Invalid credentials' });
}

req.logIn(user, (loginErr) => {
if (loginErr) {
return next(loginErr);
}

return res.status(200).json({ message: 'Login successful', user: req.user });
});
})(req, res, next);
});

// Logout route
router.get("/logout", (req, res) => {

if (!useMongoAuth) {
req.session.destroy((err) => {
if (err) {
return res.status(500).json({ message: 'Logout failed', error: err.message });
}

return res.status(200).json({ message: 'Logged out successfully' });
});

return;
}

req.logout((err) => {

if (err)
Expand Down
Loading