i am creating login api and hashed password using bcrypt - javascript

I want to create a register login logout system. at time of registration i am taking email and password
and storing hashed password. now when logging in i want to compare password entered to hashed password. so basically I want to know how can I compare and check plain password with hashed passwords

I think this is a duplicate question but am not able to mark it as such.
This should work, taken from the bcryptJS docs.
Sync
// Load hash from your password DB.
bcrypt.compare(myPlaintextPassword, hash, function(err, result) {
// result == true
});
Promise
// Load hash from your password DB.
bcrypt.compare(myPlaintextPassword, hash).then(function(result) {
// result == true
});

Related

MySql, NodeJS, ExpressJS and bcrypt: what is the best way to handle users' login?

My solution works, but I'm not sure this is safe and appropriate. On the front end I have a ReactJS app that send with axios a request with the login and password. On the back end I have NodeJS + ExpressJS handling the request as follows:
router.post('/', function(req, res, next) {
// get the records that match the login provided
const sql = "SELECT name, surname, login, password, blocked FROM users WHERE login=?";
query(sql, [req.body.login])
.then((result)=> {
// if there are 1 or more results, compare the passwords with bcrypt
if (result.length > 0) {
bcrypt.compare(req.body.password, result[0].password, function(err, success) {
if (success) {
// if the user is not blocked, send the status 200 with user's data
result[0].blocked ?
res.status(401).json({type: 'Warning', message: 'Your account has been blocked. Plase contact the admins.'})
:
res.status(200).json({name: result[0].name, surname: result[0].surname, email: result[0].email});
} else {
// send an error if the password is wrong
res.status(401).json({type: 'Error', message: 'Please check that your login and password are correct.'});
}
});
} else {
// send an error if the login was not found
res.status(401).json({type: 'Error', message: 'Please check that your login and password are correct.'});
}
});
});
Is it enough/safe to query the db for the provided login (it's unique) with if (result.length > 0)?
Is it ok to have the error message contained in the server response like this?
res.status(401).json({type: 'Warning', message: 'Your account has been blocked. Plase contact the admins.'})
I have the chance to let the user know if he typed the correct login but the wrong password; should I let him know that? I think it would give to malicious users the knowledge that the login actually exists, so for now I just send a generic login/pwd error. Is this ok?
Is ok to send the user's data from the server to the client if the login was successful?
Is it ok to have the error message contained in the server response like this?
I have the chance to let the user know if he typed the correct login but the wrong password; should I let him know that? I think it would give to malicious users the knowledge that the login actually exists, so for now I just send a generic login/pwd error. Is this ok?
Your implementation is good enough. It's also a good practice letting users know why they are unable to login without giving out too much information EVEN when it's a problem with their supplied credentials (something you are doing already).
Is it enough/safe to query the db for the provided login (it's unique) with if (result.length > 0)?
Yes, this is fine too. You may also want to add a LIMIT 1 to your query to give you a little performance boost since there is no point having your DB scan through all the records when you expect only one result.
It is also a good practice to only send the minimum amount of information and request for more on demand.
As a general observation of your code, you would benefit from the following:
Doing some error checking on your request object before querying the database at all (good practice too) as there is no guarantee that a valid or well formatted username/password would be sent with the request.
Moving the responses into another file to make your code cleaner and maintainable.

How to handle and validate sessions between the backend and the frontend

I have created a backend for user registration and login, I do not know how sessions are handled and verified in the back end.
I read some articles on how to generate the session token but I have no clue of how to validate that token once send to the server side asking for some information
this is what i did, stored the session in the backend for each user and then with a handmade middle-ware asked if this session is created for that user or not which i know is inefficient
router.post("/createUser",(req,res)=>{
const {Name, Email , Phone , Password, UserName} = req.body
console.log(Email,Phone,Password)
if(Name && Email && Phone && Password){
const user = new UserModel({Name,Email,Phone,Password,UserName})
user.save((e)=>e? console.log(e): console.log("success"))
const Session = new SessionModel({userID:user._id,session:req.sessionID})
Session.save()
res.status(201).send(req.sessionID)
}else{
res.status(500).send()
}
})
and this is how i validate the request
router.use("/profile",(req, res , next)=>{
const {SessionID , UserID} = req.query
SessionModel.findOne({userID:UserID},(err,session)=>{
if(session.session === SessionID){
next()
}else{
return res.status(500).send()
}
})})
router.get("/profile",(req,res)=>{
res.send("works")
})
You are quite duplicating things: express-sessions already manages sessions for you, there is no sense in duplicating those sessions into a database (express-sessions can do that for you if you have to scale beyond one server).
Actually you could just store the userID in the session, then check wether a userID exists in the session to validate the request. If you need to access the user data, you can just look the user up based on the id.
router.post("/createUser",(req,res) => {
// ...
req.session.userID = user._id;
//...
});
router.use((req, res, next) => {
if(!req.session.userID)
return res.status(403).send("not logged in");
next();
});
// all routes are secured beyond this point
Mandatory Note: Never ever store plain text passwords in your database (aka don't be like Facebook ;)). At least hash them, if you want to do it right hash them with a per user salt.

Change Password using react native and Firebase

In our project there is an option that the user can change their password. To do that
Before change the password user must enter current password, then check whether the entered password is matched with the saved password right now.
If it is OK, Then User has to update the old password (saved password) with new password.
I am using react native and Firebase for the developing of the project. If any one knows the solution, please let me know...
Firebase Auth won't let you change a password unless you are recently authenticated. If you try to updatePassword without being recently authenticated, you will get an error auth/requires-recent-login.
Here is how you can do it:
// Ask signed in user for current password.
const currentPass = window.prompt('Please enter current password');
const emailCred = firebase.auth.EmailAuthProvider.credential(
firebase.auth().currentUser, currentPass);
firebase.auth().currentUser.reauthenticateWithCredential(emailCred)
.then(() => {
// User successfully reauthenticated.
const newPass = window.prompt('Please enter new password');
return firebase.auth().currentUser.updatePassword(newPass);
})
.catch(error = > {
// Handle error.
});
Note the above example, uses window.prompt for illustration. You would use your own equivalent react-native UI here instead.

Quickblox: Change password of other user in Javascript

I'm doing a javascript app with Quickblox and I'm having one problem. I want to have a recover user password function and I have thought that an special user could change another one password. For that I'm using this:
var params = {password: newPassword, old_password: oldPassword };
QB.users.update(userId, params, function (error, response) {
//...
});
The function only works if I use the same userId of the user connected. I know that there is a forgot password function that is sending mails in Quickblox, however, I would like to not send any mail. What I can do? How can I use QB.users.update properly?
Lot of thanks in advance and best regards
You can't change a password of another users, only yours.
You can try to use admin account's credentials to change other user's password

how to store signup data into redis with node.js

i want to store signup data it contains name and email and password.
i will store this data in mongodb like this
db.save({"name":"xxxx","email":"xxxxx","password":'xxxxxxxx'},function(err,result){});
when user login ,they surely give their email id or username with password so i will find this user exist in db or not by using like this
db.find({'email:'xxxxxxx','password':'xxxxxxxxx'},function(err,result){});
i have tried to do same in redis,by like this
db.hmset('key' name xxxxx email xxxx pass xxxxxx,function(){});
it is stored but how can i check email id usename already exist becz user will give email and password only.if i know key then only i can find that data.even if i know key i can get only data i could not be found data already exist ot not like mongodb
how can i solve this?
You could store your users both in a Set and a Hash for details.
You can then check in the Set if a user exists with: http://redis.io/commands/sismember
I think you should break things down into chunks instead of trying to do everything with one query. So, for example, to add a new user, first check if the user exists:
(My example assumes a Mongoose User Model has been defined)
User.findOne({$or : [{'email': req.body.email}, {'username': req.body.username}],
function(err, result) {
if (err) {next(err);}
if (result) {
// you found an existing user
res.send(309, {'message':'Error: User exists'});
} else {
// no user found
var user = new User({
'email': req.body.email,
'username': req.body.username,
'password': req.body.password,
'and-so-on': req.body.moredata
});
user.save(function(err){
if (err) {next(err);}
res.send(200, {'message':'User Registered Successfully'});
});
}
Honestly though, I wouldn't recommend writing a user authentication system from scratch, because it is pretty limiting in todays world of auth methods. I personally use Passport, because it gives you the ability to use multiple auth systems with your app, including Facebook, Twitter, and so on and so forth.

Categories

Resources