-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.js
159 lines (140 loc) · 4.9 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
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
const dotenv = require('dotenv').config();
require('isomorphic-fetch');
const compression = require('compression');
const express = require('express');
const app = express();
const crypto = require('crypto');
const cookie = require('cookie');
const nonce = require('nonce')();
const querystring = require('querystring');
const apiKey = process.env.SHOPIFY_API_KEY;
const apiSecret = process.env.SHOPIFY_API_SECRET;
const scopes = 'read_products';
const forwardingAddress = process.env.HOST;
app.use(compression());
app.use((req, res, next) => {
console.log(req.path);
next();
})
app.use('/proxy', express.static('./static'));
app.get('/', (req, res) => {
res.send('Your server is up. Add shop parameter to url to start a install on a shop. eg /shopify?shop=xxx.myshopify.com');
});
app.use('/reverse-proxy', async (req, res) => {
try {
const url = req.query.url;
const response = await fetch(url, {
method: req.method,
// headers: req.headers,
body: req.body
});
const responseContent = await response.text();
// set fetch response headers to res headers
[...response.headers].forEach(([key, value]) => {
if (key.toLowerCase() == 'access-control-allow-methods') {
res.setHeader(key, value);
}
});
// remove powered-by-express header
res.removeHeader('x-powered-by');
// set cors headers
res.setHeader('Content-Type', 'application/javascript');
res.setHeader('Access-Control-Allow-Origin', '*');
// allow all headers
res.setHeader('Access-Control-Allow-Headers', '*');
// add a cache policy that caches for 1 day
res.setHeader('Cache-Control', 'public, max-age=86400');
res.send(responseContent);
} catch (err) {
res.status(500).send('Could not get resource');
}
});
// Shopify install route
app.get('/shopify', (req, res) => {
const shop = req.query.shop;
if (shop) {
const state = nonce();
const redirectUri = forwardingAddress + '/shopify/callback';
const installUrl = 'https://' + shop +
'/admin/oauth/authorize?client_id=' + apiKey +
'&scope=' + scopes +
'&state=' + state +
'&redirect_uri=' + redirectUri;
res.cookie('state', state);
res.redirect(installUrl);
} else {
return res.status(400).send('Missing shop parameter. Please add ?shop=your-development-shop.myshopify.com to your request');
}
});
// Shopify callback route
app.get('/shopify/callback', async (req, res) => {
const { shop, hmac, code, state } = req.query;
const stateCookie = cookie.parse(req.headers.cookie).state;
if (state !== stateCookie) {
return res.status(403).send('Request origin cannot be verified');
}
if (shop && hmac && code) {
// DONE: Validate request is from Shopify
const map = Object.assign({}, req.query);
delete map['signature'];
delete map['hmac'];
const message = querystring.stringify(map);
const providedHmac = Buffer.from(hmac, 'utf-8');
const generatedHash = Buffer.from(
crypto
.createHmac('sha256', apiSecret)
.update(message)
.digest('hex'),
'utf-8'
);
let hashEquals = false;
// timingSafeEqual will prevent any timing attacks. Arguments must be buffers
try {
hashEquals = crypto.timingSafeEqual(generatedHash, providedHmac)
// timingSafeEqual will return an error if the input buffers are not the same length.
} catch (e) {
hashEquals = false;
};
if (!hashEquals) {
return res.status(400).send('HMAC validation failed');
}
// DONE: Exchange temporary code for a permanent access token
const accessTokenRequestUrl = 'https://' + shop + '/admin/oauth/access_token';
const accessTokenPayload = {
client_id: apiKey,
client_secret: apiSecret,
code,
};
fetch(accessTokenRequestUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(accessTokenPayload),
})
.then((accessTokenResponse) => accessTokenResponse.json())
.then((accessTokenResponse) => {
const accessToken = accessTokenResponse.access_token;
const shopRequestUrl = 'https://' + shop + '/admin/api/2020-01/shop.json';
const shopRequestHeaders = {
'X-Shopify-Access-Token': accessToken,
};
fetch(shopRequestUrl, { headers: shopRequestHeaders })
.then((shopResponse) => shopResponse.json())
.then((shopResponse) => {
res.status(200).end(shopResponse);
})
.catch((error) => {
res.status(error.statusCode).send(error.error.error_description);
});
})
.catch((error) => {
res.status(error.statusCode).send(error.error.error_description);
});
} else {
res.status(400).send('Required parameters missing');
}
});
app.listen(process.env.PORT || 3000, () => {
console.log('Example app listening on port ' + process.env.PORT || 3000 + '!');
});