Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Auth middleware
import jwt from "jsonwebtoken";
import User from "@server/models/user_model";
const PRODUCTION = process.env.NODE_ENV === "production";
export default (options) => async (req, res, next) => {
const refreshToken = req.cookies["refresh_token"];
const accessToken = req.cookies["access_token"];
const csrfHeader = req.get("X-Csrf-Token");
if (req.get("X-Csrf-Token") || !options.checkCsrf) {
if (accessToken && refreshToken) {
res.set({ "Cache-Control": "private" });
try {
// Access token valid, user set on req object
if (user.csrfToken === csrfHeader || !options.checkCsrf) {
req.user = user;
next();
} else {
next();
}
} catch (e) {
// Access token expired
try {
//Try to refresh tokens using refresh token
const user = jwt.verify(refreshToken, process.env.SECRET);
if (user.csrfToken === csrfHeader || !options.checkCsrf) {
const dbUser = await User.query()
.first()
.where("fb_user_id", user.sub);
if (dbUser && dbUser.refresh_token === refreshToken) {
const {
accessToken: newAccessToken,
refreshToken: newRefreshToken,
csrfToken: newCsrfToken
} = await dbUser.generateTokens();
await User.query()
.patch({ refresh_token: newRefreshToken, updated_at: new Date() })
.where("id", dbUser.id);
req.user = jwt.decode(newAccessToken);
res.cookie("refresh_token", newRefreshToken, { httpOnly: true, secure: PRODUCTION, overwrite: true });
res.cookie("access_token", newAccessToken, { httpOnly: true, secure: PRODUCTION, overwrite: true });
res.cookie("csrf_token", newCsrfToken, { overwrite: true, secure: PRODUCTION });
} else {
// User not found or user token doesn't match token from cookie
}
} else {
// Invalid CSRF token
next();
}
} catch (e) {
// Refresh token expired
res.clearCookie("refresh_token");
res.clearCookie("access_token");
} finally {
console.log("Continue");
next();
}
}
} else {
// Tokens missing
next();
}
} else {
// CSRF-header missing
next();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment