Skip to content
Merged
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: 3 additions & 0 deletions server/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,7 @@ jspm_packages/
.DS_Store
Thumbs.db

.vercel/
/generated/prisma
cookies.txt

11 changes: 0 additions & 11 deletions server/.vercel/README.txt

This file was deleted.

1 change: 0 additions & 1 deletion server/.vercel/project.json

This file was deleted.

53 changes: 53 additions & 0 deletions server/controllers/auth.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import jwt from 'jsonwebtoken';
import { signupUser, loginUser, getPublicUser } from '../services/auth.service.js';
import { asyncHandler } from '../utils/asyncHandler.js';
import { BadRequestError } from '../utils/errors.js';
import isStrongPassword from 'validator/lib/isStrongPassword.js';

const TOKEN_COOKIE_NAME = 'token';

const setAuthCookie = (res, payload) => {
if (!process.env.JWT_SECRET) {
throw new Error('Missing JWT_SECRET');
}
const token = jwt.sign(payload, process.env.JWT_SECRET, {
expiresIn: process.env.JWT_EXPIRES_IN || '7d',
});
const isProd = process.env.NODE_ENV === 'production';
res.cookie(TOKEN_COOKIE_NAME, token, {
httpOnly: true,
secure: isProd,
sameSite: isProd ? 'none' : 'lax',
maxAge: 7 * 24 * 60 * 60 * 1000,
path: '/',
});
}

export const signup = asyncHandler(async (req, res) => {
const { email, password, username, firstname, lastname } = req.body;
if (!email || !password) throw new BadRequestError('Email and password are required');
if (!isStrongPassword(String(password), { minLength: 6, minLowercase: 0, minUppercase: 1, minNumbers: 1, minSymbols: 0 })) {
throw new BadRequestError('Password must be at least 6 characters and include at least one uppercase letter and one number');
}
const user = await signupUser({ email: req.body.email, password, username, firstname, lastname });
setAuthCookie(res, { user_id: user.user_id, email: user.email });
return res.status(201).json(user);
});

export const login = asyncHandler(async (req, res) => {
const { email, password } = req.body;
if (!email || !password) throw new BadRequestError('Email and password are required');
const publicUser = await loginUser({ email: req.body.email, password });
setAuthCookie(res, { user_id: publicUser.user_id, email: publicUser.email });
return res.json(publicUser);
});

export const me = asyncHandler(async (req, res) => {
const user = await getPublicUser(req.user.user_id);
return res.json(user);
});

export const logout = asyncHandler(async (_req, res) => {
res.clearCookie(TOKEN_COOKIE_NAME, { path: '/', sameSite: 'lax' });
return res.status(204).send();
});
16 changes: 16 additions & 0 deletions server/middleware/auth.middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import jwt from 'jsonwebtoken';

export function requireAuth(req, res, next) {
try {
const token = req.cookies?.token;
if (!token) return res.status(401).json({ error: 'Unauthorized' });

const payload = jwt.verify(token, process.env.JWT_SECRET);
if (!payload?.user_id) return res.status(401).json({ error: 'Unauthorized' });

req.user = { user_id: payload.user_id, email: payload.email };
next();
} catch (err) {
return res.status(401).json({ error: 'Unauthorized' });
}
}
61 changes: 61 additions & 0 deletions server/middleware/validate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { BadRequestError } from '../utils/errors.js';
import isEmail from 'validator/lib/isEmail.js';
import normalizeEmail from 'validator/lib/normalizeEmail.js';

export const requireFields = (...fields) => (req, _res, next) => {
for (const f of fields) {
const v = req.body?.[f];
if (v == null || v === '') {
return next(new BadRequestError(`Missing field: ${f}`));
}
}
next();
};

// Normalize and validate email. Sets req.body.email to the normalized lowercase value.
export const validateEmail = () => (req, _res, next) => {
const raw = String(req.body.email || '').trim();
if (!isEmail(raw)) return next(new BadRequestError('Invalid email format'));
const normalized = normalizeEmail(raw, {
all_lowercase: true,
gmail_remove_dots: false,
gmail_remove_subaddress: false,
outlookdotcom_remove_subaddress: false,
yahoo_remove_subaddress: false,
icloud_remove_subaddress: false,
});
req.body.email = normalized;
next();
};

export const sanitizeBody = (...fields) => (req, _res, next) => {
for (const f of fields) {
if (typeof req.body?.[f] === 'string') {
req.body[f] = req.body[f].trim();
}
}
next();
};

export const validateTextMaxLengths = (limits) => (req, _res, next) => {
for (const [field, max] of Object.entries(limits || {})) {
const v = req.body?.[field];
if (typeof v === 'string' && v.length > max) {
return next(new BadRequestError(`${field} is too long (max ${max} characters)`));
}
}
next();
};

// Combined middlewares for cleaner routes
export const validateSignup = [
requireFields('email', 'password'),
validateEmail(),
sanitizeBody('username', 'firstname', 'lastname'),
validateTextMaxLengths({ username: 50, firstname: 50}),
];

export const validateLogin = [
requireFields('email', 'password'),
validateEmail(),
];
Loading