I need to compare user input with set usernames and passwords. For now this is what I came up with:
var sys = {
users: [
{user: 'user1', pass: 'qwerty'},
{user: 'Ragnar', pass: 'lothbrok'},
{user: 'guest', pass: 'guest'}
],
valid: function(){
var userInp = document.getElementById("userInp").value;
// var pwInp = document.getElementById("pwInp").value;
var check = false;
for (var i=0; i < sys.users.length; i++ ){
if (userInp == sys.users.user /*&& apwInp == 'sys.users{pass}'*/) {
alert ("logged in")
} else {
alert ("no match")
}
}
}
}
I need to do it in this specific way and I can't figure it out.
Just to have some clarity, have your username-password combination as a separate object and use the authentication in a different block of code.
//username-password objects
var sys = {
users: [
{user: 'user1', pass: 'qwerty'},
{user: 'Ragnar', pass: 'lothbrok'},
{user: 'guest', pass: 'guest'}
]}
//take your inputs and store them in a variable
var username = document.getElementById("userInp").value;
var password= document.getElementById("passInp").value;
var count = 0;
for(i = 0; i< sys.users.length; i++)
{
if(sys.users[i].user == username && sys.users[i].pass == password)
count++;
}
if(count>0)
alert("correct credentials");
else
alert("incorrect credentials");
You have pretty much in your code already, hope this clears out the rest.
Use Array::some
var sys = {
users: [
{
user: 'user1',
pass: 'qwerty'
},
{
user: 'Ragnar',
pass: 'lothbrok'
},
{
user: 'guest',
pass: 'guest'
}
],
valid: function () {
let username = "Ragnar";
let password = "lothbrok";
return sys.users.some(u => u.user === username && u.pass === password);
}
}
console.log(sys.valid())
Related
app.get("/api/users/:_id/logs", (req, res) => {
const id = req.params._id;
const { from, to, limit } = req.query;
** Here I tried to search for the matched user and it works successfully: **
User.findById({ _id: id }, (err, user) => {
if (!user || err) {
res.send("Unknown User Id !!");
} else {
**Then I tried to filter the log array with date **
// const username = user.username;
let responObject = {};
if (from) {
responObject["$gte"] = new Date(from).toDateString();
}
if (to) {
responObject["$lte"] = new Date(to).toDateString();
}
let filter = {
_id: id,
};
if (from || to) {
filter.date = responObject;
}
let nonNullLimit = limit ?? 500;
**try to build the array log and return it to the user but it always be empty and never return the exercises for the user **
Exercise.find(filter)
.limit(+nonNullLimit)
.exec((err, data) => {
if (err || !data) {
res.json([]);
} else {
const count = data.length;
const rowLog = data;
const { username, _id } = user;
const log = rowLog.map((item) => ({
description: item.description,
duration: item.duration,
date: new Date(item.date).toDateString(),
}));
console.log(log)
if (from && to) {
res.json({
username,
from: new Date(from).toDateString(),
to: new Date(to).toDateString(),
count,
_id,
log,
});
} else {
res.json({
username,
count,
_id,
log,
});
}
}
});
}
});
});
this is the result when I try to log all the exercises for the user
{"username":"ahmed","count":0,"_id":"62a9aab2743ddfc9df5165f2","log":[]}
I wrote a function in javascript expression to check if the result is true or false but i am always getting undefined error
var array = [{
email: 'usman#gmail.com',
password: '123'
},
{
email: 'ali#gmail.com',
password: '123'
}
];
let main = function(email, password) {
return array.forEach((row) => {
if (row.email === email && row.password === password) {
return true
} else {
return false
}
});
};
var checkLogin = main('usman#gmail.com', '123');
console.log(checkLogin)
checkLogin always return undefined
It's because forEach does not return anything. You can use simple for-loop, like this:
var array = [
{email: 'usman#gmail.com', password: '123'},
{email: 'ali#gmail.com', password: '123'}
];
let main = function(email, password) {
for (var i = 0; i < array.length; i++) {
var row = array[i];
if (row.email === email && row.password === password) {
return true
}
}
return false;
};
var checkLogin = main('usman#gmail.com', '123');
console.log(checkLogin)
Also, take a look at some(), includes(), find() and findIndex()
The forEach array function doesn't return anything. If you touch looped array inside it then you are able to modify existing array without copying it.
there's a problem with foreach. it doesn't return anything
var array = [
{email: 'mike#gmail.com', password: '123'},
];
let main = function(email, password) {
for (var i = 0; i < array.length; i++) {
if (array[i].email === email && array[i].password === password) {
return true
}
};
return false
};
var checkLogin = main('mike#gmail.com', '123');
console.log(checkLogin) // returns true
there is something wrong with this logic:
return array.forEach((row) => {
if (row.email === email && row.password === password) {
return true
} else {
return false
}
});
without this logic it returns anything you want
You could take Array#some and return the result of the check.
var array = [{ email: 'ali#gmail.com', password: '123' }, { email: 'usman#gmail.com', password: '123' }];
let main = (email, password) =>
array.some(row => row.email === email && row.password === password);
var checkLogin = main('usman#gmail.com', '123');
console.log(checkLogin)
For, an user verification now I hardcoded the username and password directly on my code. But I want this dynamically using database username and password. As, i'm new to hapi.js it seems quite difficult for me. This is my code :
app.js
const auth = require('hapi-auth-basic');
const hapi = require('hapi');
mongoose.connect('mongodb://localhost:27017/db', {
useNewUrlParser: true }, (err) => {
if (!err) { console.log('Succeeded.') }
else { console.log(`Error`)}
});
const StudentModel = mongoose.model('Student', {
username: String,
password: String
});
const user = {
name: 'jon',
password: '123'
};
const validate = async (request, username, password, h) => {
let isValid = username === user.name && password === user.password;
return {
isValid: isValid,
credentials: {
name: user.name
}
};
};
const init = async () => {
await server.register(auth);
server.auth.strategy('simple', 'basic', {validate});
server.auth.default('simple');
server.route({
method: 'GET',
path: '/',
handler: async (request, h) => {
return 'welcome';
}
});
}
I tried to do this by changing the validate as below :
const validate = async (request, username, password, h) => {
let isValid = username === request.payload.name && password === request.payload.password;
return {
isValid: isValid,
credentials: {
name: request.payload.name
}
};
};
but i got the type error "name" as it's natural. How can I modify this?
Here, fetch user and check in the validation method
const validate = async (request, username, password, h) => {
// fetch user here
const user = await StudentModel.findOne({username, password}).exec();
// user doesn't exist
if(!user) return {isValid: false}
// just make sure here user really exists
return {
isValid: true,
credentials: {
name: user.name
}
}
}
I was writing a MEAN stack application when I came across a rather peculiar error that I don't quite understand.
One of the functions I wrote should return a regular JSON object with certain parameters that will be set in the execution of the function. However, that is not what happens. It instead returns a promise object.
I created a user model, and then created some methods/functions for it. The function in question that returns a promise is the validate function.
What this function does is simply that it makes sure that the data the user entered is in check! You can tell from the code in user.js that it merely checks the length of the input data as well as match it to some predefined regular expressions to see if the data is within acceptable limits (in order not to cause problems later).
I call this function when a user registers which happens in the register function in registerController.js which also should find if the user already exists (has created an account before) or if the username he chose is taken (username exists) after that it sends them a confirmation email containing a link that is their temporaryToken. The route that leads the user to register is in registerRoutes.js. I tried logging the value of the objects received from the functions checkData and validate. checkData returns a normal object while validate returns a promise even though it shouldn't.
Here is the user file user.js
const mongoose = require('mongoose');
var userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true
},
email:{
type: String,
required: true,
unique: true
},
password:{
type: String,
required: true
},
firstName:{
type: String,
required: true
},
lastName:{
type: String,
required: true
},
confirmed:{
type: Boolean,
default:false,
required: true
},
temporaryToken:{
type: String,
default: "NO_TOKEN",
required: true
}
});
userSchema.method({
checkData: function() {
let checkData = {};
checkData.missing = [];
checkData.wrongType = [];
checkData.success = true;
if(!this.username)
{
checkData.success = false;
checkData.missing.push("username");
}
if(!this.email)
{
checkData.success = false;
checkData.missing.push("email");
}
if(!this.password)
{
checkData.success = false;
checkData.missing.push("password");
}
if(!this.firstName)
{
checkData.success = false;
checkData.missing.push("firstName");
}
if(!this.lastName)
{
checkData.success = false;
checkData.missing.push("lastName");
}
return checkData;
},
validate: function() {
let validation = {};
validation.errors = [];
validation.success = true;
if(this.username.length < 2 || this.username.length > 35)
{
validation.success = false;
validation.errors.push({
"field": "username",
"message": "Invalid length of username. Username must be between 2 and 35 characters long."
});
}
if(this.email.length < 6 || this.username.length > 256)
{
validation.success = false;
validation.errors.push({
"field": "email",
"message": "Invalid length of email. Email must be between 6 and 256 characters long."
});
}
if(this.password.length < 8 || this.password.length > 50)
{
validation.success = false;
validation.errors.push({
"field": "password",
"message": "Invalid length of password. Password must be between 6 and 256 characters long."
});
}
if(this.firstName.length < 2 || this.firstName.length > 35)
{
validation.success = false;
validation.errors.push({
"field": "firstName",
"message": "Invalid length of first name. First name must be between 2 and 35 characters long."
});
}
if(this.lastName.length < 2 || this.lastName.length > 35)
{
validation.success = false;
validation.errors.push({
"field": "lastName",
"message": "Invalid length of last name. Last name must be between 2 and 35 characters long."
});
}
let usernameRegex = /^[a-zA-Z0-9$##%`'"\.]+$/
if(!usernameRegex.test(this.username))
{
validation.success = false;
validation.errors.push({
"field": "username",
"message": "Invalid format of username. Username can only contain Alphanumeric characters and $ # # % ` ' \" and .."
});
}
let emailRegex = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if(!emailRegex.test(this.email))
{
validation.success = false;
validation.errors.push({
"field": "email",
"message": "Invalid format and email. Email has to be in the form example#domain.com."
})
}
let passwordRegex = /^[A-Za-z0-9$##%`'"\.]+$/;
if(!passwordRegex.test(this.password))
{
validation.success = false;
validation.errors.push({
"field": "email",
"message": "Invalid format of password. Password an only contain Alphanumeric characters and $ # # % ` ' \" and .."
});
}
let nameRegex = /^[A-Z][a-z-]+$/;
if(!nameRegex.test(this.firstName))
{
validation.success = false;
validation.errors.push({
"field": "firstName",
"message": "Invalid format of first name. First Name can only contain English letters and hyphens (-)."
});
}
if(!nameRegex.test(this.middleName))
{
validation.success = false;
validation.errors.push({
"field": "middleName",
"message": "Invalid format of middle name. Middle Name can only contain English letters and hyphens (-)."
});
}
if(!nameRegex.test(this.lastName))
{
validation.success = false;
validation.errors.push({
"field": "lastName",
"message": "Invalid format of last name. Last Name can only contain English letters and hyphens (-)."
});
}
return validation;
},
capitalizeNames: function() {
this.firstName = this.firstName.charAt(0).toUpperCase() + this.firstName.slice(1);
this.lastName = this.lastName.charAt(0).toUpperCase() + this.lastName.slice(1);
}
});
const UserModel = mongoose.model("user", userSchema);
module.exports = UserModel;
Here is the register controller file registerController.js
const User = require("../model/user.js");
const system = require("../middleware/system.js");
const mails = require("../../config/mails.js");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const nodemailer = require('nodemailer');
let registerController = {
register: function(req, res, next) {
let newUser = new User ({
"username": req.body.username,
"email": req.body.email,
"password": req.body.password,
"firstName": req.body.firstName,
"lastName": req.body.lastName,
});
let check = newUser.checkData();
if(!check.success)
{
res.status(400).json(check);
next();
return;
}
newUser.capitalizeNames();
let validity = newUser.validate();
console.log(validity); // "Promise { <pending> }"
if(!validity.success)
{
res.status(400).json(validity);
next();
return;
}
newUser.findOne({"username": newUser.username}, function(err, foundUser1) {
if(err)
{
system.handleServerError(res);
next();
return;
}
if(foundUser1)
{
res.status(403).json({
"success": false,
"message": "The user with the name " + newUser.username + " already exists. Please choose another name."
});
next();
return;
}
newUser.findOne({"email": newUser.email}, function(err, foundUser2) {
if(err)
{
system.handleServerError(res);
next();
return;
}
if(foundUser2)
{
res.status(403).json({
"success": false,
"message": "The user with the email " + newUser.email + " already exists. If you already have an account, please log in."
});
next();
return;
}
bcrypt.hash(newUser.password, saltRounds, function(err, hash) {
newUser.password = hash;
newUser.temporaryToken = jwt.sign({
"email": newUser.email
}, "confirm", {
expiresIn: 60*60*24*365
});
newUser.save(function(err, product, numAffected) {
if(err)
{
system.handleServerError(res);
next();
return;
}
// SEND EMAIL TO USER
res.status(200).json({
"success": true,
"message": "Your registration has been completed successfully. A confirmation link has been sent to your email. Please use that link to actvate your account and login."
});
next();
return;
});
});
});
});
}
};
module.exports = registerController;
Here is the routes file registerRoutes.js
const express = require("express");
const router = express.Router();
const registerController = require("../controllers/registerController.js")
router.post("/api/register", registerController.register);
module.exports = router;
Please tell me if there is anything other information that I can provide or clarify. And thank you all for your time. :)
The error is in the naming of the function.
validate() is already defined in the mongoose module. Calling it on an instance of the user model called the native mongoose function that expected a callback, and therefore returned a promise.
Thankfully, changing validate() to validator() solved the problem.
I am trying to push array of objects into MongoDB through NodeJS.
So my schema
var UserSchema = new mongoose.Schema({
id: mongoose.Schema.ObjectId,
added: {
type: Date,
default: Date.now()
},
displayName: String,
login: String,
email: String,
phone: String,
password: String,
salt: String,
role: Number,
hasPremium: Boolean,
avatar: Buffer,
description: String,
additional: [{
name: String,
data: String
}],
cart: [{
exposition: Object,
offer: Object,
state: Number,
history: [{
date: Date,
state: Number,
modifier: Number
}]
}],
balance: Number,
topUps: [{
orderNumber: String,
sum: Number,
added: Date,
paid: Date
}],
lock: Boolean
});
My save controller
module.exports = function (passport) {
passport.use('signup', new LocalStrategy({
passReqToCallback: true // allows us to pass back the entire request to the callback
},
function (req, username, password, done) {
findOrCreateUser = function () {
// find a user in Mongo with provided username
UserModel.findOne({'login': username}, function (err, user) {
// In case of any error, return using the done method
if (err) {
console.log('Error in SignUp: ' + err);
return done(err);
}
// already exists
if (user) {
console.log('User already exists with username: ' + username);
return done(null, false, req.flash('message', 'User Already Exists'));
} else {
// if there is no user with that email
// create the user
var newUser = new UserModel();
// set the user's local credentials
newUser.displayName = req.param('displayName');
newUser.login = username;
newUser.password = createHash(password);
newUser.email = req.param('email');
newUser.phone = req.param('phone');
newUser.role = req.param('role');
newUser.description = req.param('description');
if (req.param('avatar')) {
var avatar = new Buffer(req.param('avatar')).toString('base64');
newUser.avatar = new Buffer(avatar, 'base64');
}
var adds = req.param('additional');
console.log(adds);
if (adds) {
newUser.additional = [];
for (var i = 0; i < adds.length; i++) {
newUser.additional[i] = {};
newUser.additional[i].name = adds[i].name;
newUser.additional[i].data = adds[i].data;
}
}
console.log(newUser.additional);
// save the user
newUser.save(function (err) {
if (err) {
console.log('Error in Saving user: ' + err);
throw err;
}
console.log('User Registration succesful');
return done(null, newUser);
});
}
});
};
// Delay the execution of findOrCreateUser and execute the method
// in the next tick of the event loop
process.nextTick(findOrCreateUser);
})
);
// Generates hash using bCrypt
var createHash = function (password) {
return bCrypt.hashSync(password, bCrypt.genSaltSync(10), null);
}
}
So, when I run this code I got strange error
TypeError: doc.validate is not a function
Even if I had no validation in my scheme.
What am I doing wrong?
Thank you
OMG, I don't know what happened but when I did it like
newUser.additional = req.param('additional');
Insted of this part of code
if (adds) {
newUser.additional = [];
for (var i = 0; i < adds.length; i++) {
newUser.additional[i] = {};
newUser.additional[i].name = adds[i].name;
newUser.additional[i].data = adds[i].data;
}
}
It worked perfectly. There is still magic for me...