Authentication page - javascript

Im trying to build out my sign in page on a JavaScript, Node and Express app. Iv got the login correct, im getting a response when the users password and username match. So that part is fine. But once they match id like to take them to the home screen. However, im not sure how todo that. Iv found a res.redirect("route") but it returns: res.redirect is not a function. Ill add my code: ```app.post('/lgnfrm', function (req, res) {
var usrEmail= req.body.usrEmail;
var usrPassw = req.body.usrPass;
// INSERT WORKING
var sql = 'SELECT * FROM loginInfo WHERE email = (?)'
connection.query(sql, [usrEmail], function (err, res) {
// IF/ELSE CHECKING IF PASSWORD AND EMAIL MATCH DB VALUES
if (err) {
//
console.log(err)
} else {
// CHECKS IF THE EMAIL MATCHES DB
console.log("VALID EMAIL")
if (res.length > 0){
// IF EMAIL VALID, CHECK PASSWORD
if (res[0].passW == usrPassw) {
res.redirect("/home");
console.log("LOGIN SUCCESSFUL");
} else {
// INCORRECT PASSWORD
console.log("PASSWORD INCORRECT");
}
}
}
})
}) ```

app.post('/lgnfrm', function (request, response) {
var usrEmail= request.body.usrEmail;
var usrPassw = request.body.usrPass;
// INSERT WORKING
var sql = 'SELECT * FROM loginInfo WHERE email = (?)'
connection.query(sql, [usrEmail], function (err, res) {
// IF/ELSE CHECKING IF PASSWORD AND EMAIL MATCH DB VALUES
if (err) {
//
console.log(err)
} else {
// CHECKS IF THE EMAIL MATCHES DB
console.log("VALID EMAIL")
if (res.length > 0){
// IF EMAIL VALID, CHECK PASSWORD
if (res[0].passW == usrPassw) {
response.redirect("/home");
console.log("LOGIN SUCCESSFUL");
} else {
// INCORRECT PASSWORD
console.log("PASSWORD INCORRECT");
}
}
}
})
})

Related

Why find() using models won't work in signup route?

It's a simple signup route to store credentials in a mongoDB database but I miss something because the 2 else if won't work properly. I suspect it is my find().
The first else if returns me in Postman "error": "E11000 duplicate key error collection: vinted.users index: email_1 dup key: { email: \"jean#dpont.com\" }" and the second give me "email already exists".
Thanks in advance for your help
const express = require("express");
const router = express.Router();
const SHA256 = require("crypto-js/sha256");
const encBase64 = require("crypto-js/enc-base64");
const uid2 = require("uid2");
const User = require("../models/User");
router.post("/user/signup", async (req, res) => {
try {
const email = req.fields.email;
const username = req.fields.username;
const phone = req.fields.phone;
const password = req.fields.password;
const token = uid2(64);
const salt = uid2(16);
const hash = SHA256(password + salt).toString(encBase64);
const emailSearch = await User.find({ email: email });
if (!emailSearch || username !== null) {
const newUser = new User({
email: email,
account: {
username: username,
phone: phone,
},
password: password,
token: token,
hash: hash,
salt: salt,
});
await newUser.save();
res.status(200).json({
_id: newUser._id,
token: newUser.token,
account: newUser.account,
});
}
//problem under
else if (emailSearch) {
res.status(404).json({ message: "email already exists" });
} else if (username === null) {
res.status(404).json({ message: "please type a username" });
}
} catch (error) {
res.status(404).json({
error: error.message,
});
}
});
It looks like the issue is that if the username in the request body is not null, it's going to attempt to create a new User with that username regardless of whether a User exists with the same email - if (!emailSearch || username !== null).
It's generally best-practice to do as much input validation as you can before you start looking for records or creating new ones, as you will be able to avoid more Mongo errors and database actions if you can stop invalid actions before they're attempted. So in this case, check that the username is valid before looking for existing Users.
To solve this problem, I would move that last else-if to before you check whether a User exists with the same email. That way, once you determine whether the username is valid, then the only thing that you need to consider is existing Users before creating a new one. Something like this:
if (username === null) {
res.status(400).send({ message: "Error: Please provide a 'username'." });
}
const existingUserWithEmail = await User.find({ email: email });
if (!existingUserWithEmail) {
// Create the new User
} else {
res.status(400).send({ message: "Error: An account already exists with this email." });
}

UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client when adding response

When I add the following line res.status(201).json({ email }); I get the error message UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client. What can I do to fix this problem.
Below is a snippet of my code
module.exports.signup_post = (req, res ) => {
const { firstname, lastname, email, password } = req.body;
handleErrorSignup(firstname.trim(), lastname.trim(), email.trim(), password.trim())
.then( async (errors) => {
if(errors.firstname === '' && errors.lastname === '' && errors.email === '' && errors.password === '') {
const hash = bcrypt.hashSync('password', 10);
try {
await db.none('INSERT INTO users(firstname, lastname, email, password) VALUES($1, $2, $3, $4)', [firstname, lastname, email, hash]);
const token = createToken(email);
res.cookie('jwt', token, { httpOnly: true, maxAge: maxAge * 1000 });
res.status(201).json({ email });
}
catch(err) {
res.status(400).send('Error, user not created');
}
res.redirect('/');
}
else {
res.status(400).json({ errors });
}
});
}
The problem here is that you are sending response from try catch already, so you cannot redirect if you have sent the response already from the earlier parts of your code.
You need to remove this line from your code, or redirect only if response is not already sent in try and catch blocks.
try {
...
res.status(201).json({ email });
} catch (err) {
res.status(400).send('Error, user not created');
}
// Remove below code
res.redirect('/');
If you are looking to redirect to your home screen after signup, you need to handle the same in frontend based on the status code or response received for signup from backend.

Authentication, Compare data input from client side with mySql in server side using express JS

I need help comparing data and return true or false from the cilent side to server side to check an email is valid or not. In the client side, the client will enter an email and click a button to verify, then server will check the database if the email exist or not. If the email exists the the user is valid, and if the email doesn't exist then the client is not valid and cannot proceed to the next page. I'm not really familiar with express and some mysql query. I tested my code in postman application and it returns valid everytime. Here is some sample emails from mySql.
I'm using app.post command in my javascript express code, but looks like i'm doing it wrong and i wrote the if statement incorrectly. In postman application when i check it, it always returns valid and in client side i cannot authenticate with any email. I'm not sure what condition should i put because i'm not really familiar with express.
app.post('/verifyEmail', (req, res) => {
var email = req.body.email;
let sql = 'SELECT * FROM email WHERE email = ?'; //incorrect condition checking
let query = db.query(sql, (err, result) => {
if (email == null || !email) { //incorrect condition checking
throw err;
res.send('invalid');
}
console.log('valid');
res.send('valid');
})
})
In the client side, i'm using Angular with typescript.
//service.ts
email: string[];
getEmailAPI(): Observable < any > {
return this.http.get("http://localhost:8000/verifyEmail")
.map((res: Response) => res.json())
.catch((error: any) => Observable.throw(error.json().error || 'Server error'))
}
//component.ts
Email = [];
isVerified: boolean;
getEmailAPI() {
this.QuestionService.getEmailAPI().subscribe(
data => console.log('All email', this.Email = data),
error => console.log('server returns error')
);
}
verifyEmail(formValue) {
this.AppService.getEmailAPI().subscribe(
data => {
if (data) {
// do whatever needed is with returned data
this.isVerified = true;
} else {
this.isVerified = false;
}
},
error => console.log('server returns error')
);
}
<!--component.html-->
<form #emailVerification='ngForm' ngNativeValidate>
<label>Please Enter Your Email Below</label>
<input name="email" type="text" required/>
<button type="submit" (click)="verifyEmail(emailVerification.value)">VERIFY</button>
</form>
Can anyone help me, please? Please let me know if more snippets are needed.
you will always get valid since you are checking whether the email variable is null and your end result should return the json.Since in your client you're going to get the json. Change the code to following
app.post('/verifyEmail', (req, res) => {
var email = req.body.email;
let sql = 'SELECT count(*) as count FROM email WHERE email = ?';
let query = db.query(sql, [email],(err, result) => {
if (result[0].count == 1) {
res.json({
"data": "valid"
})
} else {
res.json({
"data": "invalid"
})
}
});
});

What am I supposed to write in my if condition in order to check if there is a record in my MySQL query?

What am I supposed to write in my if condition in order to check if there is a record in my MySQL query? I want to console.log('Taken') if there is already a user with the post-ed username in my user table.
db.query('SELECT username FROM user WHERE username = ?', [username], function (err, result) {
if (err) throw err;
if () {
console.log('Taken');
} else {
console.log('Free')
}
});
You can check whether the result have items:
db.query('SELECT username FROM user WHERE username = ?', [username], function(err, result) {
if (err) throw err;
if (result.length) { // will test if result.lenght is > 0
console.log('Taken');
} else {
console.log('Free')
}
});
Try if(result.length). You need to check the result variable for data.

Mongoose won't validate user

this is my user model and this is my js file that searches for email in database.
When passing the correct email to following code, it doesn't find the user in database although the email is correct. Should I do it somehow different?
workflow.on('patchUser', function(token, hash) {
var conditions = { email: req.body.email.toLowerCase() };
var fieldsToSet = {
resetPasswordToken: hash,
resetPasswordExpires: Date.now() + 10000000
};
req.app.db.models.User.findOneAndUpdate(conditions, fieldsToSet, function(err, user) {
if (err) {
return workflow.emit('exception', err);
}
if (!user) {
workflow.outcome.errors.push("Can't find any email match it");
return workflow.emit('response');
}
workflow.emit('sendEmail', token, user);
});
});
user is always null even thought the correct email is passed.

Categories