Reset password using restful API - javascript

So I'm trying to Create a reset page using restful API. I haven't found much info on the internet and I'm probably no using the best method. What I'm trying to do is send a code in the email of the user and then after the user typing the code will be decided if he can or cannot update the pass. I can't seem to find a way to pass the value of the code generated on the first request to the second to check if its correct. Any help is appreciated. Thanks in advance!
//ForgotPassword?
app.get('/forgotpassword/:username', function (_req, res) {
var seq = (Math.floor(Math.random() * 10000) + 10000).toString().substring(1);
console.log(seq);
mysqlConnection.connect(function () {
mysqlConnection.query('SELECT Email from Customer Where Username = ?', [_req.params.username], (err, results, _fields) => {
if (!err){
console.log(results[0].Email);
var mailOptions = {
from: 'myemail',
to: results[0].Email,
subject: "Password Reset Verification",
text: "If you did not request this, please ignore this email and your password will remain unchanged. CODE: " + seq,
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
//Handle error here
res.send('Please try again!');
} else {
console.log('Email sent: ' + info.response);
res.send('Sent!');
}
})
}
else
console.log(err);
})
})
});
//CodeRandomCodeFromResetPass
app.get('/reset', function (req, res) {
var code;
//if code typed is = to seq sent in the email
res.send("The code is correct");
});```
//then I'll create a post request that updates the password username from the first get request

The code sent in email should be store in a table or collection. So code will be store against the email and an expiry time of the code. So in the next phase when the code will pass with an email you can check that this(entered) email should belong to this(entered) code within this(expiry time of code) time frame, so if condition satisfied then requested user can reset/change the password.

Related

Input Value doesn't save, when pushing onto array gives undefined value

I am trying to update the user account details in firebase but I have noticed that the input value for one of my fields keeps coming up as undefined even when I console.log it. I am working in two files one is a loginjs file in which I am defining the user input.
signUpForm.addEventListener('click', function (e) {
e.preventDefault();
isSigningUp = true;
var email = signUpEmailInput.value;
var password = signUpPasswordInput.value;
var displayNameUser = displayNameInput.value;
var userPrivateKey = signUpPrivateKey.value;
var user = firebase.auth().currentUser;
var photoURL = "https://www.gravatar.com/avatar/" + md5(email);
if (signUpPasswordInput.value !== signUpPasswordConfirmInput.value) {
setSignUpError('Passwords do not match!');
} else if (!displayNameUser) {
setSignUpError("Display Name is required!");
} else if (!userPrivateKey) {
setSignUpError('You need to set a Private Key!');
} else {
auth.createUserWithEmailAndPassword(email, password)
.then(function (user) {
user.updateProfile({
displayName: displayNameUser,
photoURL: photoURL,
privateKey: userPrivateKey
}).then(function () {
// Update successful.
window.location.href = 'chat.html';
}).catch(function (error) {
// An error happened.
window.alert("Some unexpected error happened!");
});
user.sendEmailVerification().then(function () {
// Email sent.
}).catch(function (error) {
// An error happened.
window.alert("Email was not able to send!");
});
})
.catch(function (error) {
// Display error messages
setSignUpError(error.message);
});
}});
The weird thing is that the user input for my displayname and photoURL are working just fine, but when it comes to my private key user input it registers the input when it goes to the chat page and I do a console.log(user.privatekey) It says it is undefined.
In my chatjs file, thats when I am pushing the all the user profile information. The chatjs file basically allows a user to send a message, the message and all the user profile information gets stored onto the firebase database.
messages.push({
displayName: displayName,
userId: userId,
pic: userPic,
text: myString.toString(),
privatekey: user.privatekey,
timestamp: new Date().getTime() // unix timestamp in milliseconds
})
.then(function () {
messageStuff.value = "";
})
.catch(function (error) {
windows.alert("Your message was not sent!");
messageStuff;
});
The thing again is that the privatekey does not get stored at all, which is what I am not understanding, since it is registering user input in the loginjs file but when I go to the chatjs file it keeps saying the value is undefiend. I have googled everywhere and I still haven't found a solution to it. Any help would be greatly appricated!
It's because the Firebase user object you receive from Firebase is not customizable. When you call the createUserWithEmailAndPassword(email, password) method, it returns a specifically defined user object back to you - check out the docs for the properties of this object.
The properties displayName and photoURL both work because they are already properties of the user returned. privateKey is not an existing property of the Firebase user object, and Firebase doesn't know how to handle an update call for a property that isn't defined. Check out this question & answer where Frank explains that Users in Firebase aren't customizable - you need to store any extra info separately.

How to remove logged in user in Meteor

I'm developing an app in Meteor and I want to know how I do can delete a user's account who is logged into the system? I mean that you can delete your account (like Tinder or Facebook) and the application ejects you because you're already deleted, and you no longer exist.
With a simple button of "Delete your account" attached.
If you could help me; I'm still a novice I'd really appreciate it, I try to retrieve the id of the current user with Meteor.userId(), and I was creating a method in the following way:
Meteor.methods({
SuprimirPersona: function(id) {
var postId = Meteor.userId();
const userId = this.userId;
const p = Meteor.users.findOne(postId);
if (userId && p === userId) {
Meteor.users.remove({
postId: this._id
},
function(error, result) {
if (error) {
console.log("Error removing user:", error);
} else {
console.log("users removed:" + result);
}
})
}
}
});
And calling the method in the following way but it does not give any results, I do not understand why:
'click #Desactivarr': function() {
var postId = Meteor.userId();
Meteor.call('SuprimirPersona', userId, function(error, result) {
if (error) {
console.log("Somee Error");
}
});
Meteor.logout(function() {
FlowRouter.go('/');
});
},
Hope someone could help me! Regards!
I've just answered this question on Meteor Forums:
https://forums.meteor.com/t/how-to-remove-logged-in-user-in-meteor/42639/3
The issue is you're trying to remove Users by postId, instead of Users.remove({_id: id}). You're removing nothing :)
To remove a user from the user's collection. You need to get the userid of the user you want to remove. This you can get by calling Meteor.userId() on the client to get the userid of the user or this.userId on the server. You need to logout the user and after a successful logout you can pass the userid you got to the meteor.users.remove(userId)
You are doing some unnecessary things on the client and server side - like getting the same user id multiple times, not even passing it to the server side method and then getting it again.
I think what you are trying to do is get the id of a user that posted something and pass it to the server side, where you check if the poster's id is the same as the id of the current user. If so, you remove the user, otherwise nothing happens.
'click #desactivarr' : function() {
var postID = <get the id of the user you want to delete here>;
Meteor.call("suprimirPersona", postID, callbackfunc);
}
Then on the server side it would be
Meteor.methods({
suprimirPersona : function(postID) {
var userID = Meteor.userId();
if (userID && postID === userID) {
Meteor.users.remove({ postId : userID })
}
}
});
Meteor.userId() and this.userId return the id of the currently logged in user that is executing the code on the client side or making the request to a server side method.

How to redirect another page after successfully login nodejs

I'am trying to sending client to next page when login process is successful done,page is confirm page.but i am geting some error.
image screenshot
router.post('/sign_in', urlend, function(req, res) {
var email = req.body.user_id;
var password = req.body.password;
if (email != '' && password != '') {
user_modell.findOne({
email: email,
password: password
}, function(err, data) {
if (err) {
//res.status(500).send();
console.log('error');
} else if (!data) {
console.log('Incorrect User ID or Password');
return res.end();
} else {
res.render("confirm");
}
});
}
res.end();
});
response.redirect('URL'); is used to redirect request to another page
Code
router.post('/sign_in',urlend,function(req,res){
var email=req.body.user_id;
var password=req.body.password;
if(email!='' && password!=''){
user_modell.findOne({email:email,password:password},function(err,data){
if(err){
//res.status(500).send();
console.log('error');
} else if(!data){
console.log('Incorrect User ID or Password');
return res.end();
}else{
res.redirect("/confirm");
}
});
}
res.end();
});
You can use express-redirect package as well.
Explanation for your error
The error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client is because your code tries to send two responses. model.findOne is like a timeout. You pass in a callback and it executes later. This means that res.end() sets the headers and sends a response. Then later, your callback is called and you try to send another response.
Think of it like a telephone conversation: someone calls you and tells you their email/password, you say "Hold on a second, I'll just check", then you hang up the phone and pick up a notebook of known emails/passwords. Then when you figure out what you want to respond with, you pick the phone back up, but there's nobody listening, cause you cut them off when you hung up the phone!

NodeJS express Authentication using POST returns Error Cannot Set Headers After they Are Sent

I am trying to build a basic Auth using post
app.post("/api/auth",function(req,resp)
{
var username = req.body.username||req.param('username');
var password = req.body.password||req.param('password');
log("Performing Log Check");
log(username + " "+password);
var sent ={};
sent.status =false;
sent.authenticated = false;
var query = {}
query.sql= "SELECT * FROM voix_auth";
query.timeout= 4000; // 40s
connection.query(query, function (error, rows, fields)
{
if(!error)
{
var i=0;
while(i!=rows.length)
{
if(rows[i].username == username && rows[i].password == password)
{
log(rows);
sent.status = true;
sent.authenticated = true;
sent.token = tokenData;
log(sent);
break;
}
i+=1;
}
resp.send(sent);
} //Error Ends
else
{
log("Error Occured");
}
}); //connection Query
log(sent);
resp.send(sent);
});
The issue here is that I get Cannot set header After They are Sent.
So when I remove resp.send() this error is gone.
But if the response I get is always false even though the user is Authenticated.
Please help.
You cant send out multiple responses.
Things to change
Change query to something like select ONLY_STUFF_YOU_NEED from table where username & passwords match. Take care of sql injection.
Wrap the query in a function that returns back a valid user object ONLY if auth matches. Move it outside the controller. Example + shameless plug - https://github.com/swarajgiri/express-bootstrap/tree/master/core
After auth is done, send the response using res.send

Geddy Save User

I am currently involved helping out on a project which involves using the Geddy js framework, which it is my first time using. I am currently trying to fix the create method inside a model for users. Here is the code below:
this.create = function (req, resp, params) {
var self = this
, user = geddy.model.User.create(params);
//need to ensure that the user agrees with the terms and conditions.
// Non-blocking uniqueness checks are hard
geddy.model.User.first({username: user.username}, function(err, data) {
if (data) {
params.errors = {
username: 'This username is already in use.'
};
//self.transfer('add');
}
else {
if (user.isValid()) {
user.password = cryptPass(user.password);
user.suburb = "";
user.state = "";
user.postcode = "";
}
user.save(function(err, data) {
if (err) {
params.errors = err;
self.transfer('add');
}
else {
// setup e-mail data with unicode symbols
var mailOptions = {
from: "App ✔ <hello#app.com>", // sender address
to: user.email, // list of receivers
subject: user.username + " Thank you for Signing Up ✔", // Subject line
text: "Please log in and start shopping! ✔", // plaintext body
html: "<b>Please log in and start shopping!✔</b>" // html body
}
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
}else{
console.log("Message sent: " + response.message);
}
// if you don't want to use this transport object anymore, uncomment following line
smtpTransport.close(); // shut down the connection pool, no more messages
});
self.redirect({controller: self.name});
}
});
}
});
};
If you look in the code there is apparently a check to see if the so-called user is valid like so: if (user.isValid()) {
user.password = cryptPass(user.password);
user.suburb = "";
user.state = "";
user.postcode = "";
}
The proceeds on to 'save' regardless whether or not the user is valid. I'm thinking why is the code this way? It sounds nonsensical. I asked the original developer who was on the project about it and he said the model was apparently generated when he created the project.
So in bit of a confused state, if anyone can tell me why the save method is outside the if statement in the first place? Is it something the original creators of Geddy intended? or is really nonsensical and I should change it?
Thanks.
Geddy's save() call will error out if the data is invalid (unless force flag is set, which it isn't). It uses the same isValid() call actually. So, looks like what you have here is just someone's way to have a single error handler for all the error cases.
For user.password being set with crypted data only if the data looks valid, I'm guessing this is simply to make 'must be set' type of validation to work. Chances are that even with an empty password, the crypted string would be otherwise counted as set.

Categories