Why when I have else statement added like this, the if statement is ignored. I put values that are true and the if statement is ignored the output always is my else code...
$(document).ready(function() {
let userData = [
{
email: 'knorr#live.com',
password: 'ksGuQbzYPpW'
},
{
email: 'rddesign#msn.com',
password: '9Q6urHqy'
},
{
email: 'chaffar#yahoo.ca',
password: '4xaz2pyk'
},
{
email: 'fatelk#mac.com',
password: 'TAePJSb2ACX'
},
{
email: 'luebke#me.com',
password: 'EyFY8uhX'
},
{
email: 'amichalo#mac.com',
password: 'c7muQ6bxcA9QJKS'
},
{
email: 'mallanmba#yahoo.ca',
password: 'NqCGLmGtcFU'
},
{
email: 'isaacson#att.net',
password: 'PMjRGUug7Ff73Kt'
},
{
email: 'aracne#aol.com',
password: 'sBJU7JJR7Qx6f55'
},
{
email: 'boser#comcast.net',
password: 'DMXQRNj7BHZ'
},
{
email: 'gtaylor#verizon.net',
password: 'AbefrKfkbxHbP3u'
},
{
email: 'firstpr#comcast.net',
password: 'PGWPUtcwP'
},
{
email: 'sumdumass#sbcglobal.net',
password: '2DrCpjkk9mm8bjW'
},
{
email: 'campbell#yahoo.com',
password: 'ZmYZgaDq6'
},
{
email: 'wetter#me.com',
password: 'ppTG3pGAe'
},
{
email: 'british#verizon.net',
password: '67SbpGYvPJ2'
}
];
$("#loginBtn").on("click", function() {
let email = $("#email").val();
let password = $("#pass").val();
for (let i = 0; i < userData.length; i++) {
if (email === userData[i].email) {
if (password === userData[i].password) {
alert("Match");
} else if (password !== userData[i].password) {
alert("Incorrect Password");
}
break;
} else {
alert("Invalid Login");
}
}
});
});
I think it works, except it doesn't appear that it does. Because the if statement is in the loop, for every element in userData that is incorrect, "Invalid Login" will appear.
Your code doesn't ignore your if statement. It works. You may try something like this:
$(document).ready(function () {
let userData = [{ email: 'admin',
password: '1234'
}, {
email: 'admin2',
password: '12345'
}];
$("#loginBtn").on("click", () => {
let email = $("#email").val();
let password = $("#pass").val();
let pos = userData.map((user) => user.email).indexOf(email);
if (pos !== -1) {
alert((userData[pos].password === password) ? "match"
: "password invalid");
} else { alert("user not found"); }
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="email" type="text"/>
<input id="pass" type="password"/>
<button id="loginBtn">Login</button>
Your code is okay and it works even if it has a lot of security matters. I tested myself and at a certain using a pair email and pass from the array there is a MATCH:
<html>
<body>
<input id="email">
<input id="password">
<button id="sub" type="button">Sbmit</button>
<script>
let userData = [
{
email: 'knorr#live.com',
password: 'ksGuQbzYPpW'
},
{
email: 'rddesign#msn.com',
password: '9Q6urHqy'
},
{
email: 'chaffar#yahoo.ca',
password: '4xaz2pyk'
},
{
email: 'fatelk#mac.com',
password: 'TAePJSb2ACX'
},
{
email: 'luebke#me.com',
password: 'EyFY8uhX'
},
{
email: 'amichalo#mac.com',
password: 'c7muQ6bxcA9QJKS'
},
{
email: 'mallanmba#yahoo.ca',
password: 'NqCGLmGtcFU'
},
{
email: 'isaacson#att.net',
password: 'PMjRGUug7Ff73Kt'
},
{
email: 'aracne#aol.com',
password: 'sBJU7JJR7Qx6f55'
},
{
email: 'boser#comcast.net',
password: 'DMXQRNj7BHZ'
},
{
email: 'gtaylor#verizon.net',
password: 'AbefrKfkbxHbP3u'
},
{
email: 'firstpr#comcast.net',
password: 'PGWPUtcwP'
},
{
email: 'sumdumass#sbcglobal.net',
password: '2DrCpjkk9mm8bjW'
},
{
email: 'campbell#yahoo.com',
password: 'ZmYZgaDq6'
},
{
email: 'wetter#me.com',
password: 'ppTG3pGAe'
},
{
email: 'british#verizon.net',
password: '67SbpGYvPJ2'
}
];
document.getElementById("sub").addEventListener("click", function() {
let email = document.getElementById("email").value;
console.log(typeof email);
let password = document.getElementById("password").value;
for (let i = 0; i < userData.length; i++) {
console.log(typeof userData[i].email);
if (email === userData[i].email) {
if (password === userData[i].password) {
alert("Match");
} else if (password !== userData[i].password) {
alert("Incorrect Password");
}
break;
} else {
alert("Invalid Login");
}
}
});
</script>
</body>
</html>
Related
getting null value as response with 200 status code. i want to see the profile details as response but instead of that showing null value with no error status code in my postman i dont find any error on my code. why it shows like this ? i want to see profile details as response after sending
Router.post
router.post(
'/',
[
auth,
[
check('status', 'Status is required').not().isEmpty(),
check('skills', 'Skills cannot be empty').not().isEmpty(),
],
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const {
company,
website,
location,
bio,
status,
githubusername,
skills,
youtube,
twitter,
instagram,
linkedin,
} = req.body;
const profileFields = {};
profileFields.user = req.user.id;
if (company) profileFields.company = company;
if (website) profileFields.website = website;
if (location) profileFields.location = location;
if (bio) profileFields.bio = bio;
if (status) profileFields.status = status;
if (githubusername) profileFields.githubusername = githubusername;
if (skills) {
profileFields.skills = skills.split(',').map(skill => skill.trim());
}
// creating object for socila links
profileFields.social = {};
if (youtube) profileFields.social.youtube = youtube;
if (twitter) profileFields.social.twitter = twitter;
if (instagram) profileFields.social.instagram = instagram;
if (linkedin) profileFields.social.linkedin = linkedin;
try {
let profile = await Profile.findOne({ user: req.user.id });
if (profile)
//update
profile = await Profile.findOneAndUpdate(
{ user: req.user.id },
{ $set: profileFields },
{ new: true }
);
return res.json(profile);
// create
profile = new Profile(profileFields);
await profile.save();
res.json(profile);
} catch (err) {
console.error(err);
res.status(500).send('server error');
}
}
);
here is profile schema looks like
const ProfileSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'user',
},
company: {
type: String,
},
website: {
type: String,
},
status: {
type: String,
required: true,
},
location: {
type: String,
},
skills: {
type: [String],
required: true,
},
bio: {
type: String,
},
githubusername: {
type: String,
},
experience: [
{
title: {
type: String,
required: true,
},
company: {
type: String,
required: true,
},
location: {
type: String,
},
from: {
type: Date,
required: true,
},
to: {
type: Date,
},
current: {
type: Boolean,
default: false,
},
description: {
type: String,
},
},
],
education: [
{
school: {
type: String,
required: true,
},
degree: {
type: String,
required: true,
},
fieldofstudy: {
type: String,
required: true,
},
from: {
type: Date,
required: true,
},
to: {
type: Date,
},
current: {
type: Boolean,
default: false,
},
description: {
type: String,
},
},
],
social: {
youtube: {
type: String,
},
twitter: {
type: String,
},
linkedin: {
type: String,
},
instagram: {
type: String,
},
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = Profile = mongoose.model('profile',ProfileSchema)
your code logic has problem.
let profile = await Profile.findOne({ user: req.user.id }); if (profile) //update profile = await Profile.findOneAndUpdate( { user: req.user.id }, { $set: profileFields }, { new: true } ); return res.json(profile);
here, if you can't find the record in database, you still return and there is no value so that you got null response. i suggest you remoe the return res.json(profile); into if statement
Back to the basics, the if statement.
if (profile){
//update
profile = await Profile.findOneAndUpdate(
{ user: req.user.id },
{ $set: profileFields },
{ new: true }
);
return res.json(profile);
}
You need to use brackets {}.
In your code, return res.json(profile); gets fired no matter if the response is null or not
the problem is with your syntax you need to add curly braces
if (profile){
//update
profile = await Profile.findOneAndUpdate(
{ user: req.user.id },
{ $set: profileFields },
{ new: true }
)};
I want to take the user input and iterate through my data to check whether it matches or not.
How do I verify if the user entered input matches with my data.
const userInput = document.querySelector(".ID");
const button = document.querySelector(".login");
const data = [
{ userName: "Jon", userId: 1, admin: true },
{ userName: "Mike", userId: 2, admin: false },
{ userName: "Martha", userId: 3, admin: false },
];
function checkUser() {
const id = userInput.value;
data.forEach((user) => {
if (id === user.userId) {
console.log("Welcome");
} else {
console.log("Incorrect ID");
}
});
}
button.addEventListener("click", (e) => {
e.preventDefault();
checkUser();
});
<input class="ID" />
<input type="button" class="login" value="login" />
Input element values are string. For your code to work, you must declare your data.userId as strings.
So it must be:
const data = [
{ userName: "Jon", userId: "1", admin: true },
{ userName: "Mike", userId: "2", admin: false },
{ userName: "Martha", userId: "3", admin: false },
];
If you don't want to use strings as userId, you should change the logical operator of your conditional statement into == instead of === so it would ignore data types.
Please how can I write this Function with Ifs to have a corresponding else statement.
What I'm trying to do is to add an else statement for each of the if statement
Please see my code below.
validate = (lname, fname, email, eid) => {
if (lname) {
this.setState({
validationState: {
...this.state.validationState,
lastname: false,
},
});
}
if (fname) {
this.setState({
validationState: {
...this.state.validationState,
firstname: false,
},
});
}
if (helpers.isEmail(email)) {
this.setState({
validationState: {
...this.state.validationState,
email: false,
},
});
}
if (eid) {
this.setState({
validationState: {
...this.state.validationState,
eid: false,
},
});
}
}
In the following, lname is checked, either the if clause or the else clause are executed, then, regardless of what happened until now, fname is checked, etc.
Is that what you were looking for?
validate = (lname, fname, email, eid) => {
if (lname) {
this.setState({
validationState: {
...this.state.validationState,
lastname: false,
},
});
} else {
....
}
if (fname) {
this.setState({
validationState: {
...this.state.validationState,
firstname: false,
},
});
} else {
....
}
if (helpers.isEmail(email)) {
this.setState({
validationState: {
...this.state.validationState,
email: false,
},
});
} else {
...
}
if (eid) {
this.setState({
validationState: {
...this.state.validationState,
eid: false,
},
});
} else {
...
}
}
i'm using SequelizeJS(MySql) with Passportjs for authentication
when i write
User.find(db.Sequelize.or({ 'username': username }, { 'email': req.body.email }) )
.then((user) => {console.log(user)}
or
User.find({$or:[({ 'username': username }, { 'email': req.body.email })]} )
Generats
Executing (default): SELECT id, name, username, email, password, Picture, role, Description, joinedAt, Social, createdAt, updatedAt FROM Users AS User LIMIT 1;
I don't understand what happen , i'm using or and it generates query with limit 1 !
my user Model
const bcrypt = require('bcrypt-node');
const db = require('../Config/db');
module.exports = function () {
let DataType = db.Sequelize;
let User = db.sequelize.define('User', {
name: { type: DataType.STRING, allowNull: false },
username: { type: DataType.STRING, unique: true, allowNull: false },
email: { type: DataType.STRING, unique: true, allowNull: false, validate: { isEmail: true } },
password: {
type: DataType.STRING, allowNull: false, set: function (pass) {
let newPassword = bcrypt.hashSync(pass);
this.setDataValue('password', newPassword);
}
},
Picture: { type: DataType.STRING, default: '#' },
role: { type: DataType.STRING, default: 'user',allowNull: false },
Description: { type: DataType.TEXT },
joinedAt: { type: DataType.DATE, defaultValue: DataType.NOW },
Social: { type: DataType.TEXT }
}, {
classMethods: {
associate: function (models) {
User.hasMany(models.Post);
}
}
}, {
instanceMethods: {
comparePassword: function (password) {
return bcrypt.compareSync(password, this.password);
}
}
});
return User;
}
There is no function Model.find() in Sequelize, so it looks like you are probably calling Model.findOne() which applies the LIMIT 1 to your query. To find all of the results, you need to use Model.findAll().
You should use the query operator $or, but it needs to be inside a where element with an array of OR values. See an example below.
User.findAll({
where: {
$or: [
username: username,
email: req.body.email,
],
}
})
.then(users => console.log(users));
I'm trying to create a log in window. My code is simple.
var employees = {
'1' : {
firstName: '',
lastName: '',
login: 'qwerty',
password: '12345',
},
'2' : {
login: 'asdfg',
password: '12345',
},
};
app.post('/main', function(req, res) {
if (!req.body) return res.sendStatus(400);
console.log(req.body);
for (var key in employees) {
console.log(key['login']);
console.log(key['password']);
if ((key.login == req.body.login) && (key.password == req.body.password)) {
res.render('main');
} else {
app.get('/', function(req,res) {
res.send(createIndexPage());
});
};
};
});
Why key.login and key.password return undefined?
And why else block does not run when if statement is wrong?
Look at what the value of key actually is:
var employees = {
'1': {
firstName: '',
lastName: '',
login: 'qwerty',
password: '12345',
},
'2': {
login: 'asdfg',
password: '12345',
},
};
for (var key in employees) {
console.log(key);
}
It is the property name (as a string), not the value of the property.
console.log(employees[key]['login']); will give you what you are looking for.