Skip to content

Instantly share code, notes, and snippets.

@tcrowe
Created September 13, 2019 20:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tcrowe/ef781ebe09dad7035a89718e0c6912fb to your computer and use it in GitHub Desktop.
Save tcrowe/ef781ebe09dad7035a89718e0c6912fb to your computer and use it in GitHub Desktop.
express, sapper, polka authentication idea
/*
+ assuming you're using cookie-session or similar session
usage:
import authenticated from "./middleware/authenticated.js"
server.use(authenticated)
*/
// ➕ add more routes as needed
const privateRoutes = [
"/dashboard",
"/account"
];
// ↪️ where to redirect to login
const loginRoute = "/login";
export default function authenticated(req, res, next) {
const { url, session } = req;
let privateRouteFound = false;
// [].some is like for each but you can stop it
const privateRouteFound = privateRoutes.some(function(privateRoute) {
if (url.toLowerCase().startsWith(privateRoute.toLowerCase()) === true) {
// found, stop `some` loop
return true;
}
// not found, keep looping and searching
return false;
});
if (privateRouteFound === true) {
if (
// session is blank
session === undefined ||
session === null ||
// or they aren't logged in yet
session.loggedIn === false
) {
// 🛡shall not pass
return res.redirect(loginRoute);
}
}
// ✅ should be okay
next();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment