0.1.2 • Published 6 years ago

express-route-config v0.1.2

Weekly downloads
1
License
MIT
Repository
github
Last release
6 years ago

Express route config

A simple route configuration for Express apps powered by Typescript typing.

Greenkeeper badge Travis codecov Dev Dependencies

About

The motivation is to provide a simple util for role based authentication. It's a common scenario in web apps that some routes are public, allowed only for authentication users or only for admins.

Getting Started

npm install express-route-config
yarn add express-route-config

Example

import passport from 'passport';
import { loadRoutes } from 'express-route-config';

const app = express();
const router = Router();

type UserRole = 'user' | 'admin' | 'reporter';

loadRoutes<UserRole>({
  // use any ExpressJS middleware for authentication
  // The middleware should set `req.user` if authentication was successful.
  authMiddleware: passport.authenticate('bearer', { session: false }),
  router,
  hasRole: (req, role) => req.user.role === role,
  isLoggedIn: req => req.user != null,
  routes: {
    '/public': {
      get: {
        method: handler,
        public: true,
      },
    },
    '/public2': {
      get: {
        // method can be any valid handler/middleware used in Express
        method: [handler, handler2, handler3],
        public: true,
      },
    },
    '/auth': {
      get: {
        method: handler,
      },
    },
    '/admin-only': {
      get: {
        method: handler,
        // roles must be UserRole
        // an error will be reported if there is any typo
        roles: 'admin',
      },
    },
    '/any-roles': {
      get: {
        method: handler,
        roles: ['user', 'admin'],
      },
    },
  },
});

app.use('/', router);

// in types/index.ts
// extend the Request object to include a `user` property.
declare global {
  namespace Express {
    interface Request {
      user: {
        id: string;
        role: UserRole
      };
    }
  }
}

// or if you install @types/passport
declare global {
  namespace Express {
    interface User {
      id: string;
      role: UserRole;
  }
}

Docs

API Reference

License

MIT

0.1.2

6 years ago

0.1.1

6 years ago

0.1.0

6 years ago

0.0.3

6 years ago

0.0.2

6 years ago

0.0.1

6 years ago

0.0.0

6 years ago

1.0.0

8 years ago