Skip to content

Instantly share code, notes, and snippets.

@giautm
Forked from theevangelista/feathersjs-auth0.js
Created March 7, 2017 06:19
Show Gist options
  • Save giautm/0ffa2654c883cf3cba1a8ab5e1e298c0 to your computer and use it in GitHub Desktop.
Save giautm/0ffa2654c883cf3cba1a8ab5e1e298c0 to your computer and use it in GitHub Desktop.
A hook to populate an user from Auth0 into feathersjs
const request = require('request-promise');
const errors = require('feathers-errors');
const options = {
idField: 'sub',
issuer: 'iss'
};
module.exports = function() {
return function(hook) {
if (hook.type !== 'before') {
throw new Error(`The 'auth0' hook should only be used as a 'before' hook.`);
}
let id; // the sub of the payload
let issuer; //the guy who issued we will get it to query user info
const payload = hook.params.payload
const token = hook.params.token;
if (payload[options.idField]) {
id = payload[options.idField];
console.log(`User ${id} issued`);
}
if (payload[options.issuer]) {
issuer = payload[options.issuer];
console.log(issuer)
}
return new Promise(function(resolve, reject) {
//there is an Id query auth0 for user info
if (id && issuer) {
return request({
method: 'POST',
uri: `${issuer}tokeninfo`,
json: true,
headers: {
'Content-Type': 'application/json',
},
body: {
'id_token': `${token}`
}
})
.then(json => {
hook.params.user = json;
resolve(hook)
})
.catch(err => reject(errors.NotAuthenticated('You are not authenticated', err)))
} else {
return reject(errors.NotAuthenticated('You are not authenticated'));
}
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment