auth-server-helper/README.md

65 lines
1.4 KiB
Markdown
Raw Normal View History

2020-05-17 17:37:41 +02:00
# @sapphirecode/auth-server-helper
2020-03-06 12:06:10 +01:00
2020-07-10 15:39:14 +02:00
version: 1.1.x
2020-05-17 17:37:41 +02:00
authentication middleware for express
## Installation
npm:
> npm i --save @sapphirecode/auth-server-helper
yarn:
> yarn add @sapphirecode/auth-server-helper
2020-03-06 12:06:10 +01:00
## Usage
```js
2020-05-17 18:55:29 +02:00
const auth = require('@sapphirecode/auth-server-helper');
const password_helper = require('@sapphirecode/password_helper');
2020-03-11 16:03:49 +01:00
const users = {
foo: {
id: 0
password: await password_helper.hash('bar'),
salt: '123'
}
}
2020-03-06 12:06:10 +01:00
// add cookieParser to allow session management via cookies
app.use(cookieParser());
2020-03-11 16:03:49 +01:00
// the middleware needs a function to determine user data
// this function can also return a promise
app.use(auth((user_name) => {
if (!users[user_name])
return null;
return users[user_name];
}));
2020-03-06 12:06:10 +01:00
```
2020-05-17 17:37:41 +02:00
when a client logs in, it will set a header called 'session' that the client can
use to authorize the following requests. it also sets a cookie to make
requesting from the client more simple. (cookie parser is needed to make
authentication with cookies possible)
2020-03-14 12:38:40 +01:00
2020-07-10 15:39:14 +02:00
the id of the logged in user will be available in `res.connection.user_id` in
all of the following request handlers.
2020-05-17 17:37:41 +02:00
### Excluding routes
2020-03-14 12:38:40 +01:00
2020-05-17 17:37:41 +02:00
exceptions to the auth module can be added by adding an array of regular
expressions a specific method can also be filtered for by giving an object
instead of a plain regular expression.
2020-03-14 12:38:40 +01:00
```js
auth(..., [/no-auth/, {regex: '/no-auth-post/', method: 'POST'}]);
2020-05-17 17:37:41 +02:00
```
## License
MIT © Timo Hocker <timo@scode.ovh>