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.
Related
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;
}
})
});
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">
I am having an issue while using JSON server for login form. I have login credentials like Username and password and trying to execute it. I have used POST on the server, specifying username and password inserted by the user. The server should execute a query on the specified condition, to check if there are any rows with that name and password. If yes return true, if false return false. then the client should parse this response.
This is my HTML code :
<form ng-submit="loginform(logcred)" name="logform"><br/><br>
<tr ng-repeat="logcred in loginfo"></tr>
<div>
<label form="emailinput"><b>Email</b></label>
<input type="email" class="form-control" name="uname" id="emailinput" placeholder="you#example.com" ng-model="logcred.username" >
</div>
<div>
<label form="pwdinput"><b>Password</b></label>
<input type="password" class="form-control" name="pwd" id="pwdinput" placeholder="*******" ng-model="logcred.password">
</div>
<div>
<button type="cancel" class="btn" ng-click="toggle_cancel()">Cancel</button>
<button class="btn btn-primary" ng-click="submit()">Login</button>
</div>
</form>
This is the Javascript code using AngularJS:
var myApp = angular.module('myApp', []);
myApp.controller('credientials', function($scope, $http) {
$http.get('http://localhost:3000/loginfo')
.then(
function successCallback(response){
$scope.loginfo == response.data;
$scope.loginform = function(loginfo,username,password){
console.log(loginfo);
$http({
url :'http://localhost:3000/loginfo',
method : 'POST',
data : loginfo
})
.then(
function successCallback(response){
$scope.loginfo = response.data;
if (username === username && password === password) {
console.log(response);
}
else
{
console.log("Error: " + response)
}
});
}
});
I am getting the response properly from my server. But when I match the data using POST request using if condition, there I am not understanding what mistake I am doing ?
Any help / advice would be greatly appreciated.
i didnt understand if your problem is server side or client ? is your problem at
if (username === username && password === password) {
console.log(response);
}
you may use == insted of ====
You are comparing the data with itself.
username === username && password === password
Should be
username === $scope.loginfo.username && password === $scope.loginfo.password
Still, any kind of security validation should be done on the server rather than on the client.
Also, you seem to be new to Angular. Let me recommend to you the John Papa's Styleguide.
I'm trying to write an app to do real time messaging as a learning tool. I've been googling for the past 4 and a half hours trying to figure out why my insert method isn't working. It doesn't throw any errors, it simply doesn't do the actual insert.
Here's the code for it:
JS client:
Template.input.events({
"keypress .input": function(event, template){
if(event.which == 13){
event.preventDefault();
var user = Meteor.user();
var message = template.find(".input").value;
alert(Meteor.call("insert", user.username, message));
template.find(".input").value = "";
}
}
});
JS Server:
Meteor.methods({
'insert':function(username, message){
Messages.insert({
'message': message,
'user': Meteor.userId(),
'username': username,
'timestamp': new Date()
});
return "success";
},
'find': function(){
Messages.find({}, {sort: {timestamp:-1}});
}
});
HTML:
<template name="input">
<div id="input">
<input class="input" type="text" placeholder="Message..." id="message" />
</div>
</template>
I've checked using the console to confirm that nothing is being added.
Your code runs fine, and the items are saved in the DB. Just as jorjordandan and Michel mentioned it's probably caused by your publications.
An easy way to check this is to simply log what's stored. Add some logging. Since server methods always have access to all collections you can see what's actually stored.
'insert':function(username, message){
var id = Messages.insert({
'message': message,
'user': Meteor.userId(),
'username': username,
'timestamp': new Date()
});
console.log('Inserted id: ' + id);
var insertedMessage = Messages.findOne(id);
console.log(insertedMessage);
return "success";
},
Also, as a side-note, you might reconsider posting username as a string to the server method, depending on what you're after. This can easily be manipulated by the client.
Instead you could fetch the user on server-side.
Meteor.user().username
Just make sure that the user is actually logged on, or check if Meteor.user() is undefined.
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.