Skip to content

Instantly share code, notes, and snippets.

@atakde
Created April 24, 2022 21:42
Show Gist options
  • Save atakde/7d93d6a0193d6144426c49278c8c8ea3 to your computer and use it in GitHub Desktop.
Save atakde/7d93d6a0193d6144426c49278c8c8ea3 to your computer and use it in GitHub Desktop.
Node.js JWT Authentication With HTTP Only Cookie
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import { PrismaClient } from '@prisma/client';
import HTTPMethod from 'http-method-enum';
import HTTP_STATUS_CODES from 'http-status-enum';
import { serialize } from 'cookie';
const prisma = new PrismaClient();
const KEY = process.env.JWT_KEY;
export default async function authenticate(req, res) {
const { method } = req;
try {
switch (method) {
case HTTPMethod.POST:
const { email, password } = req.body;
if (!email || !password) {
return res.status(HTTP_STATUS_CODES.BAD_REQUEST).json({
status: 'error',
error: 'Request missing email or password',
});
}
const user = await prisma.user.findUnique({
where: {
email: email,
},
});
if (!user) {
return res
.status(HTTP_STATUS_CODES.BAD_REQUEST)
.json({ status: 'error', error: 'User Not Found' });
}
bcrypt.compare(password, user.password).then((isMatch) => {
if (isMatch) {
const payload = {
id: user.id,
email: user.email,
createdAt: user.createdAt,
username: user.username,
fullname: user.fullname,
};
jwt.sign(
payload,
KEY,
{
expiresIn: 60 * 60 * 24 * 30,
},
(_err, token) => {
const serialized = serialize('token', token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
maxAge: 60 * 60 * 24 * 30,
path: '/',
});
res.setHeader('Set-Cookie', serialized);
res.status(HTTP_STATUS_CODES.OK).json({
success: true,
user: {
email: payload.email,
username: payload.username,
fullname: payload.fullname,
},
});
},
);
} else {
res.status(HTTP_STATUS_CODES.BAD_REQUEST).json({
status: 'error',
error: 'Password and email does not match.',
});
}
});
break;
}
} catch (error) {
console.log(error);
res.status(HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR).json({
status: 'error',
error: 'Internal Server Error',
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment