My goal is to put a login and register form on one page. The register already works but I always get this error when logging in.
I have already tried several things and believe that it has something to do with the submit button. because when the login button is pressed, the login function is not even called. Or I think that I have somehow set the routes wrong.
Here is the html code (register.hbs):
<div class="main_content transform8">
<img class="swipe transform" src="img/ETCO-img/swipepattern.svg" height="150%" width="auto">
<img class="secwave transform7" style="filter: drop-shadow(5px 5px 10px rgba(0, 0,0, 0.171));"
src="img/ETCO-img/secwave.svg" height="30%" width="auto">
<img class="logo transform5" src="img/ETCO-img/logoetco.png" height="270px">
<img id="wave" class="wave transform6" style="filter: drop-shadow(5px 5px 10px rgba(0, 0, 0, 0.171));"
src="img/ETCO-img/wave.svg" height="400px" width="auto">
<div id="login">
<h1 class="loginh1 transform2">Willkommen</h1>
<form class="form transform3" action="/auth/register" method="POST">
<div class="input-container">
<label class="label" for="emaillogin"><img src="../img/ETCO-img/icons/mail.svg" height="25px"> <span
style="margin-left:25px;"></span></label>
<input placeholder="example#gmail.com" class="input" type="email" id="emaillogin" name="emaillogin">
</div>
<div class="input-container">
<label class="label" for="passwordlogin"><img src="../img/ETCO-img/icons/lock.svg" height="25px"> <span
style="margin-left:25px;"></span></label>
<input placeholder="Passwort" class="input" type="password" id="passwordlogin" name="passwordlogin">
</div>
<button type="SUBMIT" class="bnlogin transform4">LOGIN</button>
</form>
</div>
<div class="registerarea transform7">
<h1 class="registerh1 ">Join us</h1>
<form class="formregister" action="/auth/register" method="POST">
<div class="input-container">
<label class="label" for="name"><img src="../img/ETCO-img/icons/user.svg" height="30px"> <span
style="margin-left:30px;"></span></label>
<input placeholder="Your Name" class="input" type="text" id="name" name="name">
</div>
<div class="input-container">
<label class="label" for="email"><img src="../img/ETCO-img/icons/mail.svg" height="25px"> <span
style="margin-left:25px;"></span></label>
<input placeholder="example#gmail.com" class="input" type="email" id="email" name="email">
</div>
<div class="input-container">
<label class="label" for="password"><img src="../img/ETCO-img/icons/lock.svg" height="25px"> <span
style="margin-left:25px;"></span></label>
<input placeholder="Passwort" class="input" type="password" id="password" name="password">
</div>
<div class="input-container">
<label class="label" for="passwordConfirm"><img src="../img/ETCO-img/icons/lock.svg" height="25px">
<span style="margin-left:25px;"></span></label>
<input placeholder="Passwort Bestätigen" class="input" type="password" id="passwordConfirm"
name="passwordConfirm">
</div>
<button type="submit" class="btnregister">Lets go</button>
</form>
{{#if message}}
<h3 class="alert alert-danger mt-4">{{message}}</h3>
{{/if}}
</div>
and the routes/auth.js
const express = require('express');
const authController = require('../controllers/auth');
const router = express.Router();
router.post('/register', authController.register);
router.post('/register', authController.login);
module.exports = router;
and the code of the controller auth.js
const mysql = require("mysql");
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const db = mysql.createConnection({
host: process.env.DATABASE_HOST,
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE
});
exports.register = (req, res) => {
console.log(req.body);
const { name, email, password, passwordConfirm } = req.body;
let hashedPassword = bcrypt.hash(password, 10);
console.log(hashedPassword);
db.query('SELECT email from users WHERE email = ?', [email], async(error, results) => {
if (error) {
console.log(error);
}
if (results.length > 0) {
return res.render('message/emailerror');
} else if (password !== passwordConfirm) {
return res.render('message/pwderror');
}
let hashedPassword = await bcrypt.hash(password, 10);
console.log(hashedPassword);
db.query('INSERT INTO users SET ?', { name: name, email: email, password: hashedPassword }, (error, results) => {
if (error) {
console.log(error);
} else {
console.log(results);
console.log('+++++++++++ User registered ++++++++++')
//route to other page later on
}
});
});
}
//to login the user
exports.login = async (req, res) => {
console.log('##### Login Versuch gestartet #####');
try {
const {emaillogin, passwordlogin} = req.body;
if(!emaillogin || !passwordlogin) {
console.log('Fehler Versuch es nochmal');
return;
} else{console.log('funktioniert')}
} catch (error) {
console.log(error);
}
}
I hope someone can help me here, because unfortunately I haven't had much to do with node.js.
Related
I'm trying to implement an authentication system using Passport.js for my express web server. However I can't let passport.js do his job in any way , could someone explain me why?
Here is my passport-config.js ;
`
const LocalStrategy = require('passport-local').Strategy
const bcrypt = require('bcrypt')
const database = require('./modules/database')
function initialize(passport, getUserByUsername) {
const authenticateUser = async (username, password, done) => {
const user = await getUserByUsername(username)
if (user == null) {
return done(null, false, { message: 'No user with that username' })
}
try {
if (await bcrypt.compare(password, user.password)) {
return done(null, user)
} else {
return done(null, false, { message: 'Password incorrect' })
}
} catch (e) {
return done(e)
}
}
passport.use(new LocalStrategy({ usernameField: 'username' , passwordField: 'password' }, authenticateUser))
passport.serializeUser((user, done) => done(null, user.username))
passport.deserializeUser((username, done) => {
return done(null, getUserByUsername(username))
})
}
Here is how i initialize it within app.js ;
initializePassport(
passport ,
username => database.User.findOne({where : {username : username}}).then(user => {return user || null})
)
Here is my get and post /login routers;
app.get("/login", function(req, res, next){
beforeEach(req, res)
res.render("login.ejs", {
session: req.session
})
})
app.post('/login' , passport.authenticate('local', {
successRedirect : '/main',
failureRedirect: '/login',
failureFlash : true
}))
I thought I implemented everything properly , maybe passport can't access the username and password? Here is my login.ejs as well;
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="common.css">
<link rel="stylesheet" href="log_sign.css">
</head>
<body>
<%- include("banner.ejs", {}) %>
<div class="col d-flex justify-content-center">
<div class="extra-padding">
<div class="card" style="width: 18rem;">
<div class="card-body">
<h1>Log in</h1>
<% if (messages.error) { %>
<%= messages.error %>
<% } %>
<form action="/login" method="POST">
<div class="form-group">
<label for="username">Username</label>
<input for="username" type="username" class="form-control" id="username" placeholder="Enter username">
</div>
<br>
<div class="form-group">
<label for="password">Password</label>
<input for="password" type="password" class="form-control" id="password" placeholder="Password">
</div>
<a class="nav-item" href="register">Need an account ? Sign in</a>
<div class="col d-flex justify-content-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
I'm trying to make a register page. When I enter the data that needs to be registered, it shows up on the console followed by Error: ER_EMPTY_QUERY.
I believe the problem is in the controllers/auth.js file but I can't figure it out for some reason. Please help, been stuck on this for the past 2 days.
controllers/auth.js:
const mysql = require('mysql');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'practice'
})
exports.register = (req, res) => {
console.log(req.body)
const {name, email, password, passwordConfirm} = req.body
db.query('SELECT email FROM users WHERE email = ?' [email], async (error, results) => {
if(error) {
console.log(error)
}
if( results.length > 0 ) {
return res.render('register', {
message: 'That email is already is use'
})
} else if( password !== passwordConfirm) {
return res.render('register', {
message: 'Passwords do not match'
})
}
let hashedPassword = await bcrypt.hash(password, 8);
console.log(hashedPassword);
db.query('INSERT INTO users SET ?', {name: name, email: email, password: hashedPassword}, (error, results) => {
if(error) {
console.log(error)
} else {
console.log(results);
return res.render('register', {
message: 'User registered'
})
}
})
})
}
register.hbs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/styles.css">
<title>Document</title>
</head>
<body>
<nav>
<h4>Node MySQL</h4>
<ul>
<li>Home</li>
<li>Login</li>
<li>register</li>
</ul>
</nav>
<div class="container mt-4">
<div class="card">
<div class="card-header">
Register Form
</div>
<div class="card-body">
<form action="/auth/register" method="POST">
<div class="mb-3">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name">
</div>
<div class="mb-3">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" name="email">
</div>
<div class="mb-3">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password">
</div>
<div class="mb-3">
<label for="passwordConfirm">Confirm Password</label>
<input type="password" class="form-control" id="passwordConfirm" name="passwordConfirm">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
{{#if message}}
<h4 class="alert alert-daner mt-4">{{message}}</h4>
{{/if}}
</div>
</body>
</html>
I am trying to create a register and login page where the registered user's details are setn to the database and then from there they are used to verify login.
The sign up button is supposed to send data to the database, hence registering a user. After that, in the login form the data os authenticated and the user logs in.
I haven't gotten to the login part, still stuck on the sign up part.
I don't get any errors displayed, it is just that my data is not being fed to the database.
index.js for nodejs:
//var { app } = require("cli");
const express = require("express");
const mysql = require("mysql");
const cors = require("cors");
app = express();
app.use(express.json());
app.use(cors());
const db = mysql.createConnection({
user: "root",
host: "localhost",
password: "",
database: "crm database",
});
app.post("/register", (req, res) => {
const CompanyCode = req.body.CompanyCode;
const UserID = req.body.UserID;
const UserFullName = req.body.UserFullName;
const UserDetail = req.body.UserDetail;
const LoginID = req.body.LoginID;
const Password = req.body.Password;
const ConfirmPassword = req.body.ConfirmPassword;
const UserPin = req.body.UserPin;
const UserEmailID = req.body.UserEmailID;
db.query(
"INSERT INTO usermst (CmpnyCode,UserID,UserFullName,UserDetail,LoginID,Password,UserPin,UserEmailID) VALUES (?,?,?,?,?,?,?,?)",
[
CompanyCode,
UserID,
UserFullName,
UserDetail,
LoginID,
Password,
UserPin,
UserEmailID,
],
(err, result) => {
console.log(err);
}
);
});
app.listen(8000, () => {
console.log("Server running on port 8000");
});
app.js for react js:
import "bootstrap/dist/css/bootstrap.min.css";
import React, { useState } from "react";
//import { BrowserRouter, Switch, Route } from "react-router-dom";
import "./App.css";
import axios from "axios";
function App() {
const [CompanyCodeReg, setCompanyCodeReg] = useState("");
const [UserIDReg, setUserIDReg] = useState("");
const [UserFullNameReg, setUserFullNameReg] = useState("");
const [UserDetailReg, setUserDetailReg] = useState("");
const [LoginIDReg, setLoginIDReg] = useState("");
const [PasswordReg, setPasswordReg] = useState("");
const [ConfirmPasswordReg, setConfirmPasswordReg] = useState("");
const [UserPinReg, setUserPinReg] = useState("");
const [UserEmailIDReg, setUserEmailIDReg] = useState("");
const register = () => {
axios
.post("http://localhost8000/register", {
CompanyCode: CompanyCodeReg,
UserID: UserIDReg,
UserFullName: UserFullNameReg,
UserDetail: UserDetailReg,
LoginID: LoginIDReg,
Password: PasswordReg,
ConfirmPassword: ConfirmPasswordReg,
UserPin: UserPinReg,
UserEmailID: UserEmailIDReg,
})
.then((response) => {
console.log(response);
});
};
return (
<div className="App">
<nav className="navbar navbar-expand navbar-light fixed-top">
<div className="container">Home</div>
</nav>
<div className="auth-wrapper">
<div className="auth-inner">
<form>
<h3>Sign Up</h3>
<div className="form-group">
<label>Company Code</label>
<input
type="text"
className="form-control"
placeholder="CompanyCode"
onChange={(e) => {
setCompanyCodeReg(e.target.value);
}}
/>
</div>
<div className="form-group">
<label>User ID</label>
<input
type="text"
className="form-control"
placeholder="UserID"
onChange={(e) => {
setUserIDReg(e.target.value);
}}
/>
</div>
<div className="form-group">
<label>User Full Name</label>
<input
type="text"
className="form-control"
placeholder="UserFullName"
onChange={(e) => {
setUserFullNameReg(e.target.value);
}}
/>
</div>
<div className="form-group">
<label>User Detail</label>
<input
type="text"
className="form-control"
placeholder="UserDetail"
onChange={(e) => {
setUserDetailReg(e.target.value);
}}
/>
</div>
<div className="form-group">
<label>Login ID</label>
<input
type="text"
className="form-control"
placeholder="LoginID"
onChange={(e) => {
setLoginIDReg(e.target.value);
}}
/>
</div>
<div className="form-group">
<label>Password</label>
<input
type="password"
className="form-control"
placeholder="Password"
onChange={(e) => {
setPasswordReg(e.target.value);
}}
/>
</div>
<div className="form-group">
<label>Confirm Password</label>
<input
type="password"
className="form-control"
placeholder=" ConfirmPassword"
onChange={(e) => {
setConfirmPasswordReg(e.target.value);
}}
/>
</div>
<div className="form-group">
<label>User Pin</label>
<input
type="Text"
className="form-control"
placeholder="UserPin"
onChange={(e) => {
setUserPinReg(e.target.value);
}}
/>
</div>
<div className="form-group">
<label>UserEmailID</label>
<input
type="email"
className="form-control"
placeholder="UserEmailID"
onChange={(e) => {
setUserEmailIDReg(e.target.value);
}}
/>
</div>
<button className="btn btn-primary btn-block" onClick={register}>
Sign Up
</button>
</form>
</div>
<div className="auth-inner">
<form>
<h3>Log In</h3>
<div className="form-group">
<label>Login ID</label>
<input
type="text"
className="form-control"
placeholder="First Name"
/>
</div>
<div className="form-group">
<label>Password</label>
<input
type="password"
className="form-control"
placeholder="Password"
/>
</div>
<button className="btn btn-primary btn-block">Login</button>
</form>
</div>
</div>
</div>
);
}
export default App;
You have to send the response back to the client, you can do so with the res object like
res.json({ result });
app.post("/register", (req, res) => {
const CompanyCode = req.body.CompanyCode;
const UserID = req.body.UserID;
const UserFullName = req.body.UserFullName;
const UserDetail = req.body.UserDetail;
const LoginID = req.body.LoginID;
const Password = req.body.Password;
const ConfirmPassword = req.body.ConfirmPassword;
const UserPin = req.body.UserPin;
const UserEmailID = req.body.UserEmailID;
db.query(
"INSERT INTO usermst (CmpnyCode,UserID,UserFullName,UserDetail,LoginID,Password,UserPin,UserEmailID) VALUES (?,?,?,?,?,?,?,?)",
[
CompanyCode,
UserID,
UserFullName,
UserDetail,
LoginID,
Password,
UserPin,
UserEmailID,
],
(err, result) => {
console.log(err);
// You have missed this line
res.json({ result });
}
);
});
I just realized that I was violating my own database foreign key constraints.
I added the following line:
db.connect((err) => {
if (err) {
console.log(err);
}
console.log("Connected to MySQL Server!");
});```
after creating the database connection and it displayed to me what was going wrong.
I created an app.use with express in order to INSERT values in a database. I want to get those values when user clicks register.
My form:
<form class="form-signin" method="POST">
<h1 class="h3 mb-3 font-weight-normal">Register</h1>
<label for="inputEmail" id="lblEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" placeholder="Email
address" name="email" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control"
placeholder="Password" name="passworf" required>
<label for="repeatInputPassword" class="sr-only">Repeat Password</label>
<input type="password" id="repeatinputPassword" class="form-control"
placeholder="Repeat Password" required>
<label for="name" class="sr-only">Name</label>
<input type="name" id="inputName" class="form-control" placeholder="Name"
name="name" required>
<label for="surname" class="sr-only">Surname</label>
<input type="surname" id="inputSurname" class="form-control"
placeholder="Surname" name="surname" required>
<div class="checkbox mb-3">
</div>
<button class="btn btn-lg btn-primary btnblock-"
type="submit">Register</button>
<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
</form>
app.use used in order to insert values in the database. Am using MySQL below:
var express = require('express');
var app = express();
var bodyParser = require('body-parser')
var http = require('http');
var urlencodedParser = bodyParser.urlencoded({extended: false});
app.use('/', urlencodedParser, function(req,res, next){
var adminUser = req.body.email;
var adminPass = req.body.password;
var adminName = req.body.name;
var adminSurname = req.body.surname;
console.log(req.body);
var sql = "INSERT INTO admins VALUES(null, ?, ?, ?, ?) ";
con.query(sql, [ adminUser, adminPass, adminName, adminSurname],
function(error, rows, fields){
if(!!error) {
console.log('Query Failed' + error.message);
} else {
console.log('Query Successful');
console.log(rows.insertId);
next();
}
});
})
app.listen(5500);
You need to create a Express POST route that the form can post too.
app.post('/', function (req, res) {
// Process form here
var adminUser = req.body.email;
var adminPass = req.body.password;
var adminName = req.body.name;
var adminSurname = req.body.surname;
// etc.
});
The path should match the form action attribute
Your form must be sending the POST request to the same route that you defined with app.use(...). In this case, your form is POSTing to the same route it is on, which means it needs to be on the / route to work.
Change your app.use(...) to be app.post(...) so that it only handles POST requests, then serve the form's html from the same route using:
app.get('/', function(req, res) {
res.sendFile(path-to-form);
})
See: https://codesandbox.io/s/won9jzj8k7
I am getting the following error :
crypto.js:562
return binding.PBKDF2(password, salt, iterations, keylen, digest, callback);
^
TypeError: Not a buffer
at TypeError (native)
at pbkdf2 (crypto.js:562:20)
at Object.exports.pbkdf2 (crypto.js:548:10)
at pbkdf2 (/home/ubuntu/workspace/GroupWrites/node_modules/passport-local-mongoose/index.js:56:14)
at InternalFieldObject.ondone (/home/ubuntu/workspace/GroupWrites/node_modules/passport-local-mongoose/index.js:105:9)
[nodemon] app crashed - waiting for file changes before starting...
It was working fine before I implemented a confirm password feature. My form looks like this:
<div class="row">
<h1 style="text-align: center">Create Your Account</h1>
<div style="width: 20%; margin: 25px auto;">
<form action="/register" method="post">
<div class="form-group">
<label>Username</label>
<input class="form-control" type="text" name="username" placeholder="hermioneGranger">
</div>
<div class="form-group">
<label>Email</label>
<input class="form-control" type="text" name="email" placeholder="hermioneGranger#hogwarts.edu">
</div>
<div class="form-group">
<label>Password</label>
<input id="password" class="form-control" type="password" name="password" placeholder="gryffindor3" autocomplete="new-password">
</div>
<div class="form-group">
<label>Confirm Password</label>
<input id="confirm_password" class="form-control" type="password" name="password" placeholder="gryffindor3" autocomplete="new-password">
</div>
<div class="form-group" style="text-align: center">
<button id="button" class="btn btn-lg">Create</button>
</div>
</form>
</div>
</div>
<!--Confirm Password Script-->
<script type="text/javascript">
var password = document.getElementById("password")
, confirm_password = document.getElementById("confirm_password");
function validatePassword(){
if(password.value != confirm_password.value) {
confirm_password.setCustomValidity("Passwords Don't Match");
} else {
confirm_password.setCustomValidity('');
}
}
password.onchange = validatePassword;
confirm_password.onkeyup = validatePassword;
</script>
And my user schema looks like this :
var mongoose = require("mongoose")
var passportLocalMongoose = require("passport-local-mongoose")
var UserSchema = new mongoose.Schema({
username: String,
password: String,
email: String,
subscriptions: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Story"
}
]
})
UserSchema.plugin(passportLocalMongoose)
module.exports = mongoose.model("User", UserSchema)
Please help. Cannot figure this one out. I found out about something called bcrypt and tried to require it in my app.js and get something working but that would not solve my issues. I believe it has something to do with the confirm password script, because before I added it I was making accounts just fine.