passport missing credentials on form post - mysql

I am developing a nodejs express application with MySQL and for the session, authentication, and authorization I am using the passport, I dont know why but when I create the account everything goes fine. User is being created.
But when I login, it returns an error message saying "Missing credentials".
I have already seen every other Stackoverflow question regarding this problem but I haven't found a solution.
app.js
const express = require("express");
const cors = require('cors');
const accountRoute = require("./routes/account");
const app = express();
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.set("view engine","ejs");
app.use(express.static(__dirname + '/views'));
app.use(accountRoute.app)
app.use(accountRoute.router);
app.get("/", (req,res) => {
res.render("index.ejs");
});
app.listen(8000, () => console.log(`Listening on port 8000...`));
Login and Register
const express = require('express');
const session = require('express-session');
const flash = require('express-flash');
const bcrypt = require('bcryptjs');
const passport = require('passport');
const config = require('../config');
const initalizePassport = require('../passport');
const user = require('../models/user').User;
const router = express.Router();
const app = express();
initalizePassport(passport, async (email) => {
return await user.findOne({ where: { "email": email } }) === email;
}, async (id) => {
return await user.findOne({ where: { "id": id } }) === id;
});
app.use(session({
secret: config.sessionPassword,
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
router.get('/login', (req, res) => {
res.render('login.ejs');
});
router.post('/login', passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login',
failureFlash: true
}));
router.get('/register', (req, res) => {
res.render('register.ejs');
});
router.post('/register', async (req, res) => {
try {
const hashedPassword = await bcrypt.hashSync(req.body.userpass, 10);
user.create({
"email": req.body.email,
"username": req.body.username,
"userpass": hashedPassword
});
res.redirect('/login');
} catch (error) {
res.redirect('/register');
}
});
router.get('/unregister', (req, res) => {
res.render('unregister.ejs');
});
router.post('/unregister', (req, res) => {
res.send(req.body);
});
module.exports.router = router;
module.exports.app = app;
passport.js
const LocalStrategy = require('passport-local').Strategy
const bcrypt = require('bcryptjs')
function initialize(passport, getUserByEmail, getUserById) {
const authenticateUser = async (email, userpass, done) => {
const user = getUserByEmail(email);
if (!user) {
return done(null, false, { message: 'No user with that email' })
}
try {
var correctPassword = false;
await bcrypt.compare(userpass, user.userpass, function (err, result) {
if (err) {
console.log(err);
}
else {
correctPassword = true;
console.log("passwords match!");
return;
}
});
if (correctPassword) {
return done(null, user)
} else {
return done(null, false, { message: 'Password incorrect' })
}
} catch (e) {
return done(e)
}
}
passport.use(new LocalStrategy({ usernameField: 'email', passwordField: 'userpass' }, authenticateUser))
passport.serializeUser((user, done) => done(null, user.id))
passport.deserializeUser((id, done) => {
return done(null, getUserById(id))
})
}
module.exports = initialize
Login.ejs
<h1>Login</h1>
<% if(messages.error) { %>
<%= messages.error %>
<% } %>
<form action="/login" method="post">
<input name="email" type="text" placeholder="email">
<input name="userpass" type="password" placeholder="userpass">
<input type="submit" value="submit">
</form>
Now it's throwing me this:
Error: Illegal arguments: string, undefined
at _async (C:\Users\datte\Desktop\auth\node_modules\bcryptjs\dist\bcrypt.js:286:46)
at C:\Users\datte\Desktop\auth\node_modules\bcryptjs\dist\bcrypt.js:307:17
at new Promise (<anonymous>)
at Object.bcrypt.compare (C:\Users\datte\Desktop\auth\node_modules\bcryptjs\dist\bcrypt.js:306:20)
at Strategy.authenticateUser [as _verify] (C:\Users\datte\Desktop\auth\passport.js:13:24)
at Strategy.authenticate (C:\Users\datte\Desktop\auth\node_modules\passport-local\lib\strategy.js:90:12)
at attempt (C:\Users\datte\Desktop\auth\node_modules\passport\lib\middleware\authenticate.js:366:16)
at authenticate (C:\Users\datte\Desktop\auth\node_modules\passport\lib\middleware\authenticate.js:367:7)
at Layer.handle [as handle_request] (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:275:10)
at Function.handle (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:174:3)
at router (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:47:12)
at Layer.handle [as handle_request] (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:317:13)
at C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\datte\Desktop\auth\node_modules\express\lib\router\index.js:275:10)
Executing (default): SELECT `id`, `email`, `username`, `userpass`, `createdAt`, `updatedAt` FROM `Users` AS `User` WHERE `User`.`email` = 'myemail' LIMIT 1;

Related

404 NOT FOUND react and node js

I'm trying to do a post with a form on react, but when i submit for the name, the browser console always show "404 not found localhost:3000/store-data"
Sometimes it works, but in the database the value "name" is "NULL"
i dont know where is the error. so i need some help.
My db:
CREATE TABLE users(
id INT(11) PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(200)
)ENGINE=INNODB;
My Form.js code:
import React from 'react'
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = { name: '' };
}
handleChange = (event) => {
this.setState({[event.target.name]: event.target.value});
}
handleSubmit = (event) => {
alert('A form was submitted: ' + this.state);
fetch('/store-data', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
// We convert the React state to JSON and send it as the POST body
body: JSON.stringify(this.state)
}).then(function(response) {
console.log(response)
return response.json();
});
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} name="name" onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
export default MyForm;
And my server.js code:
const express = require("express");
const bodyParser = require('body-parser');
const cors = require("cors");
const mysql = require('mysql');
const app = express();
app.use(cors());
// parse application/json
app.use(bodyParser.json());
//create database connection
const conn = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'conex'
});
//connect to database
conn.connect((err) => {
if (err) throw err;
console.log('Mysql Connected...');
});
//add new user
app.post('/store-data', (req, res) => {
let data = { name: req.body.name };
let sql = "INSERT INTO users SET ?";
let query = conn.query(sql, data, (err, results) => {
if (err) throw err;
res.send(JSON.stringify({ "status": 200, "error": null, "response": results }));
});
});
app.listen(3000, () => {
console.log("Server running successfully on 3000");
});
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, HEAD');
next();
});
I'm trying to do simple form.

Cannot set headers after they are sent to the client error when add code to redirect another page

I have login page and signup page. when a user want register account and register is successful, I want to redirect him to signin.html page. however, nothing I've tried have worked so far. I always get the error "Cannot set headers after they are sent to the client" when I add this code "res.redirect('http://localhost:3000/signin.html')". here is my code
signup.html
const form = document.getElementById('reg-form')
form.addEventListener('submit', registerUser)
async function registerUser(event){
event.preventDefault()
const username = document.getElementById('user').value
const password = document.getElementById('password').value
const password_confirmation = document.getElementById('password_confirmation').value
const phone = document.getElementById('tel').value
const result = await fetch('/register',{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username,
password,
password_confirmation,
phone
})
}).then((res) => res.json())
if (result.status === 'ok') {
alert('success')
}else {
alert (result.error)
}
}
and here is server.js
const express = require('express')
const path = require ('path')
const mongoose = require ('mongoose')
const User = require ('./model/user')
const bodyParser = require('body-parser')
const bcrypt = require ('bcryptjs')
const jwt = require ('jsonwebtoken')
const JWT_SECRET = 'lkjlfg%nlnkllkj#R%##%#&bgkj3nskk2cnklvdfsflkjlkjf98748'
const port =3000
mongoose.connect('mongodb://localhost:27017/login-app-db', {
useNewUrlParser: true,
useUnifiedTopology: true,
})
const app = express()
app.use('/', express.static(path.join(__dirname, '../code FE/')))
app.use(bodyParser.json())
// app.post('/api/change-password', (req, res) => {
// const { token } = req.body
// const user = jwt.verify(token, JWT_SECRET)
// console.log()
// })
app.post('/signin', async (req, res) => {
const { username, password } = req.body
const user = await User.findOne({ username }).lean()
console.log(password)
if (!user) {
return res.json({status: 'error', error: 'Invalid username/password'})
}
if (await bcrypt.compare('password', user.password)) {
// the username, password combination is successfully
const token = jwt.sign({
id: user._id,
username: user.username
},
JWT_SECRET
)
return res.json({status: 'ok', data: token})
}
return res.json({status: 'error', error: 'Invalid username/password'})
})
app.post('/register', async (req, res) => {
console.log(req.body)
const { username, password: plainTextPassword, password_confirmation: someOtherPlaintextPassword, phone} = req.body
if (!username || typeof username !== 'string') {
return res.json({ status: 'error', error: 'Invalid username'})
}
if (!plainTextPassword || typeof plainTextPassword !== 'string') {
return res.json({ status: 'error', error: 'Invalid password'})
}
const password = await bcrypt.hash('password', 10)
const password_confirmation = await bcrypt.hash('password_confirmation', 10)
try {
const response = await User.create({
username,
password,
password_confirmation,
phone
})
console.log('user created successfully: ', response)
res.redirect('http://localhost:3000/signin.html')
}catch(error){
if (error.code === 11000) {
return res.json({ status: 'error', error: 'username already in use'})
}
throw error
}
res.json({status: 'ok'})
})
app.listen(port, () => {
console.log(`Example app listening on port http://localhost:${port}`)
})

SyntaxError: Unexpected token l in JSON at position

Why do I get this error every time I use the api (POST)
SyntaxError: Unexpected token l in JSON at position 18
at JSON.parse (<anonymous>)
at parse (/Users/.../Desktop/ecommerceapi/node_modules/body-parser/lib/types/json.js:89:19)
at /Users/.../Desktop/ecommerceapi/node_modules/body-parser/lib/read.js:121:18
at invokeCallback (/Users/.../Desktop/ecommerceapi/node_modules/raw-body/index.js:224:16)
at done (/Users/.../Desktop/ecommerceapi/node_modules/raw-body/index.js:213:7)
at IncomingMessage.onEnd (/Users/.../Desktop/ecommerceapi/node_modules/raw-body/index.js:273:7)
at IncomingMessage.emit (node:events:532:35)
at endReadableNT (node:internal/streams/readable:1346:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
This is my entire code: (auth.js)
const router = require("express").Router();
const User = require("../models/User");
const CryptoJS = require("crypto-js");
const jwt = require("jsonwebtoken");
//REGISTER
router.post("/register", async (req, res) => {
const newUser = new User({
username: req.body.username,
email: req.body.email,
password: CryptoJS.AES.encrypt(
req.body.password,
process.env.PASS_SEC
).toString(),
});
try {
const savedUser = await newUser.save();
res.status(201).json(savedUser);
} catch (err) {
res.status(500).json(err);
}
});
//LOGIN
router.post('/login', async (req, res) => {
try{
const user = await User.findOne(
{
userName: req.body.user_name
}
);
!user && res.status(401).json("Wrong User Name");
const hashedPassword = CryptoJS.AES.decrypt(
user.password,
process.env.PASS_SEC
);
const originalPassword = hashedPassword.toString(CryptoJS.enc.Utf8);
const inputPassword = req.body.password;
originalPassword != inputPassword &&
res.status(401).json("Wrong Password");
const accessToken = jwt.sign(
{
id: user._id,
isAdmin: user.isAdmin,
},
process.env.JWT_SEC,
{expiresIn:"3d"}
);
const { password, ...others } = user._doc;
res.status(200).json({...others, accessToken});
}catch(err){
res.status(500).json(err);
}
});
module.exports = router;
I'm using Postman to use the API to POST this
{ "username": sultan "password": 12345qwer }
and this is index.js:
const express = require("express");
const app = express();
mongoose = require("mongoose")
const dotenv = require("dotenv");
const userRoute = require("./routes/user");
const authRoute = require("./routes/auth");
dotenv.config();
mongoose
.connect(process.env.MONGO_URL)
.then(() => console.log("DB Connection Successfull!"))
.catch((err) => {
console.log(err);
});
app.use(express.json());
app.use("/api/auth", authRoute);
app.use("/api/users", userRoute);
app.listen(process.env.PORT || 50, () => {
console.log("Backend server is running!");
});
it should give me the users Info or "Wrong Password" but it gives the above error as a response!
double quotes and comma are missing
{
"username": "sultan",
"password": "12345 qwer"
}

Axios post is giving me an error: Internal server Error

I am doing a post request with Axios and gives me this error:
xhr.js:178 POST http://localhost:3000/dependentes 500 (Internal Server
Error)
I have seen people asking about this but none of their solutions work for me!
I don't know if is something wrong in this component or I have something wrong with the server side.
import React, { Component } from "react";
import axios from "axios";
class LogIn extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: ""
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChangeEmail = this.handleChangeEmail.bind(this);
this.handleChangePass = this.handleChangePass.bind(this);
}
handleChangeEmail = e => {
this.setState({ email: e.target.value });
//console.log(e.target.value);
};
handleChangePass = e => {
this.setState({ password: e.target.value });
//console.log(e.target.value);
};
handleSubmit = e => {
/*this.props.history.push('/');
console.log(this.props);*/
event.preventDefault();
let data = JSON.stringify({
email: this.state.email,
password: this.state.password
});
let url = "http://localhost:3000/dependentes";
const response = axios.post(url, data, {
headers: { "Content-Type": "application/json" }
});
};
render() {
return (
<div className="container">
<form onSubmit={this.handleSubmit} className="white">
<h5 className="grey-text text-darken-3">Log In</h5>
<div className="input-field">
<label htmlFor="email">Email</label>
<input
type="email"
id="email"
onChange={this.handleChangeEmail}
value={this.state.email}
/>
</div>
<div className="input-field">
<label htmlFor="password">Password</label>
<input
type="password"
id="password"
onChange={this.handleChangePass}
/>
</div>
<div className="input-field">
<button className="btn orange lighten-1 z-depth-0">Log In</button>
</div>
</form>
</div>
);
}
}
export default LogIn;
According to your node.js code you are NOT using body-parser that's why getting email from req.body will throw you an error because req.body is undefined.
Also, If you don't return the request like res.send or res.json it will always time out from front end as the request is not closed.
So, to edit your code
//installed express, mysql, cors
const config = require('./database/config');
const express = require('express');
const cors = require('cors');
const port = 4000;
const app = express();
const mysql = require('mysql');
const bodyParser = require('body-parser'); // <=== this line
app.use(cors());
app.use(bodyParser.json()); //<=== This line
const SELECT_ALL_ADDICTS_QUERY = 'SELECT * FROM viciados';
const connection = mysql.createConnection(config.mysql);
connection.connect(err => {
if (err) {
return err;
}
});
app.get('/', (req, res) => {
res.send('Homepage. Go to /dependentes para ver os dependentes no sistema');
res.end();
});
app.get('/dependentes', (req, res) => {
connection.query(SELECT_ALL_ADDICTS_QUERY, (err, results) => {
if (err) {
res.send(err);
} else {
res.json({
data: results
});
}
});
});
app.post('/dependentes', (req, res) => {
console.log(req.body.email);
res.json({ email: req.body.email }); ///<== and this line
});
app.listen(port, err => {
return err
? console.log(`error founded: ${err}`)
: console.log(`server runnning on port: ${port}`);
});

how can i post data from reactjs form to mysql database

How can I send this data to database MySQL from a reactjs form? I'm a beginner in reactjs and I'm tired of trying.
In the back-end I use nodejs, express, and cors, so if u can tell me how because I have to finish this work.
The console returns GET Localhost 404 Not Found.
This is what I do but I don't know there is a better way to make it.
import React, { Component } from 'react'
import { Table,Button,
Modal,ModalHeader,
ModalBody,ModalFooter,
Label,Input,Form } from 'reactstrap';
export default class Db1 extends Component {
state = {
users: [],
newUserData: {
nom: '',
prenom: '',
adresse: '',
email: ''
},
newUserModal:false,
}
componentDidMount() {
this.getUsers();
}
getUsers = () => {
fetch('http://localhost:4000/users')
.then(response => response.json())
.then(response => this.setState({ users: response.data}))
.catch(err => console.error(err))
}
addUser = () => {
let { nom,prenom,adresse,email } = this.state.newUserData;
fetch(`http://localhost:4000/users/add?
nom=${nom}&prenom=${prenom}&adresse=${adresse}&email=${email}`,{
method: 'POST',
body: JSON.stringify({
nom: this.nom,
prenom: this.prenom,
adresse: this.adresse,
email: this.email
}),
headers: {"Content-Type": "application/json"}
})
.then(this.getUsers)
.catch(err => console.error(err))
this.setState({newUserModal:false});
console.log(this.newUserData) // return undefined
}
toggleNewUserModal = () => {
this.setState({
newUserModal: ! this.state.newUserModal
});
}
const express = require('express');
const cors = require('cors');
const mysql = require('mysql');
const bodyParser = require('body-parser')
const app = express();
// Connection Mysql
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'dbusers',
});
connection.connect(err => {
if (err) {
console.log("conection error");
return err;
}
});
// Connection Express Body-Parser Cors
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.send('Hello from the users server')
});
// Selectionner Tous Les Utilisateurs
app.get('/users', (req, res) => {
const selectQuery = 'SELECT * FROM userslist';
connection.query(selectQuery, (err, results) => {
if(err) {
res.send(err)
}
else {
res.json({data: results})
}
});
});
// Ajouter Un Nouveau Utilisateur
app.post('/users/add', (req, res) => {
let nom = req.body.nom;
let prenom = req.body.prenom;
let adresse = req.body.adresse;
let email = req.body.email;
let insertQuery ="INSERT INTO userslist SET ?"
const user={nom,adresse,prenom,email}
connection.query(insertQuery,user, (err, results) => {
if(err) {
console.log("insert error");
res.send(err)
}
else {
res.send({ error: false, data: results, message: 'user has been
updated successfully.' });
}
});
});
// Editer Un Nouveau Utilisateur
app.post('/users/update/:id', (req, res) => {
let id = req.params.id;
let nom = req.body.nom;
let prenom = req.body.prenom;
let adresse = req.body.adresse;
let email = req.body.email;
let updateQuery =`UPDATE userslist SET ? WHERE id=${id}`
const user={nom,adresse,prenom,email}
connection.query(updateQuery,user, (err, results) => {
if(err) {
console.log("insert error");
res.send(err)
}
else {
res.send({ error: false, data: results, message: 'user has been
updated successfully.' });
}
});
});
// Suprimer un Utilisateur
app.post("/users/delete/:id", (req, res) => {
let id = req.params.id;
let sql = 'DELETE FROM userslist WHERE id=?';
connection.query(sql, [id], (error, results, fields) => {
if (error)
console.error(error.message);
console.log("Deleted Row(s):", results.affectedRows);
res.json({error:false,data: results})
});
});
app.listen(4000, () => {
console.log('Users server worked on port 4000...')
});