Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 1x 1x 1x 1x 119x 523x 523x 523x 523x 119x 566x 43x 523x 523x 523x 523x 523x 521x 2x 523x 523x | 'use strict';
const _ = require('lodash');
const jwt = require('jsonwebtoken');
const { deepMapKeysToCamel } = use('C2C/Helpers');
module.exports = function (Request, Config) {
/**
* Macro to login a given user
*/
Request.macro('loginVia', function () {
const args = _.toArray(arguments);
const authenticator = _.size(args) > 1 ? args.pop() : '';
this._loginAsArgs = { authenticator, metadata: args[0] };
return this;
});
/**
* Setting the header before making the request.
*/
Request.before(async (requestInstance) => {
// Skip authentication when loginVia was never executed
if (!requestInstance._loginAsArgs) {
return;
}
// Generate the token
let { authenticator, metadata } = requestInstance._loginAsArgs;
const isM2MAuth = authenticator.toString().toLowerCase() === 'm2m';
let payload = {
iss: Config.get('auth0.host'),
aud: Config.get('app.http.baseUrl'),
};
// Convert model to object
metadata = 'toJSON' in metadata ? metadata.toJSON() : deepMapKeysToCamel(metadata);
if (!isM2MAuth) {
payload = {
...payload,
sub: metadata.id || metadata.userId,
gty: 'password',
'https://user_metadata': metadata.userMetadata || {
salon_id: metadata.salonId || '742857664',
},
'https://authorization': { roles: metadata.roles || [] },
permissions: metadata.permissions || [],
};
} else {
payload = {
...payload,
sub: metadata.id || Config.get('auth0.clientId'),
gty: 'client-credentials',
'https://client_metadata': {
system_id: metadata.systemId || 'system_id',
},
permissions: metadata.permissions || [],
};
}
const token = jwt.sign(payload, Config.get('auth0.clientSecret'), { expiresIn: '5m' });
requestInstance.header('authorization', `Bearer ${token}`);
});
};
|