-
Notifications
You must be signed in to change notification settings - Fork 119
/
index.js
70 lines (59 loc) · 1.5 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
"use strict";
/**
* This example shows how to use authorization with API Gateway
*
* Example:
*
* - Try to call /test/hello. It will throw Forbidden
*
* http://localhost:3000/test/hello
*
* - Set "Authorization: Bearer 123456" to header" and try again. It will receive the response
*
*/
let path = require("path");
let { ServiceBroker } = require("moleculer");
let ApiGatewayService = require("../../index");
const { CustomError } = require("moleculer").Errors;
// Create broker
let broker = new ServiceBroker({
logger: console
});
// Load other services
broker.loadService(path.join(__dirname, "..", "test.service"));
// Load API Gateway
broker.createService(ApiGatewayService, {
settings: {
routes: [
{
// Enable authorization
authorization: true
}
]
},
methods: {
/**
* Authorize the user from request
*
* @param {Context} ctx
* @param {IncomingMessage} req
* @param {ServerResponse} res
* @returns
*/
authorize(ctx, req, res) {
let auth = req.headers["authorization"];
if (auth && auth.startsWith("Bearer")) {
let token = auth.split(" ")[1];
if (token == "123456") {
// Set the authorized user entity to `ctx.meta`
ctx.meta.user = { id: 1, name: "John Doe" };
return Promise.resolve(ctx);
} else
return Promise.reject(new CustomError("Unauthorized! Invalid token", 401));
} else
return Promise.reject(new CustomError("Unauthorized! Missing token", 401));
}
}
});
// Start server
broker.start();