This repository was archived by the owner on Jun 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathauthorize.js
54 lines (45 loc) · 1.71 KB
/
authorize.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
'use strict';
var client = require('./client');
function apiKeyAuth(apiToken, cb) {
// noop; Just forward the API key to the request handler
return cb(null, null, apiToken); // HACK: Pass API token as second param
}
function accessTokenAuth(accessToken, cb) {
// noop; Just forward the token to the request handler
return cb(null, accessToken);
}
function emailAuth(authEmail, authPassword, cache, cb) {
// If using email auth, we will hit an endpoint to sign them in, obtain
// an access_token, and then use that for the request.
var noHeaders = {};
return client(
'post',
'/users/login',
{ email: authEmail, password: authPassword },
noHeaders,
null,
function clientCb(clientErr, clientResp) {
if (clientErr) return cb(clientErr, clientResp);
return cb(null, clientResp.id);
}
);
}
function authorize(authEmail, authPassword, accessToken, apiKey, cache, cb) {
// The preferred way to authorize is via an actual api token
if (apiKey) cache.apiKey = apiKey;
else apiKey = cache.apiKey;
if (apiKey) return apiKeyAuth(apiKey, cb);
// The user can also supply an actual access_token a.k.a. a jwt, for requests
// Possibly worth adding a deprecation warning here.
if (accessToken) cache.accessToken = accessToken;
else accessToken = cache.accessToken;
if (accessToken) return accessTokenAuth(accessToken, cb);
// Finally, they are also allowed to use their account credentials if they so desire
// Possibly worth adding a deprecation warning here.
if (authEmail && authPassword) {
return emailAuth(authEmail, authPassword, cache, cb);
}
// If none of the above are provided, we can't go forward at all
return cb(new Error('Please provide authentication credentials'));
}
module.exports = authorize;