/
index.js
259 lines (232 loc) · 8.59 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
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
var crypto = require('crypto');
var path = require('path');
var url = require('url');
var request = require('request');
var Cache = require('lru-cache');
var DOMAIN = 'myshopify.com';
var INVALID_CHAR_RE = /[^0-9a-zA-Z.-]/;
/**
* @class ShopifyAuth
*/
var ShopifyAuth = {};
/**
* @param {String} appSecret
* @param {Object} params
* @returns {boolean}
*/
ShopifyAuth.checkIntegrity = function (appSecret, params) {
var hmac = params.hmac;
var message = Object.keys(params).filter(function (key) {
return key !== 'hmac' && key !== 'signature';
}).sort().map(function (key) {
// have to replace in this order,
var escapedKey = key.replace('%', '%25').replace('&', '%26').replace('=', '%3D'),
escapedVal = params[key].replace('%', '%25').replace('&', '%26');
return escapedKey + '=' + escapedVal;
}).join('&');
// get message signature
var ourSignature = crypto.createHmac('sha256', appSecret).update(message).digest('hex');
return ourSignature === hmac;
};
ShopifyAuth.checkShopHostname = function (hostname) {
var hasInvalidChar = INVALID_CHAR_RE.test(hostname);
var hasRightDomain = hostname.substring(hostname.length - DOMAIN.length) === DOMAIN;
return !hasInvalidChar && hasRightDomain;
};
/**
* @method exchangeCodeForToken
* @param {Object} options
* @param {String} options.appKey
* @param {String} options.appSecret
* @param {String} options.code
* @param {String} options.shopDomain
* @param {Function} cb
* @static
*/
ShopifyAuth.exchangeCodeForToken = function (options, cb) {
var opts = {
url: 'https://' + options.shopDomain + '/admin/oauth/access_token',
form: {
client_id: options.appKey,
client_secret: options.appSecret,
code: options.code
}
};
request.post(opts, function (err, res, body) {
if (err) return cb(err);
if (typeof body === 'string') {
try {
body = JSON.parse(body);
} catch (e) {
return cb(e);
}
}
if (!body.access_token) {
return cb(new Error('no access token supplied by shopify'));
}
return cb(null, body.access_token);
});
};
/**
* Express middleware for authenticating with Shopify via OAuth.
*
* Supports dynamic shop names and subsequent verification of
* incoming requests.
*
* Usage:
*
* ```
* var ShopifyAuth = require('./lib/shopify/auth');
*
* var auth = ShopifyAuth.create({
* appKey: 'your_app_key',
* appSecret: 'your_app_secret',
* scope: ['read_products'],
* authUrl: '/auth/shopify',
* authCallbackUrl: '/auth/shopify/callback',
* shop: function (req, done) {
* done(req.query.shop);
* },
* beforePermission: function (redirectUrl, done) {
* done();
* },
* afterAuth: function (accessToken, profile, done) {
* // req.shop now contains the authenticated shop
* }
* });
*
* app.use('/auth/shopify/', shopifyAuth)
* app.use('/auth/shopify/callback')
* ```
*
* Reference:
* https://docs.shopify.com/api/authentication/oauth
*
* @method create
* @param {Object} options
* @param {String} options.appKey
* @param {String} options.appSecret
* @param {String} options.baseUrl Base url of the server (eg. `https://localhost:8000`)
* @param {String} options.authPath Path that starts the auth process.
* @param {String} options.authCallbackPath Path that Shopify will redirect shop admins after
* granting permissions.
* @param {String} [options.redirectUrl] URL that Shopify will redirect shop admins after granting
* permissions. This should be the same as
* `url.resolve(baseUrl, authCallbackPath`.
* @param {[String]} options.scope Application scope. Eg. `['read_products', 'write_products']`
* @param {Function} options.shop Called with `(req, done)` and used to dynamically get
* the shop's myshopify domain from a request. Call `done(err,
* shop)` to continue.
* @param {String} options.authSuccessUrl User is redirected here if authentication succeeds.
* @param {String} options.authFailUrl User is redirected here if authentication fails.
* @param {Function} [options.onPermission] Called with `(shop, redirectUrl, done)` before redirecting to
* Shopify to ask for permissions.
* @param {Function} options.onAuth Called with `(req, shop, accessToken, done)` once
* authentication is
* done, but before redirecting to `authSuccessUrl`.
* @param {Function} [options.onError] Called with `(err, req, res, next)`.
*/
ShopifyAuth.create = function (options) {
var self = this;
// LRU cache to store randomly generated `state` during authentication
var cache = Cache({
max: 5000,
maxAge: 1000 * 60 * 5 // 5 minutes
});
var onError = options.onError;
if (!onError) {
onError = function (err, req, res, next) {
// log the error
if (err.stack) {
console.error(err.stack);
} else {
console.error(err);
}
// redirect
res.redirect(options.authFailUrl);
}
}
var middleware = function (req, res, next) {
if (req.path !== options.authPath && req.path !== options.authCallbackPath) {
return next();
}
if (req.path === options.authPath) {
return middleware.shop(req, function (err, shop) {
if (err) {
return middleware.onError(err, req, res, next);
}
var nonce;
try {
nonce = crypto.randomBytes(12).toString('hex');
} catch (e) {
nonce = crypto.pseudoRandomBytes(12).toString('hex');
}
cache.set(shop, nonce);
var redirectUrl = url.format({
protocol: 'https',
host: shop,
pathname: '/admin/oauth/authorize',
query: {
client_id: options.appKey,
scope: options.scope.join(','),
redirect_uri: options.redirectUrl ?
options.redirectUrl :
url.resolve(options.baseUrl, options.authCallbackPath),
state: nonce
}
});
if (!middleware.onPermission) {
// redirect to shopify to ask for permission
return res.redirect(redirectUrl);
}
// call onPermission handler and redirect
return middleware.onPermission(shop, redirectUrl, function () {
return res.redirect(redirectUrl);
});
});
} else {
var params = req.query;
if (!(params && params.code && params.hmac && params.timestamp && params.state && params.shop)) {
var paramErr = new Error('ShopifyAuth: missing required query parameters (got ' +
Object.keys(params).join(',') + ')');
return middleware.onError(paramErr, req, res, next);
}
if (cache.get(params.shop) !== params.state) {
var stateErr = new Error('ShopifyAuth: state not found in cache');
return middleware.onError(stateErr, req, res, next);
}
if (!ShopifyAuth.checkIntegrity(options.appSecret, params)) {
var integrityErr = new Error('ShopifyAuth: integrity error (signature mismatch)');
return middleware.onError(integrityErr, req, res, next);
}
if (!ShopifyAuth.checkShopHostname(params.shop)) {
var shopErr = new Error('ShopifyAuth: invalid shop hostname `' + params.shop + '`');
return middleware.onError(shopErr, req, res, next);
}
var exchangeOptions = {
appKey: options.appKey,
appSecret: options.appSecret,
code: params.code,
shopDomain: params.shop
};
self.exchangeCodeForToken(exchangeOptions, function (err, accessToken) {
if (err) {
return middleware.onError(err, req, res, next);
}
return middleware.onAuth(req, res, params.shop, accessToken, function (err) {
if (err) {
return middleware.onError(err, req, res, next);
}
return res.redirect(options.authSuccessUrl);
});
});
}
};
middleware.shop = options.shop;
// attach handlers to middleware fn
middleware.onError = onError;
middleware.onAuth = options.onAuth;
middleware.onPermission = options.onPermission;
return middleware;
};
module.exports = ShopifyAuth;