-
Notifications
You must be signed in to change notification settings - Fork 102
/
api.service.js
101 lines (85 loc) · 2.16 KB
/
api.service.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
"use strict";
const _ = require("lodash");
const ApiGateway = require("moleculer-web");
const { UnAuthorizedError } = ApiGateway.Errors;
module.exports = {
name: "api",
mixins: [ApiGateway],
settings: {
port: process.env.PORT || 3000,
routes: [{
path: "/api",
authorization: true,
autoAliases: true,
// Set CORS headers
cors: true,
// Parse body content
bodyParsers: {
json: {
strict: false
},
urlencoded: {
extended: false
}
}
}],
assets: {
folder: "./public"
},
// logRequestParams: "info",
// logResponseData: "info",
onError(req, res, err) {
// Return with the error as JSON object
res.setHeader("Content-type", "application/json; charset=utf-8");
res.writeHead(err.code || 500);
if (err.code == 422) {
let o = {};
err.data.forEach(e => {
let field = e.field.split(".").pop();
o[field] = e.message;
});
res.end(JSON.stringify({ errors: o }, null, 2));
} else {
const errObj = _.pick(err, ["name", "message", "code", "type", "data"]);
res.end(JSON.stringify(errObj, null, 2));
}
this.logResponse(req, res, err ? err.ctx : null);
}
},
methods: {
/**
* Authorize the request
*
* @param {Context} ctx
* @param {Object} route
* @param {IncomingRequest} req
* @returns {Promise}
*/
async authorize(ctx, route, req) {
let token;
if (req.headers.authorization) {
let type = req.headers.authorization.split(" ")[0];
if (type === "Token" || type === "Bearer")
token = req.headers.authorization.split(" ")[1];
}
let user;
if (token) {
// Verify JWT token
try {
user = await ctx.call("users.resolveToken", { token });
if (user) {
this.logger.info("Authenticated via JWT: ", user.username);
// Reduce user fields (it will be transferred to other nodes)
ctx.meta.user = _.pick(user, ["_id", "username", "email", "image"]);
ctx.meta.token = token;
ctx.meta.userID = user._id;
}
} catch (err) {
// Ignored because we continue processing if user doesn't exists
}
}
if (req.$action.auth == "required" && !user)
throw new UnAuthorizedError();
}
}
};