/
middleware.ts
96 lines (76 loc) · 2.5 KB
/
middleware.ts
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
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import fetch from 'node-fetch';
const IFTTT_KEY = process.env.IFTTT_KEY;
// Common functions for processing secure routes
export class Middleware {
public static actionFieldsCheck(req, res, next) {
if (!req.body || req.body.actionFields === undefined) {
res.status(400).json({
errors: [{
message: 'Incomplete data sent, please supply actionFields'
}]
});
}
else {
next();
}
}
public static triggerFieldsCheck(req, res, next) {
if (!req.body || req.body.triggerFields === undefined) {
res.status(400).json({
errors: [{
message: 'Incomplete data sent, please supply triggerFields'
}]
});
}
else {
next();
}
}
// Validate the IFTTT service key value
public static serviceKeyCheck (req, res, next) {
console.log(req.originalUrl);
const key = req.get("IFTTT-Service-Key");
if (key !== IFTTT_KEY) {
res.status(401).send({
errors: [{
message: "Channel/Service key is not correct"
}]
});
next('router');
}
else {
next();
}
}
// Validate the graph auth token in the authorization header
public static async authorizationCheck(req, res, next)
{
const authHeader = req.headers.authorization;
// Simply check auth by using the supplied key to query your own data.
const url = "https://graph.microsoft.com/v1.0/me";
const graphResponse = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Authorization': authHeader
}
});
if (graphResponse.ok) {
next();
}
else {
res.status(401).send({
"errors": [{
"message": `Authorization key is not correct : ${authHeader}`
}]
});
next('router');
}
}
};