How do I just get an email address after authenticating with oAuth2? - google-api-nodejs-client - google-api-nodejs-client

I am trying to just get an email address after authenticating with oAuth2. After I get a code when I validate with a google account, I go and get the user from Google Plus, like this:
let oAuth2Client = new auth.OAuth2(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GOOGLE_CLIENT_CALLBACK);
const tokens = await getToken(oAuth2Client, code);
oAuth2Client.setCredentials(tokens);
plus('v1').people.get({ userId: 'me', auth: oAuth2Client }, function(err, response) {
.... This repsonse is the full user object from Google Plus
});
How do I just get the email address, or a list of email addresses? I don't want all the other Google Plus info. I have already set my scope to email, but I still get lots of other information. I am assuming that I need to make a request to something other than plus, but I can't find what to do in the documentation.

If you have set email scope (https://www.googleapis.com/auth/userinfo.email), you can use oauth2("v2").userinfo.v2.me.get :
var google = require('googleapis');
....
google.oauth2("v2").userinfo.v2.me.get({
auth: oAuth2Client
}, function(e, profile) {
if ("email" in profile) {
console.log(profile.email);
} else {
console.log("scope email not set");
}
});

Related

Application creates classroom invitation, but no email is being sent to student

After creating a classroom invitation the method classroom.create returns with the return status 200 but the user never receives email with the invitation message.
I have given the the client id associated with the service account that I am using, the scopes classroom.roster and mail.google.com, but nothing seems to work.
Am I missing something?
Thank you very much,
Andres
This is the fragment of code that creates the invitation:
//get authorization client
const auth = await google.auth.getClient({
scopes
});
//impersonate teacher account
if (auth instanceof google.auth.JWT) {
auth.subject = 'teacher_email#dom.edu';
}
const options = { auth,
requestBody: {
courseId: '19220887720',
role: 'STUDENT',
userId: 'student_email#dom.edu'
}
};
//send invitation
try {
const invitation = await classroom.invitations.create(options);
console.log('invitation was sent:', invitation);
} catch (err) {
console.error('error: ' , err);
}
Response: status 200.
The invitation is really created. Response includes an invitation id and If you check on the ClassRoom home page->people you can see the correct student was invited.
Based from this forum, students need to have the same settings on in their account, which they may not by default. They should also choose to be a student first.
Also, notification e-mails of Google Classroom are sent from classroom.google.com domain. See Email notifications - Classroom Help for further details.

Expo Facebook Login- Producing Invalid Tokens

I followed the docs to use the Facebook Login SDK. Everything works except for the fact that the token that is generated does not work for our API. Our API takes the user-generated token as a header so that it can make requests. I know the reason why it isn't working is that I am logging in with Facebook, but there is no account created on our API. Facebook will not give me access to a user's password (for obvious reasons), so I can't generate an account from the information provided from Facebook.
I think the answer lies with App Access Tokens. If someone could help me out I would really appreciate it!
code:
export const logInFB = () => async dispatch => {
const { type, token } = await Expo.Facebook.logInWithReadPermissionsAsync('**Blocking this out**', {
permissions: ['public_profile'],
});
console.log('token');
console.log(token);
if (type === 'success') {
// Get the user's name using Facebook's Graph API
const response = await fetch(
`https://graph.facebook.com/me?access_token=${token}`);
console.log('fb token')
console.log(response);
dispatch(fbLoginToken(token));
Alert.alert(
'Logged in!',
`Hi ${(await response.json()).name}!`,
);
}
}
Looks like you are missing the fields property in the URL. ex: &fields=id,name,email,about,picture
Please refer to this example: https://snack.expo.io/#bacon/facebook
const response = await fetch(
`https://graph.facebook.com/me?access_token=${token}&fields=id,name,email,about,picture`
);
const responseJSON = JSON.stringify(await response.json());
this.setState({ responseJSON });

How to get the Authentication Provider for actions-on-google on Node using account linking with Auth0?

I have Javascript App running under Node v8.11.2 which uses the Actions-On-Google library. I'm using the V2 API. I have account linking set up with Auth0 and am using the SignIn helper intent. Auth0 is set up to use Google, Facebook and Twitter.
The scopes I use are OPENID, OFFLINE_ACCESS, PROFILE and EMAIL.
Everything is working fine and when the User is authenticated I get an Access Token returned.
My question is, how do I get the Authentication Provider that was selected by the User so that I can use the Access Token correctly to retrieve profile elements such as the display name, email address etc??
The signin object passed to the Sign In Confirmation intent handler just contains the following regardless of the provider selected: -
{"#type":"type.googleapis.com/google.actions.v2.SignInValue","status":"OK"}
Any help greatly appreciated as I have a deadline and this is driving me a bit crazy now!
Thanks,
Shaun
If your question is about how to get the required information when you have your accessToken available then you could use what is shown in this answer.
In node this looks like that:
let link = "https://www.googleapis.com/oauth2/v1/userinfo?access_token="+accessToken;
return new Promise(resolve => {
request(link,(error, response, body) => {
if (!error && response.statusCode === 200) {
let data = JSON.parse(body);
let name = data.given_name ? data.given_name : '';
conv.ask(new SimpleResponse({
speech: "Hello "+ name + "!",
text: "Hello "+ name + "!"
}));
resolve();
} else {
console.log("Error in request promise: "+error);
resolve();
}
})
})
Everything you need should be in the data object.
Hope it helps.

how to update an subscription without id in mail chimp rest api

I really like the new Mail Chimp REST API - it is easy to create subscriptions by PUT and those can be updated using the subscription id.
But I would like to update a subscription simply using the email address, because I do not want to save any new Mail Chimp Id in my Middle-ware application, as long as the email should be sufficient as identifier?
To update a List Member the API is:
/lists/{list_id}/members/{id}
but I would prefer a simpler way:
/lists/{list_id}/members/{email}
is something like this possible?
The subscriber's ID is the MD5 hash of their email address. Since you would have to make a function call to URL Encode the email address for your second way, using the first way is just as easy.
See this help document on managing subscribers for more details.
More specifics on updating a subscriber via MailChimp's REST API.
// node/javascript specific, but pretty basic PUT request to MailChimp API endpoint
// dependencies (npm)
var request = require('request'),
url = require('url'),
crypto = require('crypto');
// variables
var datacenter = "yourMailChimpDatacenter", // something like 'us11' (after '-' in api key)
listId = "yourMailChimpListId",
email = "subscriberEmailAddress",
apiKey = "yourMailChimpApiKey";
// mailchimp options
var options = {
url: url.parse('https://'+datacenter+'.api.mailchimp.com/3.0/lists/'+listId+'/members/'+crypto.createHash('md5').update(email).digest('hex')),
headers: {
'Authorization': 'authId '+apiKey // any string works for auth id
},
json: true,
body: {
email_address: email,
status_if_new: 'pending', // pending if new subscriber -> sends 'confirm your subscription' email
status: 'subscribed',
merge_fields: {
FNAME: "subscriberFirstName",
LNAME: "subscriberLastName"
},
interests: {
MailChimpListGroupId: true // if you're using groups within your list
}
}
};
// perform update
request.put(options, function(err, response, body) {
if (err) {
// handle error
} else {
console.log('subscriber added to mailchimp list');
}
});

verify email using accounts.ui package

I want to send a verification email when some user is created. I use the accounts-password package, so any Accounts methods are called in my code.
I read in documentation that I need to call:
Accounts.sendVerificationEmail(userId, [email])
but the problem is that I don't know when to call it.
I tried to call in the callback function of Accounts.onCreateUser(func) but the user had not been created yet in the database.
Any ideas?
on the serverside:
Accounts.config({sendVerificationEmail: true, forbidClientAccountCreation: false});
got the answer from the comments above.
sendVerificationEmail is only available server-side. What I usually do is to use a setInterval inside onCreateUser to wait for Meteor to create the user before sending an email.
Read More: Verify an Email with Meteor Accounts.
// (server-side)
Accounts.onCreateUser(function(options, user) {
user.profile = {};
// we wait for Meteor to create the user before sending an email
Meteor.setTimeout(function() {
Accounts.sendVerificationEmail(user._id);
}, 2 * 1000);
return user;
});
You need specify mail in enviroment variables.
Then use Accounts.sendVerificationEmail(userId, [email]) in callback of Account.onCreateUser sorry for mistake and delay.
Like this (below is full example js file):
Template.register.events({
'submit #register-form' : function(e, t) {
e.preventDefault();
var email = t.find('#account-email').value
, password = t.find('#account-password').value;
// Trim and validate the input
Accounts.onCreateUser({email: email, password : password}, function(err){
if (err) {
// Inform the user that account creation failed
} else {
// Success. Account has been created and the user
// has logged in successfully.
Accounts.sendVerificationEmail(this.userId, email);
}
});
return false;
} });
if(Meteor.isServer){
Meteor.startup(function(){
process.env.MAIL_URL='smtp://your_mail:your_password#host:port'
}
}
I refered to this pages :
http://blog.benmcmahen.com/post/41741539120/building-a-customized-accounts-ui-for-meteor
http://sendgrid.com/blog/send-email-meteor-sendgrid/
How come my Meteor app with accounts package is not sending a verification email?