How to get a username from response object using Auth0 Lock? - javascript

The question is how to get username, which I used to login, back from response object?
I'm creating the Auth0Lock instance by following code:
this._lock = new Auth0Lock(AUTH_CONFIG.clientId, AUTH_CONFIG.domain, AUTH_CONFIG.options);
and then I subscribe on "authenticated" event:
this._lock.on('authenticated', authResult => {
this._lock.getUserInfo(authResult.accessToken, function(error, profile) {
console.log('profile', profile); // --> undefined
if (error) {
// Handle error
}
});
})
I'm logging in by following credentials:
username: john#gmail.com password: 123456
I want to be able to see 'username: john#gmail.com' somewhere in authResult object.
But unfortunately I don't see.
Should I add something in Auth0lock options?
P.S. I've added following code inside the handler of "authenticated" event, but it returns undefined for profile.

I've just added scope: 'openid' into "auth" property of options
options: {
...
auth: {
...
scope: 'openid' <---
}
}

Related

React Admin parseResponse doesn't trigger when query returns error

I'm using React Admin and ra-data-graphQl, when I update something in my UserEdit component all works perfect, BUT, when I need to handle the error message from the API, I don't know where catch it.
This is my Update query:
case 'UPDATE': {
const updateParams = { ...params };
return {
query: gql`mutation updateUser($id: ID!, $data: UpdateUser!) {
data: updateUser(id: $id,input:$data) {
${buildFieldsGraphQL(updateFields)}
}
}`,
variables: {
...updateParams,
id: updateParams.data.uuid,
data: {
...updateParams.data,
},
},
parseResponse: (response) => {
console.log('tr response: ', response);
},
};
}
When the API returns an error, it never reach the console.log.
I was searching a list with options here (https://github.com/marmelab/react-admin/tree/master/packages/ra-data-graphql#options) searching something like "parseError", but I did not find nothing similar.
I need to catch the error and show a message in the UserEdit form.
Reading the link that I share in this post, it say this:
but must return an object matching the options of the ApolloClient query method with an additional parseResponse function.
I understand that I should go to the link in the word "query" and check if there is something like "parserError", but the link is broken:
https://www.apollographql.com/docs/react/reference/index.html#ApolloClient.query
Any help?
Ok, its easier. By adding the onFailure function I can handle the error.

ScopeKey doesn't work in nuxt.js auth module

Recently i started to learn how to use Nuxtjs and while learning how to use its Auth module i came across a problem.
I'm able to log in and I want to check the scope of the accounts, i tried doing it using the "scopeKey" property of "Auth". From the back end i get the "scope" from the databse and it can either be "user" or "admin".
I have tried to set the scope with
scopeKey: 'scope'
But I get that scope is "undefined"/"null" when checking with
this.$auth.hasScope('admin') / this.$auth.hasScope('user')
or "this.$auth.hasScope(admin)" return an empty value when setting "scopeKey" to
scopeKey: 'data.scope'
or
scopeKey: 'user.scope'
Here is my auth strategy:
auth: {
strategies: {
local: {
scopeKey: 'scope',
endpoints: {
login: {
url: 'api/auth/login',
method: 'post',
propertyName: 'token',
},
logout: {
url: 'api/auth/logout',
method: 'get'
},
user: {
url: 'api/me',
method: 'get',
propertyName: data
}
}
}
},
redirect: {
login: '/auth/login',
logout: '/',
callback: '/auth/login',
home: '/dash/'
}
}
and here it is an example of the json that the auth module reads when i log in:
"data": {
"id": 2,
"name": "test1",
"email": "test#test.com",
"email_verified_at": null,
"scope": "admin",
"created_at": "2019-08-01 13:11:49",
"updated_at": "2019-08-01 13:11:49"
},
I can access the scope value on the front end page with
$auth.user.scope
or with
$auth.$state.user.scope
But how can I give the "scope" to the "scopeKey" property in the nuxt.config.js file while setting the "auth" properties/strategy?
edit:
I have tried moving it inside the auth object or deleting the property and I still get false on $auth.hasScope('admin') and $auth.hasScope('user') which means scopeKey is still undefined and i'm not sure why.
The scopeKey is 'scope' by default. You don't need to set it again.
For me it worked by doing server side change.
When I put string value in scope, it does not work
$data['scope'] = "admin";
But when I changed it to array, $auth.hasScope('admin') works;
$data['scope'] = array("admin", "test");
Hope it helps.
scopeKey: 'scope' should not be placed inside strategies object.
Put it directly in the auth object.
Take a look at default config.
P.S. You can even delete this property from your auth config object, because 'scope' is default value for scopeKey.
Somehow hasScope() is not working for me too, so I directly checked the user object, I also has token in my response.
I am having a type variable in my response that tells me if the user is admin or someone else.
add this into your middleware
export default function ({ $auth, redirect }) {
if (!$auth.loggedIn) {
return redirect('/')
}
if ($auth.user.type != 'Super Admin') { // Super Admin or whatever the user you want to check
return redirect('/')
}
}

Parse-server social login

I am developing application based on Parse-server and I want to offer social login. I found this guide in the documentation http://docs.parseplatform.org/js/guide/#linking-users.
I started to implement the social login by google. I did following steps:
1) I added following lines to the ParseServer settings
var api = new ParseServer({
...
auth:{
google: {}
},
...
});
2) I did the authentication by hello.js on the client side (call user._linkWith function on login)
hello.init({
google: 'My Google id'
});
hello.on('auth.login', function(auth) {
// Call user information, for the given network
hello(auth.network).api('me').then(function(r) {
const user = new Parse.User();
user._linkWith(auth.network, auth.authResponse).then(function(user){
console.log('You are logged in successfully.');
});
});
});
When I debugged it, I found that it fails in _linkWith() function, when provider object is preparing. Object AuthProviders, which should store all providers, is empty. Because of it the statement provider = authProviders['google']; leads to undefined. Invoking provider.authenticate(...); leads to error "Cannot read property 'authenticate' of undefined"
What am I missing or what am I doing wrong?
Thanks for all your answers.
Honza
Did you register the authenticationProvider? You can find examples in our unit tests on how to do so:
https://github.com/parse-community/parse-server/blob/5813fd0bf8350a97d529e5e608e7620b2b65fd0c/spec/AuthenticationAdapters.spec.js#L139
I also got this error and looked at the _linkWith(provider, options) source code. It checks if options has an authData field (which in turn should contain id and credentials). If so, it uses options.authData. Otherwise it falls back on looking up a previously registered authentication provider mentioned in the previous answer.
This is a fragment of the code I'm using:
const authData = {
"id": profile.getId(),
"id_token": id_token
}
const options = {
"authData": authData
}
const user = new Parse.User();
user._linkWith('google', options).then(function(user) {
console.log('Successful user._linkWith(). returned user=' + JSON.stringify(user))
}, function(error) {
console.log('Error linking/creating user: ' + error)
alert('Error linking/creating user: ' + error)
// TODO handle error
})

Authentication strategy simple uses unknown scheme: bearer-access-token

I am using hapi-auth-bearer-token plugin for my api authentication using hapijs.
here is my code:
apiServer.register(require('hapi-auth-bearer-token'), function (err) {
server.auth.strategy('simple', 'bearer-access-token', {
allowQueryToken: true, // optional, true by default
allowMultipleHeaders: false, // optional, false by default
accessTokenName: 'access_token', // optional, 'access_token' by default
validateFunc: function( token, callback ) {
// For convenience, the request object can be accessed
// from `this` within validateFunc.
var request = this;
// Use a real strategy here,
// comparing with a token from your database for example
if(token === "1234"){
//## user object to be looked up here
callback(null, true, { token: token })
} else {
callback(null, false, { token: token })
}
}
});
});
here is the error i am getting:
Error: Authentication strategy simple uses unknown scheme: bearer-access-token
at Object.exports.assert (/Users/jamshidnafisi/Documents/srvs-node/node_modules/hapi/node_modules/hoek/lib/index.js:723:11)
at internals.Auth.strategy (/Users/jamshidnafisi/Documents/srvs-node/node_modules/hapi/lib/auth.js:44:10)
at internals.Plugin._applyChild (/Users/jamshidnafisi/Documents/srvs-node/node_modules/hapi/lib/plugin.js:471:19)
at Object.auth.strategy (/Users/jamshidnafisi/Documents/srvs-node/node_modules/hapi/lib/plugin.js:69:18)
at /Users/jamshidnafisi/Documents/srvs-node/index.js:78:17
at done (/Users/jamshidnafisi/Documents/srvs-node/node_modules/hapi/node_modules/items/lib/index.js:30:25)
at Object.exports.register (/Users/jamshidnafisi/Documents/srvs-node/node_modules/hapi-auth-bearer-token/lib/index.js:73:5)
at /Users/jamshidnafisi/Documents/srvs-node/node_modules/hapi/lib/plugin.js:254:14
at iterate (/Users/jamshidnafisi/Documents/srvs-node/node_modules/hapi/node_modules/items/lib/index.js:35:13)
at Object.exports.serial (/Users/jamshidnafisi/Documents/srvs-node/node_modules/hapi/node_modules/items/lib/index.js:38:9)
at internals.Plugin.register (/Users/jamshidnafisi/Documents/srvs-node/node_modules/hapi/lib/plugin.js:236:11)
at Object.<anonymous> (/Users/jamshidnafisi/Documents/srvs-node/index.js:76:11)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
the message is plain english but i dont understand what i have to add to my code to solve the issue.
It looks like you're registering the hapi-auth-bearer-token plugin on one server (apiServer) then setting the auth strategy on another (server)
Try
apiServer.register(require('hapi-auth-bearer-token'), function (err) {
apiServer.auth.strategy('simple', 'bearer-access-token', {
allowQueryToken: true, // optional, true by default
allowMultipleHeaders: false, // optional, false by default
accessTokenName: 'access_token', // optional, 'access_token' by default
validateFunc: function( token, callback ) {
// For convenience, the request object can be accessed
// from `this` within validateFunc.
var request = this;
// Use a real strategy here,
// comparing with a token from your database for example
if(token === "1234"){
//## user object to be looked up here
callback(null, true, { token: token })
} else {
callback(null, false, { token: token })
}
}
});
});

Template.meteorError.rendered doesn't work in errors meteor package

I am trying to use meteor-errors package in my meteor project.
It has two main files with javascript code:
errors_list.js:
Template.meteorErrors.helpers({
errors: function() {
return Errors.collection.find();
}
});
Template.meteorError.rendered = function() {
var error = this.data;
Meteor.defer(function() {
Errors.collection.update(error._id, {$set: {seen: true}});
});
};
errors.js:
Errors = {
// Local (client-only) collection
collection: new Meteor.Collection(null),
throw: function(message) {
Errors.collection.insert({message: message, seen: false})
},
clearSeen: function() {
Errors.collection.remove({seen: true});
}
};
But looks like Template.meteorError.rendered method doesn't work. And I can't set status of elements from my error's collection as seen: true.
When I call for example:
(server)
throw new Meteor.Error 401, "You need to login to add a new address"
(client)
Meteor.call "verify_address", address, name, (error, result) ->
if error
Errors.throw error.reason
I got this error message in my markup, but my browser console shows:
Errors.collection.find().fetch()
[Object]
_id: "MZ8TzpsKCXaeC33Jn"
message: "Address not the correct size"
seen: false
__proto__: Object
And message's seen attribute is still "false".
The initial problem was that an error has a 'X' icon that does not remove the error when clicked. How are we supposed to remove the errors?
The reason for the strange behavior is, you are manually throwing a Meteor.Error whereas your template is bound to a collection which is populated by calling Errors.throw(message)
Try this:
Errors.throw('You need to login to add a new address');

Categories

Resources