Javascript :Connect to login form with an API doesn't run - javascript

I use javascript to connect to a login. I put console.log on the password and the email and apparently it recovers the password well but not the email and I don't see where the problem comes from. I checked my email Id in the HTML and javascript code and nothing. Can you help me ? And tell me what's wrong with my code. Thank you and good day
I changed getElementById by querySelector but nothing. My email Id is well written however everywhere. Here is the HTML
<form class="form" action="#" method="post">
<h3>Log In</h3>
<div class="input">
<label for="email">Email</label>
<input type="email" placeholder="Email" id="email">
<label for="password">Mot de passe</label>
<input type="password" placeholder="Mot de passe" id="password">
<input type="submit" value="Se connecter" id="submit">
<p id="errorMessage"></p>
<a class="link" href="#" >Mot de passe oublié</a>
<p id="erreur"></p>
</div>
</form>
Here is the javascript code
const submit = document.getElementById("submit");
const errorMessage = document.getElementById("errorMessage");
submit.addEventListener("click", (e) => {
e.preventDefault();
const email = document.querySelector("#email").value;
const password = document.querySelector("#password").value;
console.log("email: ", email);
console.log("password: ", password);
if (!email || !password) {
document.getElementById("errorMessage").innerHTML = "Veuillez remplir tous les champs";
return;
}
fetch("http://localhost:5678/api/users/login", {
method: "POST",
headers: {
accept: "application/json",
"Content-type": "application/json",
},
body: JSON.stringify({email: email, password: password}),
})
.then(authResponse => {
console.log("authResponse: ", authResponse);
if (authResponse.status === 200) {
return authResponse.json();
}
else if (authResponse.status === 401) {
errorMessage.textcontent = "Accès non autrorisé";
}
else if (authResponse.status === 404) {
errorMessage.textcontent = "Utilisateur non trouvé";
} else {
errorMessage.textcontent = `Error: ${authResponse.status}`;
}
})
.then(userData => {
console.log("userData: ", userData);
if (userData) {
window.localStorage.setItem("userData", JSON.stringify(userData));
window.location.replace = "admin.html";
}
})
.catch(error => console.error(error));
});
Here is a screenshot of console :
enter image description here

Replace: const submit = document.getElementById("submit"); by: const submit = document.querySelector(".form");
And
submit.addEventListener("click", (e) => { by: submit.addEventListener("submit", (e) => {
Here is the full JS:
const submit = document.querySelector(".form");
const errorMessage = document.getElementById("errorMessage");
submit.addEventListener("submit", (e) => {
e.preventDefault();
const email = document.querySelector("#email").value;
const password = document.querySelector("#password").value;
console.log("email: ", email);
console.log("password: ", password);
if (!email || !password) {
document.getElementById("errorMessage").innerHTML = "Veuillez remplir tous les champs";
return;
}
fetch("http://localhost:5678/api/users/login", {
method: "POST",
headers: {
accept: "application/json",
"Content-type": "application/json",
},
body: JSON.stringify({email: email, password: password}),
})
.then(authResponse => {
console.log("authResponse: ", authResponse);
if (authResponse.status === 200) {
return authResponse.json();
}
else if (authResponse.status === 401) {
errorMessage.textcontent = "Accès non autrorisé";
}
else if (authResponse.status === 404) {
errorMessage.textcontent = "Utilisateur non trouvé";
} else {
errorMessage.textcontent = `Error: ${authResponse.status}`;
}
})
.then(userData => {
console.log("userData: ", userData);
if (userData) {
window.localStorage.setItem("userData", JSON.stringify(userData));
window.location.replace = "admin.html";
}
})
.catch(error => console.error(error));
});
https://codepen.io/Echyzen/pen/xxJaVzE

Related

Allowing users to Login, and show a message whether it was successful or not, without going through the registration process

I recently created a web application for login and registration, however I ran into a difficulty. In order to enable users to login or register, I've created a few endpoints using express.js. If a user tries to register an account that already exists in the database, an error message stating "User already exists" will be displayed. If not, the user will be able to create an account and login successfully. However, if I launch the app without first registering a new user, I am unable to log in. For instance, if I try to register an existing user who is already listed in the database, it informs me that the user already exists there before allowing me to log in, but if I try to log in first, nothing happens, so I can't login without going through the registration process. " so, I have added some fake data manually to my database and I try to access them with the login process but it won't work as I have not registered a user using the register process." Any idea of how to fix this problem?
Frontend:
import React, { useState, useEffect } from "react";
import axios from 'axios';
function Login2() {
const [form, setForm] = useState({
username: '',
email: '',
password: '',
});
const [mode, setMode] = useState('login');
const [errors, setErrors] = useState({});
const [message, setMessage] = useState('');
const handleChange = (e) => {
setForm({
...form,
[e.target.name]: e.target.value,
});
};
const validateInfo = (form) => {
let errors = {};
if (!form.username.trim()) {
errors.username = 'Username is required!';
}
if (!form.email) {
errors.email = 'Email is required!';
} else if (!/\S+#\S+\.\S+/.test(form.email)) {
errors.email = 'Email address is invalid';
}
if (!form.password) {
errors.password = 'Password is required';
} else if (form.password.length < 6) {
errors.password = 'Password must be at least 6 characters long!';
}
return errors;
};
const handleSubmit = (e) => {
e.preventDefault();
const errors = validateInfo(form);
setErrors(errors);
if (Object.keys(errors).length === 0) {
if (mode === 'login') {
axios.post('http://localhost:4000/login', form)
.then((response) => {
if (response.data === 'Logged in successfully') {
setMessage('Logged in successfully');
window.location.href = '/';
} else {
setMessage('Login was unsuccessful');
}
})
.catch((error) => {
setMessage(error.message);
});
} else {
axios.get(`http://localhost:4000/checkUser/${form.username}`)
.then((response) => {
if (response.data === 'User exists') {
setMessage('User already exists');
return;
} else {
axios.post('http://localhost:4000/register', form)
.then((response) => {
setMessage(response.data);
})
.catch((error) => {
setMessage(error.message);
});
}
})
.catch((error) => {
setMessage(error.message);
});
}
}
};
return (
<div className="App">
<form onSubmit={handleSubmit}>
<input
type="text"
name="username"
placeholder="Username"
value={form.username}
onChange={handleChange}
/>
{errors.username && <p> {errors.username}</p>}
{mode === 'register' && (
<>
<input
type="email"
name="email"
placeholder="Email"
value={form.email}
onChange={handleChange}
/>
{errors.email && <p> {errors.email}</p>}
</>
)}
<input
type="password"
name="password"
placeholder="Password"
value={form.password}
onChange={handleChange}
/>
{errors.password && <p> {errors.password}</p>}
<button type="submit">
{mode === 'login' ? 'Login' : 'Register'}
</button>
<button type="button" onClick={() => setMode(mode === 'login' ? 'register' : 'login')}>
Switch to {mode === 'login' ? 'Register' : 'Login'}
</button>
</form>
{message && <p>{message}</p>}
</div>
);
};
export default Login2;
Backend:
const express = require('express');
const app = express();
const cors = require('cors');
const mysql = require('mysql2');
const connection = mysql.createConnection({
host: "??",
user: "??",
password: "??",
database: "??",
});
app.use(cors({
origin: 'http://localhost:3000'
}))
app.use(express.json());
app.get('/checkUser/:username', (req, res) => {
const query = `SELECT * FROM userTable WHERE username = '${req.params.username}'`;
connection.query(query, (error, results) => {
if (error) {
return res.status(500).send(error);
}
if (results.length > 0) {
return res.send('User exists');
}
return res.send('User does not exist');
});
});
app.post('/register', (req, res) => {
const { username, email, password } = req.body;
const reg = `INSERT INTO userTable (username, email, password) VALUES (?,?,?)`;
connection.query(reg, [username, email, password], (error) => {
if (error) throw error;
res.send('User registered successfully');
});
});
app.post('/login', (req, res) => {
const { username, password } = req.body;
const log = `SELECT * FROM userTable WHERE username = ? AND password = ?`;
connection.query(log, [username, password], (error, results) => {
if (error) throw error;
if (results.length > 0) {
return res.send('Logged in successfully');
} else {
return res.send('Login was unsuccessful');
}
});
});
app.listen(4000, () => {
console.log('Server listening on port 4000');
});
So the exact problem is how I can login without going through the registration process.
Note:
I'm using MYSQL database, node.js, express server, Cors and axios to make the http requests.

amazon-cognito-identity-js setupMFA problems

I am attempting to setup MFA for users after they reset their passcode. The code runs smoothly until I hit mfaSetup, specifically the line user.associateSoftwareToken(). When I pass in 'this' instead of user, I get the following error:
Uncaught (in promise) TypeError: callback is undefined
When I pass in user I get Uncaught (in promise) TypeError: callback.onFailure is not a function
I am truly at a loss of what to do and would appreciate any help.
Code below:
const onSubmit = (event) => {
event.preventDefault();
const authDetails = new AuthenticationDetails({
Username: email,
Password: password
});
const user = new CognitoUser({
Username: email,
Pool: UserPool
});
user.authenticateUser(authDetails, {
onSuccess: (data) => {
console.log('onSuccess:', data);
if (location.pathname === '/') {
// navigate('dashboard');
}
},
onFailure: (err) => {
console.error('onFailure:', err);
},
newPasswordRequired: (data) => {
console.log(data);
setNewPasscodeRequired(true);
},
mfaRequired: (data) => {
console.log('mfa required');
},
mfaSetup: (challengeName, challengeParameters) => {
console.log('in mfa setup');
console.log(user.Session);
user.associateSoftwareToken(user, {
onFailure: (err) => {
console.error('onFailure', err);
},
onSuccess: (result) => {
console.log(result);
}
});
},
selectMFAType: (challengeName, challengeParameters) => {
console.log(challengeName, challengeParameters);
user.sendMFASelectionAnswer('SOFTWARE_TOKEN_MFA', this);
},
totpRequired: (secretCode) => {
console.log(secretCode);
const challengeAnswer = prompt('Please input the TOTP code.', '');
user.sendMFACode(challengeAnswer, this, 'SOFTWARE_TOKEN_MFA');
},
associateSecretCode: (secretCode) => {
const challengeAnswer = prompt('Please input the TOTP code.', '');
user.verifySoftwareToken(challengeAnswer, 'My TOTP device', this);
}
});
};
const onSubmitPasscode = (event) => {
event.preventDefault();
if (passwordFirst !== passwordSecond) {
alert('the two inputs provided are not the same');
} else {
const user = new CognitoUser({
Username: email,
Pool: UserPool
});
const authDetails = new AuthenticationDetails({
Username: email,
Password: password
});
user.authenticateUser(authDetails, {
onFailure: (err) => {
console.error('onFailure:', err);
},
onSuccess: (result) => {
console.log(result);
},
newPasswordRequired: (userAttributes, requiredAttributes) => {
console.log(userAttributes);
console.log(requiredAttributes);
delete userAttributes.email_verified;
delete userAttributes.phone_number_verified;
delete userAttributes.phone_number;
console.log(userAttributes);
user.completeNewPasswordChallenge(passwordFirst, userAttributes, {
onFailure: (err) => {
console.error('onFailure:', err);
},
onSuccess: (result) => {
console.log('call result: ', result);
},
mfaSetup: (challengeName, challengeParameters) => {
console.log('in mfa setup');
console.log(user.Session);
user.associateSoftwareToken(this, {
onFailure: (err) => {
console.error('onFailure', err);
},
onSuccess: (result) => {
console.log(result);
}
});
},
selectMFAType: (challengeName, challengeParameters) => {
console.log(challengeName, challengeParameters);
user.sendMFASelectionAnswer('SOFTWARE_TOKEN_MFA', this);
},
totpRequired: (secretCode) => {
console.log(secretCode);
const challengeAnswer = prompt('Please input the TOTP code.', '');
user.sendMFACode(challengeAnswer, this, 'SOFTWARE_TOKEN_MFA');
},
associateSecretCode: (secretCode) => {
const challengeAnswer = prompt('Please input the TOTP code.', '');
user.verifySoftwareToken(challengeAnswer, 'My TOTP device', this);
}
});
}
});
}
};
const onMFASetup = () => {
const user = new CognitoUser({
Username: email,
Pool: UserPool
});
const authDetails = new AuthenticationDetails({
Username: email,
Password: passwordFirst
});
console.log(email);
console.log(passwordFirst);
user.authenticateUser(authDetails, {
onFailure: (err) => {
console.error('onFailure:', err);
},
onSuccess: (result) => {
console.log(result);
},
mfaSetup: (challengeName, challengeParameters) => {
user.associateSoftwareToken(this);
},
selectMFAType: (challengeName, challengeParameters) => {
user.sendMFASelectionAnswer('SOFTWARE_TOKEN_MFA', this);
},
totpRequired: (secretCode) => {
const challengeAnswer = prompt('Please input the TOTP code.', '');
user.sendMFACode(challengeAnswer, this, 'SOFTWARE_TOKEN_MFA');
},
mfaRequired: (codeDeliveryDetails) => {
const verificationCode = prompt('Please input verification code', '');
user.sendMFACode(verificationCode, this);
}
});
};
const sendVerificationPin = (event) => {
event.preventDefault();
const user = new CognitoUser({
Username: email,
Pool: UserPool
});
user.forgotPassword({
onSuccess: (result) => {
console.log('call result: ', result);
},
onFailure: (err) => {
alert(err);
}
});
};
const onResetPassword = (event) => {
event.preventDefault();
console.log('in reset');
const user = new CognitoUser({
Username: email,
Pool: UserPool
});
console.log('user made');
if (passwordFirst !== passwordSecond) {
alert('the two inputs provided are not the same');
} else {
console.log('inputs are the same');
user.confirmPassword(pin, passwordSecond, {
onSuccess() {
console.log('Password confirmed!');
window.location.reload(true);
},
onFailure(err) {
console.log('Password not confirmed!');
console.log(err);
}
});
}
};
return (
<div>
{!newPasscodeRequired && !forgotPassword && !setupMFA && (
<div>
<form onSubmit={onSubmit}>
<input type="text" required value={email} onChange={(e) => setEmail(e.target.value)} />
<input
type="text"
required
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<button type="submit">Login</button>
</form>
<button onClick={(e) => setForgotPassword(true)}>
<Typography sx={{ paddingX: 5 }}>Forgot password?</Typography>
</button>
</div>
)}
{newPasscodeRequired && (
<div>
<form onSubmit={onSubmitPasscode}>
<Typography>New Password</Typography>
<input type="text" required onChange={(e) => setPasswordFirst(e.target.value)} />
<Typography>New Password Again</Typography>
<input type="text" required onChange={(e) => setPasswordSecond(e.target.value)} />
<Typography>New Password Requirements</Typography>
<Typography>
At least 8 characters long, requiring upper and lower case letters, numbers, and
special characters
</Typography>
<button type="submit">Submit new passcode</button>
</form>
</div>
)}
{forgotPassword && !newPasscodeRequired && (
<div>
<form onSubmit={sendVerificationPin}>
<Typography>Please input the email for the account</Typography>
<input type="text" required onChange={(e) => setEmail(e.target.value)} />
<button type="submit">Send verification pin</button>
</form>
<form onSubmit={onResetPassword}>
<Typography>Input the verification pin sent to your email below</Typography>
<input type="text" required onChange={(e) => setPin(e.target.value)} />
<Typography>New Password</Typography>
<input type="text" required onChange={(e) => setPasswordFirst(e.target.value)} />
<Typography>New Password Again</Typography>
<input type="text" required onChange={(e) => setPasswordSecond(e.target.value)} />
<Typography>New Password Requirements</Typography>
<Typography>
At least 8 characters long, requiring upper and lower case letters, numbers, and
special characters
</Typography>
<button type="submit">Reset Password</button>
</form>
</div>
)}
{setupMFA && (
<div>
<div>SetupMFA</div>
<button onClick={(e) => onMFASetup()}>Generate QR Code</button>
</div>
)}
</div>
);
};
have you tried this:
cognitoUser.associateSoftwareToken({
onFailure : (error)=>{
console.error(error);
},
associateSecretCode:(code)=>{
console.debug(code);
}
});

i am leraning ejs and my variable in ejs file is giving error

i am leraning ejs and variable to add dynamic data in following code is KindofDay and on running server it is giving error KindOfDay is not defined. I want to add data on basis of app.js on to my ejs file but it is producing the error
<body>
<h1>register</h1>
<form action="/api/register" method="POST">
<input type="text" name="email" id="email" placeholder="enter email" /><br />
<input
type="password"
name="password"
id="password"
placeholder="enter password"
/><br />
<button type="submit">register</button>
</form>
<p><%=kindOfDay%></p>
login
<script>
const form = document.querySelector('form')
const email = document.querySelector('#email')
const password = document.querySelector('#password')
form.addEventListener("submit", function(e){
e.preventDefault()
fetch("/api/register", {
// Adding method type
method: "POST",
// Adding body or contents to send
body: JSON.stringify({
email: email.value ,
password: password.value ,
}),
// Adding headers to the request
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
// Converting to JSON
.then(response => response.json())
// Displaying results to console
.then(json => console.log(json));
})
</script>
</body>
this is the code which is rendering the ejs file to update the kindOfDay variable
router
.route("/register")
.get((req, res) => {
res.render('register')
})
.post((req, res) => {
console.log([req.body.password, req.body.email]);
const hashPassword = bcrypt.hashSync(req.body.password, 10);
const checkUser = {
email: req.body.email,
password: req.body.password,
};
const { value, error } = validateUser(checkUser);
if (error) {
status = "error"
res.status(404).render('register' ,{kindOfDay : error.message});
} else {
user = users.find((u) => {
if (u.email === req.body.email) {
return u;
}
});
}
if (user) {
res.status(404).json("userexist");
} else {
const newUser = {
email: req.body.email,
password: hashPassword,
};
users.push(newUser);
res.status(200).json("ok");
}
});

How to do a login verification

I am creating a system in nodejs + mongodb but I am having difficulty checking if the email and password match.
this is the function that sends the parameters to the api:
function log(e){
e.preventDefault();
let email = document.querySelector('input[name="email"]').value;
let password = document.querySelector('input[name="password"]').value;
let loginstatus = document.querySelector('#loginstatus');
fetch('http://localhost:3000/userV', { method: 'post', headers: {Accept: 'application/json', 'Content-Type': 'application/json'}, body: JSON.stringify({
email: email,
senha: password
})
}).then((resp) => {
if(resp.status == 200){
}else{
loginstatus.textContent = 'Usuario ou senha incorretos!';
loginstatus.style.color = 'red';
}
}).catch((err) => {
alert("Ouve um erro no servidor.\nErro:"+err);
});}
here is where it should be doing the verification but always returns "yes", what is wrong in my form? would you have another recommended way to do it?
async index(req, res) {
let reqemail = req.params.email;
let reqsenha = req.params.senha;
const users = await Users.find({ email: reqemail });
if(reqsenha == users.senha){
return res.send('yes')
}else{
return res.send('no')
}
}

Postman able to send POST request but not my frontend code

I've been trying to register a user through my vanilla JavaScript front-end, but have been unable to make a POST request that doesn't return a 400 status code. With Postman on the other hand, POST requests work just fine and the user is registered successfully.
This is what is logged when I make POST request:
HTML:
<body>
<form id="signup-form">
<h1>Sign up Form</h1>
<table>
<tr>
<td id="yo">User email: </td>
<td><input type="email" name="email" placeholder="email" /></td>
</tr>
<tr>
<td>Username: </td>
<td><input type="text" name="username" placeholder="username"/></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" placeholder="password" /></td>
</tr>
<tr>
<td>Confirm Password:</td>
<td><input type="password" name="password2" placeholder="password" /></td>
</tr>
<tr>
<td><input type="submit" value="signup";/></td>
</tr>
</table>
</form>
<p>Already have an account? Login </p>
<script src="signup.js"></script>
</body>
This is where I need help as to why it returns a 400 response. Front-end JavaScript:
const form = document.getElementById('signup-form');
form.onsubmit = function(e) {
e.preventDefault();
const email = form.email.value;
const username = form.username.value;
const password = form.password.value;
const password2 = form.password2.value;
const user = {
email,
username,
password,
password2,
}
fetch('http://localhost:4002/api/user/register', {
method: 'POST',
body: JSON.stringify(user),
headers:{
'Content-Type': 'application/json'
}
}).then(res => {
console.log(res);
})
.catch(error => console.error('Error:', error));
form.reset();
}
Back-end code incase needed:
Route
//Register user
router.post('/register', (req, res, next) => {
const { errors, isValid } = validateRegisterInput(req.body);
//Check validation
if (!isValid) {
return res
.status(400)
.json(errors);
}
models.User.findOne({
where: {
email: req.body.email
}
})
.then(user => {
if (user) {
errors.email = 'Email already exists';
errors.username = 'Username already exists';
return res
.status(400)
.json(errors)
} else {
const data = {
email: req.body.email,
password: req.body.password,
username: req.body.username,
};
//Encrypting password
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(data.password, salt, (err, hash) => {
if (err)
throw err;
data.password = hash;
models.User.create(data).then(function(newUser, created) {
if (!newUser) {
return next(null, false);
}
if (newUser) {
return next(null, newUser);
}
})
.then( user => {
res.json(user)
})
.catch((err) => {
console.log(err);
})
})
})
}
})
});
Model
"use strict";
module.exports = function(sequelize, DataTypes){
var User = sequelize.define('User', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER,
},
username: {
type: DataTypes.STRING,
validate: {
len: [2, 20],
msg: 'Username must be between 2 and 20 characters'
}
},
email: DataTypes.STRING,
password: {
type: DataTypes.STRING,
validate: {
len: {
args: [5],
msg: 'Password must be atleast 5 characters'
}
}
}
});
User.associate = function(models) {
//associations can be defined here
}
return User;
};
Validation
const Validator = require('validator');
const isEmpty = require('./is-empty');
module.exports = function validatorRegisterInput(data) {
let errors = {};
data.username = !isEmpty(data.username)
? data.username
: '';
data.email = !isEmpty(data.email)
? data.email
: '';
data.password = !isEmpty(data.password)
? data.password
: '';
data.password2 = !isEmpty(data.password2)
? data.password2
: '';
if (Validator.isEmpty(data.email)) {
errors.email = 'Email field is required';
}
if (!Validator.isEmail(data.email)) {
errors.email = 'Email field is required';
}
if (Validator.isEmpty(data.password)) {
errors.password = 'Password is required';
}
if (!Validator.isLength(data.password, {
min: 5
})) {
errors.password = 'Password must be atleast 5 characters';
}
return {errors, isValid: isEmpty(errors)}
}
Please try changing the content type to application/json in your fetch call. A form submit would post the entire page back to the server in which case the content type you have would work but you are making a fetch call and preventing the default behavior.
fetch('http://localhost:4002/api/user/register', {
method: 'POST', // or 'PUT'
body: JSON.stringify(user), // data can be `string` or {object}!
headers:{
'Content-Type': 'application/json'
}
}).then(res => {
document.getElementById("yo").style.color = "red";
console.log(res);
})
.catch(error => console.error('Error:', error));

Categories

Resources