UNPKG

1.57 kBJavaScriptView Raw
1const Gateway = require('./Gateway');
2
3/**
4 * An authenticator service. It its simplest form, it managing
5 * gateways.
6 */
7class Authenticator {
8 constructor() {
9 this.gateways = new Map();
10 }
11
12 /**
13 *
14 * @param gateway
15 * @param protocol
16 * @param provider
17 */
18 gate(gateway, protocol, provider) {
19 this.gateways.set(gateway, new Gateway(protocol, provider));
20 }
21
22 /**
23 * Authenticate a context by a given gateway.
24 *
25 * @param gateway
26 * @param context
27 * @return {Promise<void>}
28 */
29 authenticate(gateway, context) {
30 return this.gateways.get(gateway).authenticate(context);
31 }
32
33 /**
34 * Returning a connection which can be used to mount to
35 * the transport layer.
36 *
37 * Normally, we need to authenticate over Http, then guard() will
38 * return a middleware.
39 *
40 * If we authenticate over Socket, then guard() will return the
41 * socket connection middleware.
42 *
43 * @param gateway
44 * @return {mount}
45 */
46 guard(gateway) {
47 const protocol = this.gateways.get(gateway).protocol;
48 if ('function' !== typeof protocol.mount) {
49 throw new Error(
50 `The protocol [${protocol.constructor.name}] of the gateway [${gateway}]` +
51 `does not support mounting to a framework.`
52 );
53 }
54 return this.gateways.get(gateway).protocol.mount((context => {
55 return this.authenticate(gateway, context);
56 }));
57 }
58}
59
60module.exports = Authenticator;