how to access variables inside app.get - javascript

How can I access a variable or set of variables inside app.get and make it accessible to the whole project? I am trying to capture the information sent from the SMS text, organized into the "messageData" variable, then sent to the "MessageSchema," where it is then sent and stored in the Mongo Database. My issue is that I believe none of the variables(message, number, answer) are truly being found. How can I fix that?
app.js
app.get('/smssent', function(req, res, callback) {
var message = req.query.Body;
var number = req.query.From;
var twilioNumber = req.query.To;
var context = null;
var index = 0;
var contextIndex = 0;
contexts.forEach(function(value)
{
console.log(value.from);
if (value.from == number)
{
context = value.context;
contextIndex = index;
}
index = index + 1;
});
console.log('Recieved message from ' + number + ' saying \'' + message + '\'');
var conversation = new ConversationV1({
username: '',
password: '',
version_date: ConversationV1.VERSION_DATE_2016_09_20
});
//console.log(JSON.stringify(context));
//console.log(contexts.length);
conversation.message({
input: { text: message },
workspace_id: '',
context: context
}, function(err, response) {
if (err) {
console.error(err);
} else {
var answer = response.output.text[0];
if (context == null) {
contexts.push({'from': number, 'context': response.context});
} else {
contexts[contextIndex].context = response.context;
}
var intent = response.intents[0].intent;
console.log(intent);
if (intent == "done") {
//contexts.splice(contexts.indexOf({'from': number, 'context': response.context}),1);
contexts.splice(contextIndex,1);
// Call REST API here (order pizza, etc.)
}
var client = require('twilio')(
'',
''
);
client.messages.create({
from: twilioNumber,
to: number,
body: response.output.text[0]
}, function(err, message) {
if(err) {
console.error(err.message);
}
});
}
});
res.send('');
});
(ABOVE)This is what retrieves the SMS text, and conducts Twilio, Node, and IBM Bluemix.
index.js
router.post('/app', function(req, res, next) {
if (req.body.number &&
req.body.message &&
req.body.answer
) {
// create object with form input
var messageData = {
number: req.body.number,
message: req.body.message,
answer: req.body.answer
};
// use schema's `create` method to insert document into Mongo
Message.create(messageData, function (error, message) {
if (error) {
return next(error);
} else {
return res.redirect('/');
}
});
} else {
var err = new Error('All fields required.');
err.status = 400;
return next(err);
}
});
(ABOVE)This is the code to organize and prepare everything for the "MessageSchema."
message.js
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
var MessageSchema = new mongoose.Schema({
number: {
type: String,
required: true,
trim: true
},
message: {
type: String,
required: true,
trim: true
},
answer: {
type: String,
required: true,
trim: true
}
});
var Message = mongoose.model('Message', MessageSchema);
module.exports = Message;
Finally, this is what sends all the info to the DB.
If anyone finds anything or has any tips to improve this code, please let me know, I am open for all the input you can give me!
THANKS!

var messageData = {
number: req.body.number,
message: req.body.message,
answer: req.body.answer
};
This is OK. However, keep in mind that these variables are sent through POST body, not queries like the other one.
queries: ?param = ...
body: (like POST form; hidden from the URL)
If you unsure whether you are passing them alright, you can test that easily by console.info(...) on a certain point; and using Postman to easily test POST behavior.

Related

Cognito - Automatically verifying user on sign up

I am trying to automatically verify users emails when signing them up in my web app which is connected to cognito.
I am using the method to try and do this
adminUpdateUserAttributes
I immediately try to do this after i sign a user up. The user is signed up fine but the users email and phone are not verified in the console
What am i doing wrong in my code?
Here is my code:
$('#signUp').submit(function(event) {
var poolData = {
UserPoolId : '', // your user pool id here
ClientId : '' // your app client id here
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var attributeList = [];
var dataEmail = {
Name: 'email',
Value: $('input[name=email]').val(),
};
var dataPhoneNumber = {
Name: 'phone_number',
Value: $('input[name=telephone]').val(),
};
var attributeEmail = new AmazonCognitoIdentity.CognitoUserAttribute(dataEmail);
var attributePhoneNumber = new AmazonCognitoIdentity.CognitoUserAttribute(dataPhoneNumber);
attributeList.push(attributeEmail);
attributeList.push(attributePhoneNumber);
console.log(attributeList)
userPool.signUp($('input[name=usernameSignUp]').val(), $('input[name=passwordSignUp]').val(), attributeList, null, function(err, result) {
if (err) {
alert(err.message || JSON.stringify(err));
return;
}
console.log('signed up')
var cognitoUser = result.user;
console.log('user name is ' + cognitoUser.getUsername());
updateUserAttribute($('input[name=usernameSignUp]').val())
});
//updates the new user to have verified phone and email using adminUpdateUserAttributes() -- this isnt working rn
var cognitoidentityserviceprovider = new AWSCognito.CognitoIdentityServiceProvider();
cognitoidentityserviceprovider.adminUpdateUserAttributes({
UserAttributes: [{
Name: 'phone_number_verified',
Value: 'true'
}, {
Name: 'email_verified',
Value: 'true'
}
],
UserPoolId: '',
Username: $('input[name=usernameSignUp]').val()
}, function(err) {
if (err) {
console.log(err, err.stack)
} else {
console.log('Success!')
}
})
});```
For your usecase you should allow autoVerify when signing up.
This is done in a presignup lambda.
https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-sign-up.html
You should create a presignup lambda similar like this:
exports.handler = (event, context, callback) => {
event.response.autoConfirmUser = true;
event.response.autoVerifyEmail = true;
event.response.autoVerifyPhone = true;
callback(null, event);
};

How to return the user object with exercise fields added?

I am doing this exercise tracker REST api project on FreeCodeCamp. My code seems to give the correct output but it is failing to pass the test can add an exercise to any user by posting form data userId(_id), description, duration, and optionally date to /api/exercise/add. If no date supplied it will use current date. App will return the user object with the exercise fields added.
My code for this particular test
app.post("/api/exercise/add", urlencodedParser, async (req, res) => {
const params = req.body;
try {
if (
params.description === "" ||
params.duration === "" ||
params.userId === ""
) {
return res.json({ error: "please enter required fields" });
}
if (params.date === "" || params.date === null) {
params.date = new Date().toISOString().substring(0,10);
}
var existingUser = await Username.findById({ _id: params.userId });
if (existingUser._id === null) {
return res.json({
error: "could not find the ID. enter the correct one"
});
} else if (String(existingUser._id) === params.userId) {
var assignExercise = Object.create(Exercise);
assignExercise.description = params.description;
assignExercise.duration = params.duration;
assignExercise.date = params.date;
existingUser.exercise.push({
description: assignExercise.description,
duration: assignExercise.duration,
date: assignExercise.date
});
existingUser.count = existingUser.exercise.length;
await existingUser.save();
res.json({
username:existingUser.username,
id:existingUser._id,
exercise:existingUser.exercise
});
}
} catch (err) {
console.log(err);
res.json({ error: "A problem occured. Solve it" });
}
});
also for the convenience, I wrote the schema like this
const Exercise = {
description: String,
duration: Number,
date: { type: Date, default: Date.now }
};
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true
},
count: {
type: Number
},
exercise: {
type: Array,
value: Exercise
}
});
const Username = mongoose.model("Username", userSchema);
for this code I get the output
{"username":"Tanjim","id":"5f1939c3466036054f22511f","exercise":[{"description":"pushups","duration":"21","date":"2019-09-13"}]}
But still can't pass the test. Can anyone help me regarding this?
You need to use the .toDateString() to solve this exercise.
(new Date()).toDateString()
the return will be the expected format: 'Wed Aug 03 2022'.

Why do I get an error upon entering user into a database?

I'm teaching myself Mongodb. At first, I ran npm install --save mongoose uuid in Terminal to start things off. The goal of my program is to store a user in the database.
In Terminal, after running node index.js I want it to say:
About to save!
Saved!
But what I'm seeing in Terminal is (below):
Here's index.js
var mongoose = require('mongoose');
var uuid = require('uuid');
var Schema = mongoose.Schema;
/* New code from suggested website in error */
var promise = mongoose.connect('mongodb://localhost:testMongo/testMongo', {
useMongoClient: true,
});
promise.then(function(db) {
db.model();
connection.openUri('mongodb://localhost:testMongo/testMongo', { /* options */ });
var userSchema = new Schema({
email: {
type: String,
unique: true
},
password: {type: String},
todos: [
{
text: {type: String}
}
]
});
userSchema.pre('save', function(next) {
console.log("About to save!");
var user = this;
user.password = uuid.v4();
next();
});
var User = mongoose.model('user', userSchema);
var email = 'test#test.com';
// var user = new User({
// email: email
// });
//
// user.save(function(err) {
// if(err) {
// return console.log(err);
// } else {
// return console.log("User was saved!");
// }
// })
//
// console.log("Outside of callback!");
var text = "This is a todo.";
User.findOne({email: email}, function(user, err) {
if(err) {
return console.log(err);
}
if(!user) {
return console.log("Couldn't find user!");
}
var count = user.todos.push({
text: text
});
console.log(count);
user.save(function(err){
if(err) {
console.log(err);
} else {
console.log("Saved!");
}
});
});
Error in Terminal:
(node:14312) DeprecationWarning: `open()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead, or set the `useMongoClient` option if using `connect()` or `createConnection()`. See http://mongoosejs.com/docs/connections.html#use-mongo-client
{ _id: 595fe7c14a9810330c75aacc,
password: '297d5907-d9d7-49ef-800c-97a56aa395f7',
email: 'test#test.com',
__v: 0,
todos: [] }
That is not an error. It clearly says it's a warning: DeprecationWarning.
Also the message gives you a link to resolve the warning: http://mongoosejs.com/docs/connections.html#use-mongo-client

return resolve error in node function

Why wont usernametoid function return the acual id? cause im trying to send the result of the userdata as the return. In this case, i want to only send the userdata`s _id attribute. but it seems like it wont work.
console.log(userdata._id); // works
return resolve(userdata._id); // wont work.
output of variable userdata:
{
cash: 7300002,
bank: 0,
xp: 0,
rank: 1,
points: 1,
location: 1,
health: 100,
protection: 1,
attack: 1,
family: '0',
password: 'jKa4qC7pRCgE5jvzD9Vv1pRUNxFlQEM7Jpq/IoJ/sUWOAv1Wx1RI/j/Vu6Zf8zyNkCFcg3QBtdfAC+lmPS8KIA==',
profileImageURL: 'modules/users/client/img/profile/default.png',
roles: [ 'user' ],
created: Sat Aug 27 2016 12:33:55 GMT-0400 (EDT),
__v: 0,
username: 'signature',
provider: 'local',
salt: '4ySlrr9ggESxBB3dR5bx4Q==',
_id: 57c1c0f3b6b20c011242bf22 }
when i do: `return resolve(userdata._id) it would get this error:
/server/factory/user_factory.js:52
return resolve(userdata._id);
^
TypeError: Cannot read property '_id' of null
node.js call:
var articles = require('../controllers/articles.server.controller'),
path = require('path'),
mongoose = require('mongoose'),
Article = mongoose.model('Article'),
Users = mongoose.model('User'),
errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));
var userFunc = require('../factory/user_factory.js');
app.post('/api/kill', function (req, res) {
console.log("starting");
var username = "signature";//req.query.username;
var result = ["test service"];
var data = req.user;
userFunc.usernametoid(username).then( function (otherplayerid) {
if (!(otherplayerid)) {
console.log("other player is acually " + otherplayerid);
result.push("denne brukeren finnes ikke! " + otherplayerid);
} else {
userFunc.usernametoid(otherplayerid).then( function (otherplayer) {
if (data.location != otherplayer.location) {
result.push("Du er ikke i samme lokasjon som " + username);
result.push(data.location + " vs " + otherplayer.location);
} else {
userFunc.addCash(req.user._id,100000);
result.push("starter lokasjonisering");
}
});
}
res.json(result);
});
});
user factory:
var articles = require('../controllers/articles.server.controller'),
path = require('path'),
mongoose = require('mongoose'),
Article = mongoose.model('Article'),
Users = mongoose.model('User'),
errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));
exports.usernametoid = usernametoid;
function usernametoid(id) {
return new Promise( function (resolve, reject) {
var query = Users.findOne( { username : id } );
// var query = Users.find({_id:id});
query.exec(function(err, userdata) {
if (err){
return reject({err : 'Error while getting user info'});
}
console.log(userdata._id);
return resolve(userdata);
});
}, function (){
return reject({err : 'error while fetching cash'});
});
}
Because you are not passing correctly the fetched user to the query.exec.
You need to do:
var Users = require('../models/users-model.js');
function usernametoid(id) {
return new Promise( function (resolve, reject) {
Users.findOne({ username : id }).then( function(user){
//If you use lodash you can do _.isNull(user)
if(user == null){
return reject({error : 'User not found'});
}
user.exec(function(userdata, error) {
if(userdata){
return resolve(userdata);
}
if(error){
return reject({error : 'Error while executing query'});
}
});
});
});
}
I don't really get why you are importing Users Model like that. I do not think Node will be able to fetch it like that.
And, you should require mongoose in your server.js
To catch the rejection you need the following code:
UserFactory.userNameToId(id).then( function(response){
if(response.error){
console.log('error '+response.error);
}
if(response){
console.log('Got response '+response);
}
});

custom validation and formatting the response returned from the datadase - BEGINNER

I am new to Node.js. This is a 2 part questions. The full source code is found below.
1.) Before saving to the database I need to validate (for example check if the password contains 6 characters, and if it contains 1 numeric value) the data inserted by the end user. Where, and how can I do this ?
my workings are illustrated below:
module.exports.addUser = function(user, callback) {
//
if (user.email.length < 7 ) {
// How can I send a JSON formmated error message to the user ?
}
User.create(user, callback);
}
2.) If the User successfully adds a user, I am returning that object to the user. With this object returned I also need to return the STATUS as SUCCESS. How can I do this? (Like the example shown below - Also please note that I am NOT returning the password in the JSON)
[{
"status": "SUCCESS",
"User": {
"_id": "57377e3ec955f8620620b242",
"name": "yoyo",
"email": "chris#heytoe.com",
"__v": 0
}
}
]
FULL SOURCE CODE
APP.jS
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
app.use(bodyParser.json());
User = require('./models/user');
app.post('/my/user',function(req,res){
var user = req.body;
User.addUser(user, function(err,users){
if(err){
throw err;
} else {
res.json(users);
}
})
});
USER.JS <-- in models/user.js
var mongoose = require('mongoose');
var userSchema = mongoose.Schema({
name:{
type: String,
required:true
},
email:{
type: String,
required:true,
unique: true
},
password:{
type: String,
required:true
},
nickname:{
type: String,
required:false
},
create_date:{
type: Date,
deault: Date.now
}
});
var User = module.exports = mongoose.model('User',userSchema);
module.exports.addUser = function(user, callback) {
User.create(user, callback);
}
Your first question:
There are couple of ways. You can check the value before insert it as your code :
User = require('./models/user');
app.post('/my/user',function(req,res){
var user = req.body;
if (user.password.length > 6 && user.password.match(/\d+/g)) {
User.addUser(user, function(err,users){
if(err){
throw err;
} else {
res.json(users);
}
})
} else { throw err; }
});
Or
add your schema validation property. For instance:
var userSchema = new Schema({
password: {
type: String,
required: true,
validate: [validatePassword, 'Password is invalid.']
}
});
var validatePassword = function(value) {
return (value.length < 6 || !value.match(/\d+/g));
};
Besides, there is a pre method to call the fnction before save the value. check this mongoose pre
schema.pre('save', function(doc, next) {
if (doc.password.value < 6 || !value.match(/\d+/g)) return next("Invalid");
next();
});
Your second question:
when you send res json, you can add this as object property:
res.json({ users: users, status: "SUCCESS" });
if you dont want to send password. you can delete propery.
delete user['password']
then send it, but before send it you might need to copy or clone the object.

Categories

Resources