Login function : Error [ERR_HTTP_HEADERS_SENT] - javascript

enter image description here
I'm trying to login as a user on my website and it's giving me this error, I can register the user and search for it in the login as many times as I want if the password and username are correct, however when there is an error in the user name or password it happens this in postman and even putting the right password and username it does not show the information and stays like this. Only returning to normal when I restart the server.
enter image description here
I'm a beginner and I'm learning, so I don't know what's wrong, thank you in advance for your attention.

The error generally means that you can not send HTTP headers multiple times.
It occurs when username does not match because in line 24 you send status(401) but then code flow continues, trying to send another status() later.
It occurs when password does not match because in line 32 you send status(401), code flow continues and then in the next line (34) you try to send status(201). The last call might send you to the exception handler (catch ..) in which you also try to send another status(500)
to avoid this, you might try:
if (!user) {
return res.status(401).json('wrong credentials');
}
//... get password hash from DB...
if (password !== req.body.password) {
return res.status(401).json('wrong credentials');
}
return res.status(201).json(user);
Important sidenote:You should NEVER encrypt/decrypt passwords.
Store password hashes instead and only ever compare hashes. Use bcrypt!

Related

Why is my code sending the prompts to my phone, but not to anyone else who attempts to send a message to the bot?

When I send a message to the Twilio phone number from my phone, it displays the questions that I want the user to see. However, if someone else sends a message no prompts are shown to the user. This is stored in a database. At first, I thought it was because the number sending a message was not getting stored as phoneNumber, but after checking in the database it is stored as phoneNumber.
I already tried adding a Status Callback function to the code but it doesn't say anything about the status of the message.
if(body === 'x'){ //checks body to have a key phrase, it it does it creates the message
let newMessage = new Message();
newMessage.phoneNumber = from;
newMessage.save(() => {
client.messages.create({ //sends message to the patient
to: `${from}`,
from: `${to}`,
body: 'What is your full name?'
})
.then(message => console.log(message.sid));
res.end();
})
}
The expected output would be the prompt of full name if someone sends a message to the Twilio number. However, it doesn't display anything.
Twilio developer evangelist here.
I can think of a couple of reasons that might be affecting you here.
First up, if you are still using a trial account then you can only send SMS messages to numbers that you have verified with your account. There are instructions for how to verify numbers with your Twilio account here. You can remove this restriction by upgrading your account.
Secondly, depending on the platform you are using, there may be a race condition between sending the message and the response ending. You call client.messages.create and handle the promise when it resolves, but your code goes straight on to end the response synchronously. It is the case with Twilio Functions and it may be on other platforms, that ending the response ends all processing and that might result in the request to send a message getting cancelled. You say you are getting messages when you try from your phone, so this may not be the issue, I just thought I'd share in case.
Let me know if that helps at all.

cognitoUser.signOut() is not signing user out

I am using Cognito User Pools, currently in their Beta stage, to handle my user accounts on my website.
In javascript i have the line:
cognitoUser.signOut();
Which should sign my user out, and I think set cognitoUser to null. After the above line I have the following code:
if (cognitoUser != null) {
alert(cognitoUser.getUsername());
}
Much to my annoyance, this line is working, and popping up an alert with the should be signed out user's user name.
Why is the cognitoUser.signOut() line not working?? Do I have to sign the user out on the same page I signed them in on or something?
Thanks
cognitoUser.signOut();
This function clears any locally cached tokens for that user. This function will not set cognitoUser to null. You would still be able to call all functions on this object, however those (such as getUser, changePassword etc) functions which require valid tokens will fail because the user has signed-out (i.e. no valid tokens).

Docusign API - Views/Recipient with In Person Signing

I have everything working for the views/sender, and I have envelopeId/recipients working - so I know every piece of data that I think I need.
In my envelope I have 2 inPersonSigners. The first is a "client" always, and the second is an employee, always.
I have the UserId, RecipientGuid, RecipientId, UserName, etc. Since these are In Person AND Embedded signers, they do not have email addresses.
I have been unable to get the recipient view to return the URL because the "UNKNOWN_ENVELOPE_RECIPIENT" OR "INVALID_ENVELOPE_RECIPIENT" errors I am receiving with every combination of data I have tried.
In the documentation it states you only need the clientUserId or a userName and Email combination. I have tried a variety of these, and still cant get the in person, embedded signing recipient view to return the correct response. 100% of the time it is an envelope recipient invalid error. I have tested every combination I can think of in postman and code;
inPersonSigners
[0]
clientUserId:"SomeoneHelpfulsomeonehelpful#stackexchange.com"
hostEmail:"someonehelpful#stackexchange.com"
hostName:"StackExchange User"
note:""
recipientId:"1"
recipientIdGuid:"xxxxxxxx-xxxx-xxxx-b65d-3bb23fbf8860"
requireIdLookup:"false"
roleName:"1"
routingOrder:"1"
signerEmail:""
signerName:"Test Testeroni"
status:"sent"
userId:"xxxxxx-xxxx-xxxx-913e-c347a9f2dafd"
I just need to be able to take the data above, post to /views/recipient and get the response url.
I think the problem is that when this document template is being created, via Drawloop ->Docusign, there is no Email being passed, but there is a Name and clientUserId. Hopefully its something simple that I have missed after looking at the same thing for hours.
The below sample invocation/POST would work. I did notice that your clientUserID resembles an email# - typically this value is in a GUID format. Something to keep in mind.
POST
https://demo.docusign.net/restapi/v2/accounts/459963/envelopes//views/recipient
{
"authenticationMethod":"email",
"username": "StackExchange User",
"email": "someonehelpful#stackexchange.com",
"returnUrl":"http://www.something_you_provide.com",
"clientUserId":"SomeoneHelpfulsomeonehelpful#stackexchange.com"
}

Meteor.js redirect to "dedicated" page before email is verified

I have this logic that I'm trying to implement and I'm failing to do so... Here is the deal. I have implemented the confirmation mail for new users and now with the code that I will paste bellow I'm basically blocking the user from login into the app before he confirms he's email address. Okay fairly clear. But now I want to send him to a dedicated "verifiaction" page where it will only be some kind of text like "You need to verify you email before you can login, click to resend the confirmation link, blablabla". Im also using iron router.
Im doing this for the check:
//(server-side) called whenever a login is attempted
Accounts.validateLoginAttempt(function(attempt){
if (attempt.user && attempt.user.emails && !attempt.user.emails[0].verified ) {
console.log('email not verified');
// Router.go('verification'); - some kind of my "logic" what I want to
}
return true;
});
There is a discussion with the same issue here and in the comments, a user suggests resending the verify email token and alerting the user, instead of redirecting to a page, which would be simpler. The code for that would look like:
Accounts.validateLoginAttempt(function(attempt){
if (attempt.user && attempt.user.emails && !attempt.user.emails[0].verified ) {
Accounts.sendVerificationEmail(user._id);
Alert('Your email has not been verified, we have re-sent the email. Please verify before logging in.');
//you could also use a modal or something fancy if you want.
}
return true;
});
If definitely want to create a page, there is an answer here about ways to do that, but how you do it it depends on whether you want it to be part of the layout or not.

Checking if an email is valid in Google Apps Script

I'm using the built-in api for scripting against Google Spreadsheets to send some booking confirmations, and currently my script breaks if someone has filled in an invalid email. I'd like it to just save some data to a list of guests that haven't been notified, and then proceed with looping through the bookings.
This is my current code (simplified):
// The variables email, subject and msg are populated.
// I've tested that using Browser.msgBox(), and the correct column values are
// found and used
// The script breaks here, if an incorrect email address has been filled in
MailApp.sendEmail(email, subject, msg)
According to the documentation the only two methods on the MailApp class are to send emails and check the daily quota - nothing about checking for valid email addresses - so I don't really know what criteria must be fulfilled for the class to accept the request, and thus can't write a validation routine.
If you need to validate email addresses beforehand, create a blank spreadsheet in your drive. Then, run the function below, changing the testSheet variable to point to the spreadsheet you created. The function will do a simple regex test to catch malformed addresses, then check if the address is actually valid by attempting to temporarily add it as a viewer on the spreadsheet. If the address can be added, it must be valid.
function validateEmail(email) {
var re = /\S+#\S+\.\S+/;
if (!re.test(email)) {
return false;
} else {
var testSheet = SpreadsheetApp.openById(arbitrarySpreadsheetInYourDrive);
try {
testSheet.addViewer(email);
} catch(e) {
return false;
}
testSheet.removeViewer(email);
return true;
}
}
regex from How to validate email address in JavaScript?
Stay calm, catch and log the exception and carry on:
try {
// do stuff, including send email
MailApp.sendEmail(email, subject, msg)
} catch(e) {
Logger.log("Error with email (" + email + "). " + e);
}
On the otherhand, avoid Checking email in script and get rid of loses quota or try-catch etc. I used that I got a valid email when user attempt to send an email, by signing him in an email and got that email:
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
String s = account.getEmail(); // here is the valid email.
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
}
}
Full procedure Here.
This answer is much later than this question was asked, but I piggy-backed off of remitnotpaucity's answer based on a comment in his answer. It does basically the same thing, adding the email to the spreadsheet and catching the error, however in my case it creates a new spreadsheet, attempts to add the user, and then after attempting to add the user, deletes the spreadsheet. In both cases, that the email is a valid email or not, it deletes the newly created spreadsheet.
Some things to note:
I am not as familiar with regular expressions, so I only check to see if the # symbol is within the email read into the function, and do not check for whitespaces.
I believe that even if it passes the first if-statement, even if it's not a valid email, an error will still be thrown and caught because Google will still catch that it's not a valid email, making the first if-statement redundant
If you are trying to validate an email outside your company, I'm unsure how it would react, so be fore-warned about that
This validation method takes a few seconds because you are creating and then deleting an email all within a single function, so it takes a fair bit longer than remitnotpaucity's
Most importantly, if you are able to, I would use an API. I believe that this one would work perfectly fine and should be free, it just may take some extra elbow-grease to get to work with GAS.
function validateEmail(email){
let ss = SpreadsheetApp.openByUrl(SpreadsheetApp.create('Email Validation Spreadsheet', 1, 1).getUrl())
if(!new RegExp('[#]').test(email)){
return false
} else{
try{
ss.addViewer(email)
} catch(e){
setTrashed()
return false
}
setTrashed()
return true
}
function setTrashed(){
DriveApp.getFilesByName('Email Validation Spreadsheet').next().setTrashed(true)
}
}

Categories