-
Notifications
You must be signed in to change notification settings - Fork 0
Feat/auth #13
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Feat/auth #13
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
d2a1d82
chore: add .vercel to .gitignore
Mathieu-bot 0659826
Squashed commit of the following:
Mathieu-bot 6e93428
feat(server): add auth route and auth service
Mathieu-bot 35f9c24
Update .gitignore
Mathieu-bot 05a62d0
Merge branch 'dev' into feat/auth
Mathieu-bot 68a5f4b
refactor(server): move auth DB logic to service layer; keep controlle…
Mathieu-bot 178f25e
feat(auth): add email and password strength validation
Mathieu-bot ea48847
refactor(auth): extract validation logic into middleware
Mathieu-bot 885a8c3
Merge remote-tracking branch 'origin/feat/auth' into feat/auth
Mathieu-bot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -53,4 +53,7 @@ jspm_packages/ | |
| .DS_Store | ||
| Thumbs.db | ||
|
|
||
| .vercel/ | ||
| /generated/prisma | ||
| cookies.txt | ||
|
|
||
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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' }); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(), | ||
| ]; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Suggestions
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the suggestions — I agree.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Oh alright! I don’t think it matters that we’re not using Zod.