check if email exists in mongodb while typing - javascript

this project uses js , mongoose , node.js
if use an email that already exists during registration to create an account, it will refresh the page clear all fields and shows a pop up message using ajax that says email exists. i dont want the fields to be cleared
im trying to fix this. the idea that i thought would be perfect is if i can use an event listener that will check the email against the database every time the user types something in the email input field. i already did this with js to make sure the passwords are identical before posting, all help and tips and remarks are welcome
here is the part of the code that checks if email exists
module.exports.signUp = async (req, res) => {
const { site_web, username, fonction, direction, email} = req.body
try {
if(email){
var check = await InscritModel.findOne({ email: email });
if(check){
res.render('inscription', { layout: 'inscription', email: true});
}
else{
// create user
}
}
}
}
UPDATE
im still stuck with this, i trying to use ajax to constantly check the email input against the database in real time, but i know im messing up a lot of things,
i created a post route in user-routes called router.post("/emailCheck", emailCheck); and in function-controller file i created this function
module.exports.emailCheck = async (email) => {
var check = await InscritModel.findOne({ email: email });
if(check){
return 1;
}
else{
return 0;}
}
this is the html input call
<input type="email" id="txtUserEmail" class="form-control" name="email" placeholder="Email.." required>
and this is the crazy ajax code
$(document).ready(function () {
$('#txtUserEmail').keyup(function () {
var email = $(this).val();
if (email.length >= 3) {
$.ajax({
url: '/emailCheck',
method: 'post',
data: { email: email },
success: function (data) {
var divElement = $('#divOutput');
if (data) {
divElement.text(' already in use');
divElement.css('color', 'red');
}
else {
divElement.text( ' available')
divElement.css('color', 'green');
}
},
error: function (err) {
alert(err);
}
});
}
});
});
its shows a one very long error message with so many things, it ends with this
Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 8)
hopefuly ill get there, any help is appreciated, the idea i have in mind is to make ajax call a function that takes an email in its parameters and checks it against the database and returns true or false.

well, i ended up finding the solution, ill share for future people.
the goal: stop the other fields from getting cleared when the email already exists in database
the problem: verifying the email happens after the form is submit, which means the page gets refreshed
solution idea: disable the submit button, use js to listen on the email input, and verify the input against the database while the user is typing.
app.js or routes.js whatever u named it
const InscritModel = require('../models/inscrit-model');
router.get('/usercheck', function(req, res) {
console.log(req.query);
// dont forget to import the user model and change InscritModel by whatever you used
InscritModel.findOne({email: req.query.email} , function(err, InscritModel){
if(err) {
console.log(err);
}
var message;
if(InscritModel) {
console.log(InscritModel)
message = "user exists";
console.log(message)
} else {
message= "user doesn't exist";
console.log(message)
}
res.json({message: message});
});
});
in html
<div id="divOutput"></div>
<input type="email" id="usercheck" required>
<input type="submit" id="btsubmit" disabled />
in JS
$('#usercheck').on('keyup', function () {
console.log("ok");
console.log($(this).val().toLowerCase());
$.get('/usercheck?email=' + $(this).val().toLowerCase(), function (response) {
$('#divOutput').text(response.message);
var bouton = document.getElementById('btsubmit');
bouton.disabled = true;
if ($('#divOutput').html() === "user exists") {
$('#divOutput').text('Email not available').css('color', 'red');
}
else {
$('#divOutput').text('Email available').css('color', 'green');
bouton.disabled = false;
}
})
});

Related

I can't access a user input in node.js

I am developing an apt management app.
I managed to get all functions to work but I am having trouble with the last one.
Basically, user selects one of the 5 update options from the db update menu page by clicking one of the submit buttons numbered from 1 to 5.
Button#5 is for updating the monthly apt fee. User enters the new monthly fee and clicks the update button.
But no matter what I do, I can't access the user input in req.body.newFee.
When I display it at the console, node displays it as undefined. Can someone tell me what I am doing wrong?
Below is my main server.js file.
// Send login page file to the client.
app.get('/loginpg', function(req, res) {
res.sendFile("D:/Behrans-files/Web-projects/havuzlusite/loginpg.html");
});
app.post('/server', (req, res) => { //Post request to receive user login data that was posted to server.js by login form.
var usrname = req.body.isim;
var usrpwd = req.body.sifre;
if (usrname && usrpwd) { //Check if user has entered name and password in the login form.
if (usrname == 'Yonetim' && usrpwd == "admin") { //If building management name and pwd entered,
res.render('dbupdmenupg'); //Display db update menu page.
//Route to handle db update menu page.
app.post('/dbupdmenupg/:btnno', (req, res) => { // Get the number of clicked button.
console.log("newFee1: ", req.body.newFee);
// Route to handle apt fee payment - If button#1 was clicked.
if (req.params.btnno == 1) {
res.render('usrpmtpg'); //Display user apt fee payment page.
app.post('/', (req, res) => { //Post request to access payment month and payment amount inputs from user.
var usrname = req.body.usrname;
var pmtmnth = req.body.pmt_mnth;
var pmtamt = req.body.pmt_amt;
queryUsrName(usrname, function(response) { //Pass usrname and call function to see if the user is in db.
console.log('status_flg: ', response);
if (response == 'Found') { //If response has no error message, call function to update user payment data in db.
updateUsrPmtData(usrname, pmtmnth, pmtamt, function(response) { //Call function to update user apt fee payment data in db.
alert(response); //Display db update status message from called function.
res.render('usrpmtpg');
});
} else if (response == 'Not found')
alert('İsim veri tabanında bulunamadı. Ana sayfaya dönmek için lütfen Ana sayfa butonuna tıklayınız!'); //If response has error message, display error message.
else
alert('Site sakini ismi veri tabanında aranırken sorun oluştu.');
})
})
}
// Route to handle deletion of existing resident user - If button#2 was clicked.
if (req.params.btnno == 2) {
res.render('deluserpg');
app.post('/', (req,res) => {
var usrname = req.body.usrname;
queryUsrName(usrname, function(response) { //Pass usrname and call function to see if the user is in db.
if (response == 'Found') { //If response has no error message, it means user is in db, call function to delete it.
deleteUser(usrname, function(response) { // Pass username input data as parameter to call deleteuser function.
alert(response); //Display db delete status message from called function.
res.render('dbupdmenupg');
})
} else if (response == 'Not found') {
alert('İsim veri tabanında bulunamadı. Lütfen sistemde mevcut bir isim girin.'); //If response has error message, display error message.
res.render('deluserpg');
} else
alert('Site sakini ismi veri tabanında aranırken sorun oluştu.');
})
})
}
// Route to handle addition of new resident user - If button#3 was clicked.
if (req.params.btnno == 3) {
res.render("adduserpg");
app.post('/', (req,res) => {
var usrname = req.body.newname;
queryUsrName(usrname, function(response) { //Pass usrname and call function to see if the user is in db.
if (response == 'Found') {
alert('Isim veri tabaninda mevcut, tekrar eklenemez. Lütfen sistemde olmayan bir isim girin. '); //If response has error message, display error message.
} else {
//If response has error message, it means user is not in db, call function to add it.
addUser(req.body.newname, req.body.newpwd, req.body.newblokno, req.body.newdaireno, req.body.newaidat, function(response) { //Pass input data as parms to call addUser funcn.
alert(response);
})
}
res.render('adduserpg');
})
})
}
// Route to handle reseting residents for the new year - If button#4 was clicked.
if (req.params.btnno == 4) {
newyearReset(function(response) {
alert(response);
})
}
**// Route to handle updating apt monthly fee - If button#5 was clicked.
if (req.params.btnno == 5) {
res.render('updfeepg');
app.post('/updfeepg', (req,res) => {
newFee = req.body.newFee;
console.log("newFee: ", newFee);
if (newFee) {
aptfeeUpdate(newFee, function(response) {
alert(response);
})
}
})
res.end();**
// res.redirect("/dbupdmenupg");
}
})
} else { //If a resident user name and pwd entered, call function to query on name/pwd in database.
queryUsrNamePwd(usrname, usrpwd, function(rows) {
if (rows) { // If user name/pwd match db,
res.render('userdatapg', {rows}); // Display resident data.
} else
res.redirect('/loginpg');
})
}
} else //if no user name and pwd entered, display message
alert('Lütfen isim ve şifre giriniz!');
//res.end();
});
Below is the html form file updfeepg.html.
<body>
<! Create database update menu form >
<form class="updfee" action="/updfeepg" method="post">
<p class="parag" >Lütfen yeni aylık aidatı giriniz.<input type="number" class="newFee" id="newFee" max="999"></p>
<br>
<button type="submit" class="updfeebtn" name="updfeebtn" id="updfeebtn" >Aidatı güncelle</button>
<a href="http://localhost:3000" type="button" class='homepg-btn'>Ana sayfa</a>
</form>
</body>
You need to parse the body firstly before you could access it.
For that you can use multer.
UPD:
The issue is here
<input type="number" class="newFee" id="newFee" max="999">
You need to have name field here. The name field defines the name of that value in the body of the request.
Try this.
<input type="number" class="newFee" id="newFee" name="newFee" max="999">

How to add the value from an input box to an array and then output its contents?

How can I go about adding the value of an input box into an array and then display the contents of that array?
This is what I've come up with and I'm not sure why it's not working - the console.log doesn't post anything to the console, either.
var user = user;
if (!user) {
user = prompt('Please choose a username:');
if (!user) {
alert('Your name has been set to "Anonymous"');
} else {
alert('Your name has been set to "'+ user +'"');
}
}
var items = [];
function userArray() {
items.push(user);
return false;
console.log(items);
}
socket.on('onlineUsers', function (data) {
$('.dispUser').html(items);
});
The rest of the code in the file is below, just in case it helps... (changed the return statement, as per the first answer)
var user = user;
if (!user) {
user = prompt('Please choose a username:');
if (!user) {
alert('Your name has been set to "Anonymous"');
} else {
alert('Your name has been set to "'+ user +'"');
}
}
var items = [];
function userArray() {
items.push(users);
console.log(items);
return false;
}
socket.on('onlineUsers', function (data) {
$('.dispUser').html(items);
});
//Counts the number of users online
socket.on('count', function (data) {
$('.user-count').html(data);
});
//Receives messages and outputs it to the chat section
socket.on('message', function (data) {
$('.chat').append('<p><strong>' + data.user + '</strong>: ' + data.message + '</p>');
$('.chat').scrollTop($('.chat').height());
});
//SENDING OF THE MESSAGE
//Submit the form through HTTPS
$('form').submit(function (e) {
e.preventDefault();
// Retrieve the message from the user
var message = $(e.target).find('input').val();
// Send the message to the server
socket.emit('message', {
user: user || 'Anonymous',
message: message
});
// Clears the message box after the message has been sent
e.target.reset();
$(e.target).find('input').focus();
});
Answer
Your implementation is fine, but you have a bug which is preventing it from working as you've described.
The call to console.log(items) does not print anything, because that line of code never runs.
When you return from a function, the subsequent lines of code will not be ran. You should return as the last line within your function, or wrap it in a conditional.
For example:
function userArray() {
items.push(user);
console.log(items);
return false;
}
How to debug
Learning the techniques to figure this issue out yourself is an invaluable tool. You can leverage a debugger, such as the Chrome Devtools, to add breakpoints to your code. These will allow you to stop execution on a particular line, view the value of variables, and step through the remaining lines of code.
Doing so would make it clearly visible that the line of code is never running.
Find more details here: https://developers.google.com/web/tools/chrome-devtools/javascript

Firebase Web unlink password success but the email still exist in console

I have some function to Unlink a Password Provider from a user using this code :
var user = firebase.auth().currentUser;
user.providerData.forEach(function(providerData) {
console.log(providerData.providerId);
if (providerData.providerId == "password") {
user.unlink("password").then(function() {
alert("success");
}).catch(function(error) {
alert(error);
});
}
});
The above code is successful without any problem, i can't log in with the email that already unlinked which is great.
But when I check in my console, the email still exists and I can't create a new user with the same name and got the error User already exists.
Is this a Bug ? or is there anything that I miss?
I can unlink user data in Android just fine and the user that unlinked will be deleted too, but not on the web.
EDIT :
I'm using this code to link the Password to the current user, maybe this will help
var user = firebase.auth().currentUser;
var credential = firebase.auth.EmailAuthProvider.credential(vartxtEmail, vartxtPassword);
user.linkWithCredential(credential)
.then(function(usercred) {
alert("success");
}).catch(function(error) {
alert(error);
});

Using <Form>, jQuery, Sequelize and SQL to Login and route

My goal is to use the values of the IDs #username-l and #pwd-l in a html form when the user clicks the button submit, have it compare those values to values in a SQL database and if the values equal exactly the values in the database then route the user to a specified route (for now just /user is fine for testing). Currently it routes to /? with no errors which is not specified anywhere. The console shows the query is returning username = null and password = null. I have seeds in the DB called username = test password = test for testing. Any help is appreciated!
HTML:
<form id="login-form">
<div class="form-group">
<label for="username-l">Username:</label>
<input type="username" class="form-control" id="username-l" placeholder="Enter username">
</div>
<div class="form-group">
<label for="pwd-l">Password:</label>
<input type="password" class="form-control" id="pwd-l" placeholder="Enter password">
</div>
<button id="login-button" type="submit" class="btn btn-default">Login</button>
</form>
SEQUELIZE:
app.get("/api/users", function(req, res) {
db.User.findAll({
where:
{
username: req.body.username,
password: req.body.password
}
}).then(function(dbUser) {
// res.json(dbUser);
if (req.body.username === dbUser.username && req.body.password === dbUser.password) {
res.redirect("/users");
} else {
console.log("error");
}
});
});
LOGIN.JS:
$("#login-button").on('click', function() {
var username = $("#username-l").val().trim();
var password = $("#pwd-l").val().trim();
$.get("/api/users", function(data){
console.log(data);
if (username === data.username && username === data.password) {
reRoute();
} else {
console.log("that does not exist");
}
});
});
function getUser(userData) {
$.get("/api/users", userData).then(reRoute());
}
function reRoute() {
window.location.href = "/users";
}
First of all, you're doing a GET request, which, as much as I know HTTP, dosn't have body.
Second, I'm no expert in jQuery, nor I've ever used it, but a quick Google search showed that second parameter is passed as a query string, which is how GET is supposed to work. If you have any data to send, you send it via query string, not through request body.
Therefor, the problem you have is with the server side code, where you read username and password from body instead from query string. So in order for this to work, you need to extract username and password from query like this (I'm guessing you're using Express):
app.get("/api/users", function(req, res) {
const username = req.query.username;
const password = req.query.password;
// do the rest of the stuff with Sequelize and bussiness logic here
});
On the sidenote, you're full router callback has some bad things, like redundant checking if username and password match from the one retrieved from DB. You've already asked Sequelize to retrieve a row from the DB where username and password are the ones you recived from the frontend, and because of that, you don't need to check if instance's username and password matches the one you have. The thing you do need to check if the instance is null, because that means that there is no user with that username and password in your DB. So the "fixed" code should look something like this:
app.get("/api/users", function(req, res) {
const username = req.query.username;
const password = req.query.password;
db.User.findAll({
where: {
username,
password
}
}).then(function(dbUser) {
// res.json(dbUser);
if (dbUser != null) {
res.redirect("/users");
} else {
// you'd maybe like to set response status to 404
// also some user friendly error message could be good as response body
console.log("Error: user not found");
}
});
});
I hope you get the idea of the flow and where was your mistake.

Trying to pass <%> HTML Variable to Javascript - Node, Passport, and Stripe

A bit of a newbie here. I've been looking for an answer that works and found some similarities in a Jade problem but I'm not using Jade. I have passed an "user" attribute into an HTML view as so:
app.get('/profile', isLoggedIn, function(req, res) {
res.render('profilePage/profilePage.html', {
user : req.user // get the user out of session and pass to template
});
});
Then, in my profile HTML, I can access my user property like so:
<%=user.local.firstname%>'s Profile
However, I want to allow Stripe to send the user's credit card info via the Stripetoken. I have managed to include a variable amount from a text field the user inputs. However, I want to append the user property so I can use it in my callback. Here is the javascript/jquery that's included in the profile html:
<!-- New section -->
<script type="text/javascript">
<!-- Fill in your publishable key -->
Stripe.setPublishableKey('pkkey');
var stripeResponseHandler = function(status, response) {
var $form = $('#contactForm');
var $amount = $('#amount').val();
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
// token contains id, last4, and card type
var token = response.id;
// Insert the token into the form so it gets submitted to the server
$form.append($('<input type="hidden" name="stripeToken" />').val(token));
$form.append($('<input type="hidden" name="amount" />').val($amount));
// and re-submit
$form.get(0).submit();
}
};
jQuery(function($) {
$('#contactForm').submit(function(e) {
var $form = $(this);
// Disable the submit button to prevent repeated clicks
$form.find('button').prop('disabled', true);
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from submitting with the default action
return false;
});
});
</script>
As you can see, I have managed to append the $amount variable so I can access it in the callback:
module.exports = function(app, passport) {
app.post('/stripe', function(req,res) {
// =====STRIPETOKEN======
var transaction = req.body;
var stripeToken = transaction.stripeToken;
var donationAmount = transaction.amount;
stripe.customers.create({
source : stripeToken,
account_balance : 0
},function(err, customer) {
if (err) {
console.log(err);
} else {
console.log("Success!");
}});
// ====CREATE CHARGE======
var charge =
{
amount : donationAmount,
currency : 'USD',
card : stripeToken
};
stripe.charges.create(charge, function(err, charge) {
if(err)
console.log(err);
else
{
res.json(charge);
console.log('Successful charge sent to Stripe!');
console.log(charge);
};
});
// ====PROFILE PAGE REDIRECT=====
res.render('profilePage/profilePage.html', {
});
});
So here's my problem. I want to pass the user's information, kind of like I did the amount, into the post method so when it redirects on success, I can pass it back in the res.render function, as well as send it to Stripe for description purposes. The only thing I can think of is to put the user info in a hidden field in HTML and access it like that, but that sounds messy and not proper.
This is my first time posting here so I apologize if it was too lengthy or not specific enough. Thanks!
The answer was in the way I was declaring passport and stripe in my application. Make sure you declare passport after everything to make the user variable available to stripe and all views.

Categories

Resources