This repository was archived by the owner on Jun 24, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathstore.js
More file actions
69 lines (60 loc) · 1.62 KB
/
store.js
File metadata and controls
69 lines (60 loc) · 1.62 KB
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
'use strict';
const fetch = require('node-fetch');
const config = require('../../config/constants.js');
const authMiddleware = require('../../middlewares/auth0.js');
// Get an access token for the Auth0 Admin API
function getAdminAccessToken() {
const options = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
client_id: config.auth0.CLIENT_ID,
client_secret: config.auth0.CLIENT_SECRET,
audience: `${config.auth0.DOMAIN}/api/v2/`,
grant_type: 'client_credentials',
}),
};
return fetch(`${config.auth0.DOMAIN}/oauth/token`, options)
.then((response) => response.json());
}
// Get the user's profile from auth0
function getUserProfile(accessToken, userID) {
const options = {
headers: {
'Authorization': `Bearer ${accessToken}`
}
}
return fetch(`${config.auth0.DOMAIN}/api/v2/users/${userID}`, options)
.then(response => response.json());
}
module.exports.add = authMiddleware(async (context, request) => {
let res = {};
try {
const data = await getAdminAccessToken();
const user = await getUserProfile(data.access_token, request.user.sub);
// @TODO: check if the current user already exist in the database,
// if not, we need to add the new record.
res = {
body: {
success: true,
message: 'User successfully saved',
user,
},
};
} catch (error) {
res = {
status: 500,
body: {
success: false,
error,
},
};
}
context.res = {
...res,
headers: {
'Content-Type': 'application/json'
},
};
context.done()
});