@keeex/js-utils-express
v2.0.0
Published
Shared code for express servers
Readme
Utility functions for express
Some tools for express. For now there's a handler for promise-based requests and an authentication middleware.
Promise-based request
Write your handler as a function that takes req and res as its parameter
and returns a promise.
Then, use promiseHandler(yourfunction) in the express router.
Note that res is provided only for header manipulations; no data is expected to
be sent by the handling promise.
The function will be called when a request come through the router with the
appropriate req object.
When the promise resolve, the result is inspected and depending on it three outcome can happen:
- an object is returned: in that case, the object is used in the reply as-is. It is replied as a JSON.
- null is returned: an object with a single
okproperty set to true is replied as a JSON. - undefined is returned: the next handle will be called on the request
If the promise reject, the error is left to the error handlers.
Authentication middleware
The authentication middleware is really basic and only deal with the client-side aspect of authenticated requests. Actually performing the authentication process is not handled here. This middleware will only set/retrieve a JWT and provide the informations from it.
Expected usage should follow these instructions:
- Create a module somewhere where the authentication middleware object is initialized with proper secrets
- Use the
middleware()method in your router above the routes you want to have the user authenticate. This method can be customized to do some simple filtering on users. - Use the
setToken()method to setup the token in the cookies. It is also possible to retrieve the token from the return of the method, in case you'd rather put the token in the headers. - It is possible to use
clearToken()to remove the cookie easily.
When using the cookie, the rest of the process is automatic. When using headers, the header name used must match the one configured in the middleware, which defaults to "X-Auth-Token".
Note that returning the token to the JavaScript clientside and using it in headers makes it so it can be stolen and reused by a third party; in that case measures against CSRF must be implemented.
