Created
September 13, 2019 20:45
-
-
Save tcrowe/ef781ebe09dad7035a89718e0c6912fb to your computer and use it in GitHub Desktop.
express, sapper, polka authentication idea
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
/* | |
+ 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