UNPKG

replit-auth

Version:

A really optimized and small express middleware for repl authentication.

55 lines (46 loc) 1.56 kB
let path = __dirname + '/login.html'; const parseHeaders = (headers) => { const user = {}; for (const header in headers) { const val = headers[header]; if (header.startsWith('x-replit-') && val && typeof val === 'string') { const prop = header.replace('x-replit-user-', '').replace(/-(.)/g, (m, l) => l.toUpperCase()); switch (prop) { case 'id': user[prop] = +val; break; case 'roles': case 'teams': user[prop] = val.split(','); break; default: user[prop] = val; } } } return Object.keys(user).length === 0 ? null : user; } const auth = ({ user }, res, next) => { if (user) return next(); try { res.render(path); } catch (err) { res.sendFile(path); } }; /** * @module replit-auth * @param {object} app - An Express.js app instance. * @param {object} options - An options object. * @param {boolean} [options.allRoutes=true] - Whether to protect all routes with the middleware, or just specific ones. * @param {String} [options.customPage] Path to custom auth page file * @returns {(undefined|function)} - If allRoutes is true, returns undefined, otherwise returns the middleware function */ module.exports = function createAuthMiddleware(app, { allRoutes = true, customPage } = {}) { if (customPage) path = customPage; app.use((req, _next, next) => { req.user = parseHeaders(req.headers || req.request.headers); next ? next() : _next(); }); if (!app.eio) return allRoutes ? app.use(auth) : auth; };