This repository has been archived by the owner on May 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathserver.js
197 lines (188 loc) · 6.94 KB
/
server.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
const http = require("http");
const https = require("https");
const jwt = require("jsonwebtoken");
const cards = require("./cards");
// get the public key for JWT verification
var publicKeyUrl = getPublicKeyUrl();
var publicKey;
function parsePublicKey(res) {
var rawData = "";
res.on("data", chunk => {
rawData += chunk;
});
res.on("end", () => {
try {
publicKey = JSON.parse(rawData)["value"];
} catch (e) {
console.error(e.message);
}
});
}
if (publicKeyUrl.includes("https")) {
https.get(publicKeyUrl, res => parsePublicKey(res));
} else {
http.get(publicKeyUrl, res => parsePublicKey(res));
}
// In a real implementation, HTTPS must be used
http
.createServer((req, res) => {
if (req.method != "POST") return errorResponse(res);
var transactionType = req.headers["Toast-Transaction-Type".toLowerCase()]; // toLowerCase because the http module
var transactionGuid = req.headers["Toast-Transaction-GUID".toLowerCase()]; // stores all headers as lowercase
var restaurantGuid =
req.headers["Toast-Restaurant-External-ID".toLowerCase()];
var token = req.headers["Authorization".toLowerCase()];
// if one of the headers are null or invalid
if (!(transactionType && transactionGuid && restaurantGuid && token)) {
return errorResponse(res, "ERROR_INVALID_INPUT_PROPERTIES");
}
// verify that the JWT is valid and from Toast
try {
var decoded = jwt.verify(token, publicKey, { algorithms: ["RS256"] });
} catch (e) {
return errorResponse(res, "ERROR_INVALID_TOKEN");
}
if (transactionType == null)
return errorResponse(res, "ERROR_INVALID_TOAST_TRANSACTION_TYPE");
let body = "";
req.on("data", chunk => {
body += chunk.toString(); // converting body buffer to string
});
req.on("end", () => {
console.log("Request received, type: " + transactionType + ", GUID: " + transactionGuid + ": " + body);
body = JSON.parse(body); // converting body string to JSON
var info;
var identifier;
var amount;
var card;
var responseBody;
switch (transactionType) {
case "GIFTCARD_ACTIVATE":
try {
info = getPropOrErr(body, "activateTransactionInformation");
identifier = getPropOrErr(info, "giftCardIdentifier");
amount = getPropOrErr(info, "initialBalance");
card = cards.activate(transactionGuid, identifier, amount);
responseBody = {
activateResponse: {
currentBalance: parseFloat(card["balance"]) //parseFloat because API requires double, not string
}
};
return successResponse(res, responseBody);
} catch (e) {
return errorResponse(res, e);
}
case "GIFTCARD_ADD_VALUE":
try {
info = getPropOrErr(body, "addValueTransactionInformation");
identifier = getPropOrErr(info, "giftCardIdentifier");
amount = getPropOrErr(info, "additionalValue");
card = cards.addValue(transactionGuid, identifier, amount);
responseBody = {
addValueResponse: {
currentBalance: parseFloat(card["balance"])
}
};
return successResponse(res, responseBody);
} catch (e) {
return errorResponse(res, e);
}
case "GIFTCARD_GET_BALANCE":
try {
info = getPropOrErr(body, "getBalanceTransactionInformation");
identifier = getPropOrErr(info, "giftCardIdentifier");
let balance = cards.getBalance(identifier, getPropOrErr(info, "verificationCode"));
responseBody = {
getBalanceResponse: {
currentBalance: parseFloat(balance)
}
};
return successResponse(res, responseBody);
} catch (e) {
return errorResponse(res, e);
}
case "GIFTCARD_REDEEM":
try {
info = getPropOrErr(body, "redeemTransactionInformation");
identifier = getPropOrErr(info, "giftCardIdentifier");
let verificationCode = getPropOrErr(info, "verificationCode");
amount = getPropOrErr(info, "redeemedValue");
let origBalance = parseFloat(cards.find(identifier, verificationCode)["balance"]);
card = cards.redeem(transactionGuid, identifier, verificationCode, amount);
responseBody = {
redeemResponse: {
currentBalance: parseFloat(card["balance"]),
redeemedValue: parseFloat(
(origBalance - parseFloat(card["balance"])).toFixed(2)
)
}
};
return successResponse(res, responseBody);
} catch (e) {
return errorResponse(res, e);
}
case "GIFTCARD_REVERSE":
try {
info = getPropOrErr(body, "reverseTransactionInformation");
identifier = getPropOrErr(info, "giftCardIdentifier");
var prevTxn = getPropOrErr(info, "previousTransaction");
card = cards.reverse(transactionGuid, prevTxn, identifier);
responseBody = {
reverseResponse: {
currentBalance: parseFloat(card["balance"])
}
};
return successResponse(res, responseBody);
} catch (e) {
return errorResponse(res, e);
}
default:
return errorResponse(res, "ERROR_INVALID_TOAST_TRANSACTION_TYPE");
}
});
})
.listen(getPort());
console.log("Server is up and listening at localhost:" + getPort());
function getPort() {
if (process.argv[3] != null) {
return process.argv[3];
} else {
return 18181;
}
}
function successResponse(res, responseBody) {
responseBody["transactionStatus"] = (typeof responseBody["transactionStatus"] === 'undefined')
? "ACCEPT"
: responseBody["transactionStatus"]
responseBody = JSON.stringify(responseBody);
res.writeHead(200, { "Content-Type": "application/json" });
console.log("Successful response: " + responseBody);
res.end(responseBody);
}
function errorResponse(res, transactionStatus) {
res.writeHead(400, { "Content-Type": "application/json" });
console.log("Error response: " + transactionStatus);
if (transactionStatus != null) {
res.end(
JSON.stringify({
transactionStatus: transactionStatus
})
);
}
}
function getPropOrErr(info, infoProperty) {
var prop = info[infoProperty];
if (prop == null) {
throw "ERROR_INVALID_INPUT_PROPERTIES";
}
return prop;
}
function getPublicKeyUrl() {
// get the publicKey URL, which can be supplied as an argument: `npm start <URL>` or `node server.js <URL>`
// if it is not supplied as an argument it will default to the Toast sandbox public key
if (process.argv[2] != null) {
return process.argv[2];
} else {
return "https://ws-sandbox-api.eng.toasttab.com/usermgmt/v1/oauth/token_key";
}
}