Skip to content

Instantly share code, notes, and snippets.

@eugeniop
Created September 25, 2014 14:59
Show Gist options
  • Save eugeniop/80f257dc616ae0e89888 to your computer and use it in GitHub Desktop.
Save eugeniop/80f257dc616ae0e89888 to your computer and use it in GitHub Desktop.
function login (email, password, callback) {
//1. Auth user.
var profile = {
user_id: "103547991597142817347",
nickname: "johnfoo",
email: email,
name: "John Foo",
given_name: "John",
family_name: "Foo"
};
//2. Auth is successful, create a user in Auth0
createAuth0UserIfNew(profile,password,function(e){
if(e) return callback(e);
return callback(null, profile);
});
function createAuth0UserIfNew(user,password,done){
getAuth0ApiToken(function(e,tok){
if(e) return done(e);
var token = tok.access_token;
console.log('Got token' + token);
userExists(user,'MyUsers',token,function(e,result){
if(e) return done(e);
if( result ) {
console.log('User exists');
return done();
}
console.log('User doesn\'t exist');
createUser(user,password,'MyUsers',token,function(e){
if(e) done(e);
return done();
});
});
});
}
function createUser(user,password, connection,token,done){
request({
uri: 'https://eugeniopace.auth0.com/api/users',
method: 'POST',
json: {
email: user.email,
password: password,
connection: connection,
email_verfied: false,
//Other properties
}
},
function(e,r,b){
if(e) return done(e);
if(r.statusCode !== 200 ) return done(new Error("Create User - Invalid response" + r.statusCode));
return done();
});
}
function userExists(user,connection,token,done){
request({
uri: 'https://eugeniopace.auth0.com/api/connections/'+ connection +'/users',
qs: {
search: 'email=' + user.email,
per_page: 1
},
headers: {
Authorization: 'Bearer ' + token
}
},
function(e,r,b){
if(e) return done(e);
var list = JSON.parse(b);
console.log('Users in connection');
console.log(list);
console.log(list.length);
console.log(typeof(list));
console.log(list.length);
if(list.length > 0 ) return done(null, true);
return done(null, false);
});
}
function getAuth0ApiToken(done){
request({
uri: 'https://eugeniopace.auth0.com/oauth/token',
method: 'POST',
json: {
"client_id": "F2IEucRJQ...7ZZ0byR8lR9",
"client_secret": "ZotF9ylurI1xZ_cQvlGfMUC...YOp3N6Chvz_KV9BY0jgQ_1mA",
"grant_type": "client_credentials"
}
},
function(e,r,b){
if(e) return done(e);
if(r.statusCode !== 200 ) return done(new Error("Invalid response" + r.statusCode));
done(null, b);
});
}
}
@bbrealnex
Copy link

Need to add . . .

,
headers: {
          Authorization: 'Bearer ' + token
}

. . . to request in createUser (before or after the json block). Otherwise that request will always fail.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment