Nodemailer, Heroku, Gmail, invalid login - works locally - javascript

I have been having this issue for the past couple of weeks, it works every time locally, however once I deploy it to my heroku server, it will give me an invalid login error. I have gone into the account and givin access to less secure apps. And the credentials are correct, and it works on localhost every time. Is there something I am missing?
quickSendMail: function(routeBody, callback) {
//configuring the nodemailer for email notifications
var smtpConfig = {
host: 'smtp.gmail.com',
port: 465,
secure: true, // use SSL
auth: {
user: 'mysmtpemail123',
pass: '******'
}
};
var mailOptions = {
from: 'SageStorm Site <mysmtpemail123#gmail.com>',
to: ['my email'],
subject: routeBody.subject,
html: 'my message'
};
var transporter = nodemailer.createTransport(smtpConfig);
transporter.verify(function(error, success) {
if (error) {
console.log(error);
} else {
console.log('server is ready to send emails');
}
})
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(error);
return callback(err, null);
} else {
console.log('Message sent: ' + info.response);
return callback(null, info);
}
})
}

You can allow machines to access your gmail remotely using this link, but keep in mind that Google will affect your default account (even if you are connected with another one).
The easy way: use a incognito / private window (to have no google account connected) and log in your google account and then use the link above.
If that doesn't work try updating your nodemailer to the latest version.

According to https://support.google.com/accounts/answer/6009563, Go to https://accounts.google.com/b/0/DisplayUnlockCaptcha and allow access and try again ..
Also according to docs at nodemailer (https://github.com/nodemailer/nodemailer#delivering-bulk-mail)
I'm having issues with Gmail Gmail either works well or it does not
work at all. It is probably easier to switch to an alternative service
instead of fixing issues with Gmail. If Gmail does not work for you
then don't use it.

I set a bounty to this question, but after looking through the Nodemailer docs/Github, it seems that using Gmail will only lead to headaches.
According to the Nodemailer docs...
"...Gmail expects the user to be an actual user not a robot so it runs a lot of heuristics for every login attempt and blocks anything that looks suspicious to defend the user from account hijacking attempts.
For example you might run into trouble if your server is in another geographical location – everything works in your dev machine but messages are blocked in production."
I believe the second thing was my issue; my Nodemailer ran without issue on my machine, but immediately failed when I pushed the app to Heroku.
As for a fix, my only fix was to use a different email provider. All email accounts I've tried using have been fully authorized to allow other sign-ins and less safe apps; I've gone through every method Google has to offer to allow usage of the account, and I fully believe that it's simply not possible to get consistent results with Nodemailer and Gmail.
Using Outlook/Hotmail worked for me. I also tried switching to a different Gmail account. It worked successfully a couple times, then returned to the previous state.

Most times when one ends up with this kinda error from Nodemailer, one of these options listed by Google gets to fix it, take your time to go through the google account to be used has the required setting.
Google has listed all the potential problems and fixes for us. In as much as you turned on less secure apps setting. Be sure you are applying these to the correct account.
Step 1: Check your password
If you have these problems or can’t sign in, first check to make sure you’re using the right password.
Step 2: Try these troubleshooting steps
If you've turned on 2-Step Verification for your account, you might need to enter an App password instead of your regular password.
Sign in to your account from the web version of Gmail at https://mail.google.com. Once you’re signed in, try signing in to the mail app again.
Visit Display Unlock Captcha and sign in with your Gmail username and password. If asked, enter the letters in the distorted picture.
Your app might not support the latest security standards. Try changing a few settings to allow less secure apps access to your account.
Make sure your mail app isn't set to check for new email too often. If your mail app checks for new messages more than once every 10 minutes, the app’s access to your account could be blocked.

Related

Google OAuth code flow, can't exchange code for token with error "redirect_uri_mismatch"

I'm implementing social login on my website.
I was able to implement the "One tap" flow, but I need to have an alternative to handle the "cooldown" which prevents the popup from appearing, if the user blocked it or closed it.
So I followed the "Authorization" flow on Google documentation.
Until yesterday morning everything was working fine and I succesfully exchanged the code with a token by calling
https://oauth2.googleapis.com/token
or
https://accounts.google.com/o/oauth2/token
sending secret and everything.
In a first instance I used Postman, then I made a sample code in a Spring project, before preparing the final code in another Spring project.
The first run in the final project I started getting a 400 error, with the redirect_uri_mismatch error key.
And then I was never able to do the exchange anymore, I get the same error from Postman as well.
The config is correct (It never changed from when it was working).
How can I solve this??
Here's some code
FRONTEND
this.client = google.accounts.oauth2.initCodeClient({
client_id: this.clientId,
scope: "openid profile email",
ux_mode: "popup",
redirect_uri: this.redirectUri,
callback: (response) => {
debugger;
this.submitFakeForm({
clientId: this.clientId,
code: response.code
});
}
});
this.client.requestCode();
POSTMAN PARAMS
this.redirectUri is identical to the one passed here and set up on Google credentials
FOR THE MOST SKEPTICAL, THE AUTHORIZED REDIRECTS :)
They're repeated in couples, because one is for local development, one is for the integration environment.
And of course the production config is on another credential.
Nowhere in the docs is this, but I came across this answer here on stackoverflow and it's basically suggesting not to pass the real redirect_uri, but to use a fixed string postmessage.
I want to point up again that I was using the real redirect_uri yesterday and it worked.
I will do some tests again in the future and update here if something changes.
For now just know that using postmessage fixed the issue for me
also I will be using https://oauth2.googleapis.com/token as endpoint, since it's the one mentioned in the (awful) docs, although https://accounts.google.com/o/oauth2/token works just as well.

NodeJs API login B2C without B2C login page

All right?
I am in need of help with Azure AD B2C implementation. I need an API that manages the login for my application and that makes a connection with AAD B2C. However, I only find login options through the B2C login page. I would like to know if there is any way to implement in Node a form of login in my application without having to use the MS login screen. User entering with password and email and validating in AD. I saw that there is ROPC, but at the same time saying that it is an insecure method.
I am currently implementing it with ms graph, azure-graph, ms-rest-azure, but I think this way is wrong.
User enter the email prefix and password via post.
server.post('/login', (request, response) => {
const {email, password} = request.body
msRestAzure.loginWithUsernamePassword(`${email}#<tenant-name>.onmicrosoft.com`, `${password}`, { tokenAudience: 'graph', domain: tenantId }, function (err, credentials, subscriptions) {
if (err) console.log(err);
console.log(credentials.tokenCache)
Update: few days ago, they announced the preview feature for iframe compatibility (i.e. embedded login):
https://learn.microsoft.com/en-us/azure/active-directory-b2c/embedded-login?pivots=b2c-custom-policy
of course, it's better if you don't use it in production yet, but it might be the solution you were looking for. :)
Old answer:
The only way to achieve that is by using ROPC, as you mentioned. ROPC is insecure basically because for some time you have to manage the credentials of the user (unlike when the user directly inserts them in B2C), but in your case, this is a requirement.
You cannot achieve this with Graph API, because you'll be only able to register the user, update his/her data (incl. password), but you won't be able to get an access token.

express-stormpath login not working for email-authenticated users

i have a basic node.js / Express server using express-stormpath for user authentication. everything works beautifully without email verification. obviously, email verification is desirable for many reasons, but my email-verified users are unable to use the standard login flow for restricted routes.
specific example on a custom route i have:
app.get('/myaccount', stormpath.loginRequired, function(req,
res.send('Your email address is: ' + req.user.email);});
this route works perfectly for users that registered before email verification.
however, it's broken for users that signed up after email verification. these users received an email, clicked the link, got the confirmation screen ("You account was successfully verified and is ready for use"), and are marked as 'Enabled' in my Stormpath dashboard.
specifically, if they enter the correct password, they are sent to http://glacial-hollows-8156.herokuapp.com/login?next=%2Fmyaccount again, which presents the login screen once more, ad infinitum. if they enter an incorrect password, they get the standard error telling them so
any ideas? perhaps email-verified accounts are not being initialized correctly? the behavior is also the same for Stormpath-provided routes like '/me', so i don't think its my route. as i turn email verification on and off, /myaccount keeps working for non email-verified users, and always breaks in this manner for the email-verified users
this was a config issue with 'Link Base URL' on the stormpath dashboard
it had defaulted to 'https://api.stormpath.com/emailVerificationTokens', which verifies users - although they can't actually log in
instead, change 'Link Base URL' to http://localhost:3000/verify
note that this link is totally out of date, despite being only 3 months old... https://stormpath.com/blog/how-to-add-billing-to-your-api/ do not bother trying to use /verified

NodeMailer Invalid Login

I am new to node.js programming .I am using nodemailer module for sending emails.
const nodemailer = require ('nodemailer'),
credentials=require('./credentials.js');
var mailTransport=nodemailer.createTransport({
service:'Gmail',
auth: {
user : credentials.gmail.user,
pass : credentials.gmail.password,
}
});
function sendMail(mail_id){
mailTransport.sendMail({
from: ' "my name" <myname#gmail.com>',
to : mail_id, //user#gmail.com
subject : 'Hello',
text: "Hello How do u do ?",
},function(err,info){
if(err){
console.log('Unable to send the mail :'+err.message);
}
else{
console.log('Message response : '+info.response);
}
});
}
exports.sendMail=sendMail;
This is my program for sending emails to different users. But I am getting Invalid Login . I don't have any idea why this is coming . I am new to node.js and server side scripting.
I am using my gmail username and password for credentials.
Please help me.
One reason could be the 'modern security standard' protection from Gmail.
Check you gmail inbox for any new mail having subject "Google Account: sign-in attempt blocked"
If yes, open the mail and click on the link https://www.google.com/settings/security/lesssecureapps
set 'Access for less secure apps' to 'Turn on'. Try again, it should be working now.
Particularly 2 issues: or you don't have enabled Less Secure Apps https://myaccount.google.com/lesssecureapps or you don't have enabled Display Unlock Captcha https://accounts.google.com/DisplayUnlockCaptcha, you need to turn on both of them.
U need to Enable Security for Apps :
|*| If u r using gmail,
Use :
service: 'gmail',
Goto :
https://myaccount.google.com/lesssecureapps
Enable :
Allow less secure apps: ON
|*| If u r using yahoo,
Use :
service: 'yahoo',
Goto :
https://login.yahoo.com/account/security
Enable :
Allow apps that use less secure sign in
|*| If u r using Live or Hotmail, No need to enable anything.
Use :
service: 'hotmail',
Did you double-check your login credentials? Also did you double-check your "from" adress to match your email?
I used the nodemailer for some tests 3 weeks ago with the gmail example given on the github page and it worked like a charm:
https://github.com/andris9/Nodemailer
Invalid login indicates mistyped/wrong credentials.
In my case,
turning on less secure apps only was not enough: https://myaccount.google.com/lesssecureapps
I had to enable display unlock captcha also: https://accounts.google.com/DisplayUnlockCaptcha
This solved my issue and i was able to send emails using nodemail and gmail.
This thing is not random actually nodemailer community site itself says to perform the second step to enable captcha, if turning on the less secure apps do not work alone.
https://community.nodemailer.com/using-gmail/
Above image is taken from the nodemailer article link i have shared.
Adding this as a separate answer, since the accepted answer no longer works.
Since May 30, 2022, Google no longer supports less secure apps. There is a nodemailer GitHub issue on this (https://github.com/nodemailer/nodemailer/issues/1424) with the updated steps:
Go to https://myaccount.google.com/security
Enable 2FA
Create App Password for Email
Copy that password (16 characters) into the pass parameter in Nodemailer auth.
...,
auth: {
user: 'yourmail#gmail.com',
pass: 'your_new_app_password',
},
...
if you have a workspace user account you may need to, as an admin:
Create a user group
Add the user to that group
Go to the user group settings and enable unsecure apps under Security so that other groups emails won't be affected
If that isn't enough (this worked for me after everything was fine for months with first three steps), go to myaccount.google.com and log in with the specific user email and password, go to Security again and turn on less secure apps.

Facebook Graph API won't return email address

Edit: Not Duplicate, because:
I have the permission
Debugged the token
Code works with test user
Please don't mark as duplicate without reading.
I'm trying to get the user e-mail address, but i don't get it. On graph api explorer, when i hit send, email field becomes grayed and says that:
field is empty or disallowed by access token
But when I debug the token it has email permission granted
My profile has an e-mail address.
Update: I tried https://developers.facebook.com/tools/console/ . My profile returns nothing, even on another computer. But the same code returns the email, name and uid of another account.
Code:
<fb:login-button scope="email">
Grant Permissions to make more examples work
</fb:login-button>
<button onclick="doPost()">Post to Stream</button>
<script>
function userData() {
FB.api('/me?fields=name,email', Log.info.bind('/me callback'));
};
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
userData();
}
});
</script>
It is possible to lockdown you e-mail so no one can has it? Even when i grant permission?
The Marcus' answer leads me to the real problem I was facing.
Debugging with the Facebook Explorer tool I was able to figure out that I should set the email scope at the FB.api() method after a successful login.
FB.login(function(response) {
if (response.status === 'connected'){
FB.api('/me?fields=id,email,name', function(data) {
console.log( data.email ) // it will not be null ;)
})
}, {scope: 'email'});
It is not quite clear at the Quickstart guide and I hope it helps someone else, too.
I had the same problem and I think I found out why:
If the user has an unconfirmed email in Facebook (i.e. Facebook sent him a validation mail to his email address but he didn't respond) Facebook WILL NOT pass that email to your app even if he gave you the email permissions (!!!).
So what I did is use his Facebook email if he has a user name (i.e. userName#facebook.com).
After i got my bug report marked as duplicate, and i read all posts and links there, i got what caused this problem for me and how to fix.
The Problem
Facebook seems to sometimes forget what your primary e-mail is on the graph API (But it still there in the preferences.)
Solution
The user affected must remove the e-mail, save settings, then re-add the address, re-confirm, then make it primary. This fixed my account both on my sandbox app, and other apps where Facebook login don't used to work.
New facebook graph requires scopes added in the /me request as follow:
/me?fields=email,birthday,location,locale,age_range,currency,first_name,last_name,name_format,gender&access_token=
I had the same issue while I was developing the fb login button for my site. I had even setup permissions for my app here:
https://developers.facebook.com/apps/<my-app-ID>/permissions
and it was working fine for certain initial cases, that is, it was giving email (i tested it on my own account and it was giving my email). Then suddenly it started to reflect no email at all. After two hours of browsing, I figured it out that there was an issue with the access token as when I went on this link:
https://developers.facebook.com/tools/explorer/<your-fb-id>/?method=GET&path=100002451127858%3Ffields%3Did%2Cemail
Update your-fb-id with your id and go to the above link. Click on 'Get Access Token'. In the tab that opens up, click on 'Extended Permissions' and in that, choose 'email' and submit. Now, test your query again. It'll definitely work, on the console as well as your website. Cheers! :)
This is a known bug. If the user does not have any email address set to primary, the query will return null for email. Set the email address for your account to primary https://www.facebook.com/settings?tab=account&section=email&view and then try.
Source: https://developers.facebook.com/bugs/298946933534016/

Categories

Resources