How to do a login verification - javascript

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')
}
}

Related

Login successful with wrong credentials swagger, nodeJS, JWT

Created a login method but it spits out the token regardless of what is entered in the Userfields
This uses swagger API and I'm trying to develop the frontend and backend
I'm relatively new to nodejs/javascript
Any Help would be appreciated!
login.js
var form = document.getElementById('login')
form.addEventListener('submit', login)
async function login(event) {
event.preventDefault()
const username = document.getElementById('username').value
const password = document.getElementById('password').value
const result = await fetch('/v1/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username,
password
})
}).then((res) => res.json())
if (result.status === 'ok') {
// everythign went fine
console.log('Got the token: ', result.data)
localStorage.setItem('token', result.data)
alert('Login Successful')
return false;
} else {
alert(result.error)
}
}
userController.JS
login: async (req,res)=> {
const { userName, password } = req.body
const existUsername = await userModel.findOne({ userName: req.body.userName, password: req.body.password}).then((existUsername) =>{
if (existUsername){
res.status(400).json({status: 'Failed', message: `User was Not found`, data: null})
return;
}
try{
async() => {
await bcrypt.compare(password, req.body.password) }
// the username, password combination is successful
const token = jwt.sign(
{
id: userModel._id,
userName: userModel.userName
},
JWT_SECRET
)
res.json({ status: 'ok', data: token })
}
catch (e) {
res.status(400).json({status: 'Failed', message: `${e.message}`, data: null})
}
});
},

How to get id from response and verify OTP in Javascript

I am working with simple HTML and JS code to create a OTP verification form and when user submit the email he will receive an otp and to get verified we need to take id from response.
Here is my response JSON:-
{
"createdBy": null,
"createdAt": "2022-08-20 18:31:14",
"lastModifiedBy": null,
"lastModifiedAt": "2022-08-20 18:31:14",
"id": "huuhby667-4124-41e1-7gt6-t7thgfy7t",
"username": null,
"email": "username#gmail.com",
"phoneNumber": null,
"countryCode": null,
"isEmailVerified": false,
}
Here is my Email Code:-
const emailForm = document.getElementById('email-form');
if(!!emailForm) {
emailForm.addEventListener('submit', function(e) {
e.preventDefault();
const email = document.getElementById('email').value;
const response = fetch('api-email-link', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ email: email }),
}).then(function(response){
return response.json()}).then(function(data){
console.log(data)
document.getElementById('verify-modal-background').style.display = "flex";
}).catch(error => console.error('Error:', error))
});
};
Here is My OTP Verification Code:-
const inputOtp = document.getElementById("otp-input-form");
const id = JSON.parse(response.id);
inputOtp.addEventListener('submit', async function (e) {
e.preventDefault();
let inputs = document.getElementsByClassName("otp-input-box");
let referralCodeInput = document.getElementById("referral-input").value;
let getOtpInput = [];
for (let i=0; i<inputs.length; i++) {
getOtpInput.push(inputs[i].value);
}
const data = {
otp: getOtpInput
};
const response = await fetch(`https://otp-verification/api/auth/${id}/register-email`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
body: JSON.stringify(data)
}).catch(e => console.log(e));
I'm trying this but unable to get the ID properly so i can verify this otp for the particular register email.

Getting Request json data in C# in an HttpPost method

Im in the process of converting my nodejs implementation of my backend to c#. I want to get the request body from my client. How do i access the request body in c#. I then want to use the user input from the client to make another api call using the users parameters.
Here is the front end code
class User {
constructor(userData) {
this.user = userData.id;
this.login = userData.login;
this.password = userData.password;
this.email = userData.email;
this.external_user_id = userData.external_user_id;
this.facebook_id = userData.facebook_id;
this.twitter_id = userData.twitter_id;
this.full_name = userData.full_name;
this.phone = userData.phone;
this.website = userData.website;
this.custom_data = userData.custom_data;
this.user_tags = userData.user_tags;
this.avatar = userData.avatar;
this.created_at = userData.created_at;
this.updated_at = userData.updated_at;
this.last_request_at = userData.last_request_at;
//encrypt the password
}
}
export default User;
async signUp(userCredentials) {
let userForm = new User(userCredentials);
fetch("http://localhost:8080/auth/signup", {
method: 'POST',
body: JSON.stringify(userForm),
headers: {
'Content-Type': 'application/json',
}
})
.then(response => {
if (!response.ok) {
throw Error(`Error message: ${response.statusText}`)
}
console.log(response)
return response.json()
})
.then(json => {
console.log(json);
sessionStorage.setItem('session_token', json.session_token)
this.signIn({ login: userForm.login, password: userForm.password });
})
.catch(error => console.log(error))
}
Here is the nodejs implementation
router.post("/signup", async (req, res) => {
let reqBody = req.body;
console.log(reqBody.password);
console.log(req.headers["cb-token"]);
let cbToken = req.headers["cb-token"];
const userObj = {
user: {
login: req.body.login,
password: req.body.password,
email: req.body.email,
full_name: req.body.full_name,
phone: req.body.phone,
website: req.body.website
}
}
console.log(`token in auth route ${res.locals.session_token}`)
fetch("https://api.connectycube.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json",
"CB-Token": res.locals.session_token
},
body: JSON.stringify(userObj)
})
.then(response => {
if (!response.ok) {
throw Error(`Error message: ${response.statusText}`)
}
return response.json()
})
.then(data => {
console.log(data)
const resObj = Object.assign(data, { session_token: res.locals.session_token });
res.status(200).json(resObj);
})
.catch(error => {
console.log(error)
res.status(400).json(error)
})
})

MissingPasswordError: No password given

I can signup users just fine on my website, but when I test it with Postman I get this error:
MissingPasswordError: No password given
I also cannot login because the password/username combination is incorrect, so there's definitely something wrong but I can't for the life of me figure out what.
This is my html input field for the password:
<input type="password" class="input--text" name="password" id="password">
signup.js with my fetch function:
const btnSignup = document.querySelector('.btn').addEventListener('click', function () {
let username = document.querySelector('#username').value;
let password = document.querySelector('#password').value;
let bday = document.querySelector('#bday').value;
fetch('http://localhost:3000/users/signup', {
method: "post",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
'username': username,
'password': password,
'bday': bday
})
}).then(response => {
return response.json();
}).then(json => {
if (json.status === 'success') {
let feedback = document.querySelector('.alert');
feedback.textContent = "Sign up successful!";
feedback.classList.remove('hidden');
}
})
})
And this is my signup function in my auth.js controller:
const signup = async (req, res, next) => {
const username = req.body.username;
const password = req.body.password;
const bday = req.body.bday;
const user = new Users({
username: username
});
/*user.bday = bday;*/
await user.setPassword(password);
await user.save()
.then(result => {
console.log(result.id);
let token = jwt.sign({
id: result._id
}, "{this is a secret}");
res.json({
'status': 'success',
'data': {
'token': token
}
})
}).catch(error => {
res.json({
'status': 'error'
})
});
}
I've added bodyParser, made sure the name for my input fields are correct, ...
Solved! Turns out my code was correct, but I forgot to set the raw body in Postman to JSON (default was text).

Issue with fetch: Getting type error failed to fetch

I'm trying to make a post call to the backend server, but I keep running into this error:
TypeError: Failed to fetch
I've looked over the code a bunch of times but can't seem to find the issue. Here is the code:
async doLogin() {
if(!this.state.email || !this.state.password) {
return
}
this.setState({
buttonDisabled : true
})
try {
let res = await fetch('/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: this.state.email,
password: this.state.password
})
})
console.log(res)
let result = await res.json()
console.log(result)
if(result && result.success) {
UserStores.isLoggedIn = true
UserStores.email = result.email
alert(result.msg)
} else if(result && result.success === false) {
this.resetForm()
alert(result.msg)
}
} catch(e) {
console.log('doLogin error: ', e)
this.resetForm()
}
}
This is an example response payload:
{
"success": true,
"email": "mfultz956#gmail.com",
"msg": "Login Verified!"
}
Login Call - Network Tab
Login Call - Headers
change it to :
let res = await fetch('http://localhost:your_api_server_port/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: this.state.email,
password: this.state.password
})
})

Categories

Resources