Auth0 Add Custom Claims to User Profile - javascript

I want Auth0 to send some additional info in the user profile. So I created the following rule:
function (user, context, callback) {
user.app_metadata = user.app_metadata || {};
user.app_metadata.test = "some info here";
auth0.users.updateAppMetadata(user.user_id, user.app_metadata)
.then(function() {
context.idToken['https://example.com/test'] = user.app_metadata.test;
callback(null, user, context);
})
.catch(function(err) {
callback(err);
});
}
However, instead of receiving this (which I expected):
{
user_metadata: {
test: "some customer id"
}
nickname: "afaafa11fdf"
name: "afaafa11fdf#bob.com"
}
I receive this:
{
https://example.com/test: "some customer id"
nickname: "afaafa11fdf"
name: "afaafa11fdf#bob.com"
}
I have been following these guidelines here.

I contacted Auth0 and apparently that's the desired behaviour. I expected the wrong result, but what I describe above and did in fact receive is correct. So for anyone with this question, you will in the end receive something along these lines:
{
https://example.com/test: "some customer id"
nickname: "afaafa11fdf"
name: "afaafa11fdf#bob.com"
}

Related

Can a Firebase error message template or Alert be customised to show custom Alerts?

I am working on a React App. The app has basic auth features. Here is the code below.
export async function registration(email, password, firstName, phone) {
try {
await firebase.auth().createUserWithEmailAndPassword(email, password);
const currentUser = firebase.auth().currentUser;
const db = firebase.firestore();
db.collection("users").doc(currentUser.uid).set({
email: currentUser.email,
firstName: firstName,
phone: phone,
password: password,
});
} catch (err) {
Alert.alert("Please Use Another Email ID", err.message);
}
}
The issue here is that i am trying to create a custom alert for a specific error that is "The Email ID Already Exists". But Firebase has its own predefined error template defined for it.
And when I replace with a custom code mentioned below,
Alert.alert("Please Use Another Email ID", "This email ID already exists. If issue persists, contact support", [
{
text: "Ok",
onPress: () => null,
style: "cancel",
},
{
text: "Contact Support",
onPress: () => Linking.openURL('mailto: example#email.com'),
},
]);
return true;
}
it works, but shows the same alert for every error present.
Somone. help. I am relatively new to React and JS.
Write a custom function that takes in the auth error and displays an Alert accordingly:
export function processAuthError(authError: string) {
if(authError.includes('user-not-found')) {
Alert.alert('User not found', 'You probably have to sign up first.')
} else if(authError.includes('wrong-password')) {
Alert.alert('Wrong password', 'Try again.')
} else if(authError.includes('email-already-in-use')) {
Alert.alert("Please Use Another Email ID", "This email ID already exists. If issue persists, contact support", [
{
text: "Ok",
onPress: () => null,
style: "cancel",
},
{
text: "Contact Support",
onPress: () => Linking.openURL('mailto: example#email.com'),
},
]);
} else if(authError.includes('network-request-failed')) {
Alert.alert('Network error', 'Try again later or check your internet connection.')
} else {
Alert.alert('Unknown Error', 'Try again later.')
}
}
This should actually work pretty much out of the box since I am using it in my own code with Firebase just slightly different. I just return a custom string and then display the Alert with it but since you wan't custom Alerts this is the better way.

Updating Stripe accounts returns "Error: Stripe: "id" must be a string, but got: object"

I am trying to update a Stripe account to add an external account token to be charged later as shown in the example here.
var stripe = require("stripe")("sk_test_xxxxxxxxxxxxx"),
knex = require("knex")(config);
router.post("/paymentcardinfo",middleware.isLoggedIn,function(req,res){
knex("users.stripe").select("stripe_id_key")
.then((stripeID) => {
stripeID = stripeID[0].stripe_id_key;
console.log("My Stripe ID: "stripeID);
console.log("stripeID var type:", typeof stripeID);
stripe.accounts.update({
stripeID,
external_account: req.body.stripeToken,
}, function(err,acct) {
if(err){
console.log(err);
} else {
console.log("SUCCESS ********",acct);
// asynchronously called
}})
})
.catch((e) => {
console.log(e);
res.redirect("/paymentcardinfo")
});
});
Which returns the following
My Stripe ID: acct_xxxxxxxxxxxxx
stripeID var type: string
[Error: Stripe: "id" must be a string, but got: object (on API request to `POST /accounts/{id}`)]
where acct_xxxxxxxxxxx is the user's stored account ID. Based on the first console.log value, it would appear that stripeID is a string and not an object, which makes me unsure of how to proceed with this error.
Although the documentation specifies
stripe.accounts.update({
{CONNECTED_STRIPE_ACCOUNT_ID},
metadata: {internal_id: 42},
}).then(function(acct) {
// asynchronously called
});`
The following worked for me
stripe.accounts.update(
CONNECTED_STRIPE_ACCOUNT_ID,
{
metadata: {internal_id:42},
}
).then((account) => {
// response to successful action

"Error no label add or removes specified" when trying to modify labels using Gmail's Node.js API

I'm trying to modify the labels of emails in my inbox using gmail's Node.js API. My function to mark an email as read and star it is:
function markAsRead(auth, req, res)
{
var gmail = google.gmail('v1');
console.log(req.body.id);
gmail.users.messages.modify({
auth: auth,
id: req.body.id,
userId: 'me',
resouce:
{
"addLabelIds": [
"STARRED"
],
"removeLabelIds": [
"UNREAD"
]
}
}, function(err, response) {
if (err)
{
console.log('...The API returned an error: ' + err);
return;
}
console.log("Success???");
});
}
It gives an error saying No label add or removes specified. I've checked the email objects coming in and in their labelIds attributes "UNREAD" and "STARRED" appear so they're valid labelIds.
I seem to be doing what the docs for the API say is correct but it keeps giving that same error.
It looks good. I think it's just a typo. resouce should be resource.

Meteor.loginWithFacebook not storing email address

I'm using
accounts-password
accounts-facebook
service-configuration
On the server:
ServiceConfiguration.configurations.remove({
service: 'facebook'
});
ServiceConfiguration.configurations.upsert(
{ service: 'facebook' },
{ $set: {
appId: 'xxxxxxxxxxxxxxxx',
secret: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
}
}
);
On the client:
Meteor.loginWithFacebook({requestPermissions: ['email']}, function(error){
if (error) {
throwError('Could not log in');
} else {
// success
}
});
This configuration prompts the user for Facebook verification with access to email and returns no errors. A new user is stores with the correct name and ID. But this e-mail is not stored in the user object.
This is what I get when i fetch a user from the shell.
{ _id: 'xxxxxxxxxxxxxxxxx',
createdAt: Mon Jul 13 2015 13:36:21 GMT+0200 (CEST),
services:
{ facebook:
{ accessToken: 'xxxxxxxxxxxxxxxxxxxxx...',
expiresAt: 1441971380621,
id: 'xxxxxxxxxxxxxxxxx',
name: 'xxxx xxxxxx' },
resume: { loginTokens: [Object] } },
profile: { name: 'xxxx xxxxxx' } }
Why is the email address from Facebook not being stored?
While I have reported the issue to Meteor I've found a quick fix for the time being.
On the server run this:
Accounts.onCreateUser(function(options, user) {
if (user.hasOwnProperty('services') && user.services.hasOwnProperty('facebook') ) {
var fb = user.services.facebook;
var result = Meteor.http.get('https://graph.facebook.com/v2.4/' + fb.id + '?access_token=' + fb.accessToken + '&fields=name,email');
if (!result.error) {
_.extend(user, {
"emails": [{"address": result.data.email, "verified": false}],
"profile": {"name": result.data.name}
});
}
}
return user;
});
[EDIT]
The previous code works, but since it causes problems with other login methods I went with another approach:
In the client I call a function on the server when the user authenticates with Facebook:
Meteor.loginWithFacebook({requestPermissions: ['email']}, function(error){
if (error) {
//error
} else {
Meteor.call('fbAddEmail');
}
});
And then on the server:
Meteor.startup(function () {
Meteor.methods({
fbAddEmail: function() {
var user = Meteor.user();
if (user.hasOwnProperty('services') && user.services.hasOwnProperty('facebook') ) {
var fb = user.services.facebook;
var result = Meteor.http.get('https://graph.facebook.com/v2.4/' + fb.id + '?access_token=' + fb.accessToken + '&fields=name,email');
if (!result.error) {
Meteor.users.update({_id: user._id}, {
$addToSet: { "emails": {
'address': result.data.email,
'verified': false
}}
});
}
}
}
});
});
Facebook API may not return the email address for some users even if you asked for the "email" permission. The official API docs state that:
[email] field will not be returned if no valid email address is available.
One of the reason may be an unconfirmed email address and another one a user who registered with a mobile phone number only.

accessing github user data in meteor oauth

I am trying to authenticate a user with github, then pass their avatar_url to the client. Simplified structure looks as follows.
server/
publications.js
client/
users/
login.js
main.js
In my client/users/login.js file, I try to get the permission to the user Object which contains the avatar url
Accounts.ui.config({
requestPermissions: {
github: ['user']
}
});
Then in my server/publications.js, I try to publish the data related to the avatar url.
Meteor.publish('userData', function() {
if(this.userId) {
return Meteor.users.find(
{ _id: this.userId }, {
fields: {
'services.github.id': 1,
'services.github.user.avatar_url': 1
}
})
} else {
this.ready();
}
});
However I never get the data related to the github user when I get my user object. How can I get access to the user with OAuth?
Please have a look at this sample code, do you capture the Github profile data onCreateUser?
EDIT: this is server side code, e.g. server/accounts.js
Accounts.onCreateUser(function (options, user) {
var accessToken = user.services.github.accessToken,
result,
profile;
result = Meteor.http.get("https://api.github.com/user", {
params: {
access_token: accessToken
}
});
if (result.error)
throw result.error;
profile = _.pick(result.data,
"login",
"name",
"avatar_url",
"url",
"company",
"blog",
"location",
"email",
"bio",
"html_url");
user.profile = profile;
return user;
});
Code found here

Categories