Nodejs Request values - json

So I have a nodejs server and I am trying to make comparisons to the req values. Firstly, here is my code:
app.post('/', function(req, res) {
firstName = req.body.firstName;
lastName = req.body.lastName;
message = req.body.message;
token = req.body.token;
user = {name: firstName + " " + lastName, token: token};
selectedUser = req.body.selectedUser;
users.push(user);
console.log(user.name);
if (req.body.isAndroid === true) {
sendToAndroid(); //add message parameter
} else {
sendToios(); //add message parameter
}
});
app.listen(8080, function() {
console.log('running on port 8080');
});
//GCM
function sendToAndroid() {
var message = new gcm.Message();
var tokenLocation;
//API Server Key
var sender = new gcm.Sender('AIzaSyD-B3EG1xpMh6YhwBKfLMyw0GIQKWfGgZM');
//console.log(message);
// Value the payload data to send...
message.addData({
title: 'Hello',
body: 'Message From: ' + user.name + ': ' + message,
msgcnt: 1,
timeToLive: 3000
});
// At least one reg id required
if (registrationToken.indexOf(token) == -1) {
registrationToken.push(token);
tokenLocation = registrationToken.indexOf(token);
} else {
tokenLocation = registrationToken.indexOf(token);
}
if (users.indexOf(user.name) == -1) {
console.log("user destination not found");
} else {
var userTokenArray = [];
userTokenArray.push(user.token);
sender.send(message, { registrationTokens: userTokenArray } , function (err, response) {
if(err) console.error(err);
else console.log(response);
});
userTokenArray.pop();
}
}
And here is my problem when outputting to see what the value is:
running on port 8080
undefined undefined
user destination not found
What I am trying to do is put the registered users into an array of users that each element has a full name and token. Then in the Android function, it will check to see what value value is selected and then push a notification to the selectedUser via their token. I am so confused on how to compare the "strings" or whatever they are. I am using nodejs express with body-parser.

Related

How to create a unprotected api in Json server jwt auth

I am using json server with jwt auth to create a fake api.After successful registration or login i am receiving one token and using this token I can access the database.json.Without registation or login i can't access database.json file,but I want to access one api with out verifying my self to show all product to guest user.how it is possible.
I want a api like localhost:8000/products so I can access it without authorization,how to archive this in this js file.
I am using this code from git.
https://github.com/techiediaries/fake-api-jwt-json-server/blob/master/server.js
const fs = require('fs')
const bodyParser = require('body-parser')
const jsonServer = require('json-server')
const jwt = require('jsonwebtoken')
const server = jsonServer.create()
const router = jsonServer.router('./database.json')
const userdb = JSON.parse(fs.readFileSync('./users.json', 'UTF-8'))
server.use(bodyParser.urlencoded({extended: true}))
server.use(bodyParser.json())
server.use(jsonServer.defaults());
const SECRET_KEY = '123456789'
const expiresIn = '1h'
// Create a token from a payload
function createToken(payload){
return jwt.sign(payload, SECRET_KEY, {expiresIn})
}
// Verify the token
function verifyToken(token){
return jwt.verify(token, SECRET_KEY, (err, decode) => decode !== undefined ? decode : err)
}
// Check if the user exists in database
function isAuthenticated({email, password}){
return userdb.users.findIndex(user => user.email === email && user.password === password) !== -1
}
// Register New User
server.post('/auth/register', (req, res) => {
console.log("register endpoint called; request body:");
console.log(req.body);
const {email, password} = req.body;
if(isAuthenticated({email, password}) === true) {
const status = 401;
const message = 'Email and Password already exist';
res.status(status).json({status, message});
return
}
fs.readFile("./users.json", (err, data) => {
if (err) {
const status = 401
const message = err
res.status(status).json({status, message})
return
};
// Get current users data
var data = JSON.parse(data.toString());
// Get the id of last user
var last_item_id = data.users[data.users.length-1].id;
//Add new user
data.users.push({id: last_item_id + 1, email: email, password: password}); //add some data
var writeData = fs.writeFile("./users.json", JSON.stringify(data), (err, result) => { // WRITE
if (err) {
const status = 401
const message = err
res.status(status).json({status, message})
return
}
});
});
// Create token for new user
const access_token = createToken({email, password})
console.log("Access Token:" + access_token);
res.status(200).json({access_token})
})
// Login to one of the users from ./users.json
server.post('/auth/login', (req, res) => {
console.log("login endpoint called; request body:");
console.log(req.body);
const {email, password} = req.body;
if (isAuthenticated({email, password}) === false) {
const status = 401
const message = 'Incorrect email or password'
res.status(status).json({status, message})
return
}
const access_token = createToken({email, password})
console.log("Access Token:" + access_token);
res.status(200).json({access_token})
})
server.use(/^(?!\/auth).*$/, (req, res, next) => {
if (req.headers.authorization === undefined || req.headers.authorization.split(' ')[0] !== 'Bearer') {
const status = 401
const message = 'Error in authorization format'
res.status(status).json({status, message})
return
}
try {
let verifyTokenResult;
verifyTokenResult = verifyToken(req.headers.authorization.split(' ')[1]);
if (verifyTokenResult instanceof Error) {
const status = 401
const message = 'Access token not provided'
res.status(status).json({status, message})
return
}
next()
} catch (err) {
const status = 401
const message = 'Error access_token is revoked'
res.status(status).json({status, message})
}
})
server.use(router)
server.listen(8000, () => {
console.log('Run Auth API Server')
})

go to 404 if route is undefined node.js

I am basically trying to say, if someone types into the browser, xxx.com/homy, instead of xxx.com/home, how do I redirect them to a 404 page? here's my index.js file. I am using node.js
// Direct to View Registrations
router.get('/viewRegistration', auth.ensureAuthenticated, function(req, res, next) {
var adminActive = ""
UtilRole.roleCheck(req, res, 'ADMIN', (response) => {
adminActive = response != undefined ? response : false
const user = JSON.parse(req.session.passport.user)
var query = "SELECT * FROM table WHERE email = '" + user.emailAddress + "'";
ibmdb.open(DBCredentials.getDBCredentials(), function(err, conn) {
if (err) return res.send('sorry, were unable to establish a connection to the database. Please try again later.');
conn.query(query, function(err, rows) {
if (err) {
Response.writeHead(404);
}
for (var i = 0; i < rows.length; i++) {
console.log(rows[i])
}
res.render('viewRegistration', {
page_title: "viewRegistration",
data: rows,
user,
role: adminActive
});
return conn.close(function() {
console.log('closed /viewRegistration');
});
});
});
})
})
module.exports = router;

How to save data to mysql server with Node.js

I am currently trying to build an application for my project.
It is my first time programming as well as using node.js
I have successfully connected node.js with mysql and was able to save data to mysql server.
However, some data that I want to save is declared as undefined
currently my code looks like this
imap.once('ready', function() {
openInbox(function(err, box) {
if (err) throw err;
imap.search([ 'UNSEEN', ['SINCE', 'December 20, 2018'] ], function(err, results) {
if (err) {
console.log('you are already up to date');
}
//var f = imap.fetch(results, {markSeen: true, bodies: ''});
var f = imap.fetch(results, {bodies: ''});
f.on('message', function(msg, seqno) {
var prefix = '(#' + seqno + ') ';
msg.on('body', function(stream, info) {
simpleParser(stream, (err, mail) => {
con.connect(function(err) {
console.log("Connected!");
var sql = "INSERT INTO scrap (reply_to, content) VALUES ('" + mail.from.text + "', '" + mail.subject +"')";
con.query(sql, function (err , result) {
});
});
console.log(mail.from);
// console.log(mail.from.text);
// console.log(mail.subject);
// console.log(mail.text);
});
the Console.log will fetch information like this
{ value:
[ { address: 'xxx#gmail.com', name: 'NAME' } ],
html:
'NAME <xxx#gmail.com>',
text: 'NAME ' }
I would like to know how to fetch email and name separately.
I have tried console.log(mail.from.address) or (mail.from.mailto) but it returns undefined
try
mail.from.value[0].address // fetch email
mail.from.value[0].name //fetch name

Upload Excel file and download from mysql using Node js

I want to upload Excel sheet and after submit that excel sheet need to insert data into mysql database and same sheet which we upload need to download.
I have tried below code:
Node Service-
function getDetails(req, res) {
var sampleFile, fileInfo = {};
var post = req.body;
var ID= post.id;
var name=post.name
if (!req.files) {
res.send('No files were uploaded.');
return;
}
sampleFile = req.files.fileInputXLSX;
console.log("req.body -- ",req.body);
console.log("Uploaded -- ",sampleFile);
// Get file attributes
var fileId = req.body.fileId;
var fileExtn = sampleFile.name.split(".").pop();
var extractedFilename = sampleFile.name.slice(0, sampleFile.name.lastIndexOf('.'));
var uploadFileName = extractedFilename+'_'+fileId+'.'+fileExtn;
console.log("uploadFileName -- ",uploadFileName);
fileInfo = {
"name": uploadFileName,
"mimetype": sampleFile.mimetype
}
sampleFile.mv(__dirname+'/Myuploads/Details/'+uploadFileName, function(err) {
if (err) {
res.status(500).send(err);
}
else {
// Update file info
var queryString = "INSERT INTO 'details'('id','name') VALUES ('" + ID + "','" + name + "')";
connection.query(queryString, function(err, result) {
if (!err){
var response = [];
response.push({'result' : 'success'});
if (result.length != 0) {
response.push({'data' : result});
} else {
response.push({'msg' : 'No Result Found'});
}
res.setHeader('Content-Type', 'application/json');
res.status(200).send(JSON.stringify(response));
} else {
res.status(400).send(err);
}
});
}
});
}
Controller.js
$scope.MyFunction=function(){
var excelForm = new FormData();
excelForm.append('fileInputXLSX', document.getElementById("fileInputXLSX").files[0]);
console.log("---- excelFile : ", document.getElementById("fileInputXLSX").files[0]);
// End : Get File
$http.post(Data.baseNodeService + "getDetails", {
"newProtocolObj": $scope.newProtocolObj
},headconfig).success(function(data, status, headers, config) {
console.log('Details: success');
excelForm.append('fileId', data);
jQuery.ajax({
url: data.baseNodeService + "getDetails",
type: "POST",
cache: false,
contentType: false,
processData: false,
data: excelForm,
success: function(data) {
console.log("---- upload response : ", data);
$scope.goToTfilePage();
}
});
// End : Upload File
}).error(function(map_data, status, headers, config) {
console.log('Details: error');
console.log('status: ', status, '\nmap_data: ', map_data, '\nconfig: ', config);
});
}
Message is coming in console: No file is uploaded.
Please help with the same.It is not upload the file.It is not able to read the response from node service.
I am new in this help in which manner i need to write.
Edit:I am able to upload the file but how to insert into mysql database??

unable to print post response

I'm writing a program in node js that does the following.
Get the Access token(a jwt)
Get the user firstName from that token
Pass this token and firstName to another method to post.
print the result.
My program is as below.
function getUserDetailsFromAccessToken(session) {
var token = session.user.accessToken;
try {
// parse this and get user attributes
var decoded = jwt.decode(token);
getTheUserProfile(decoded.firstname, token, session);
} catch (err) {
console.log(err);
}
}
var hostUrl= "myUrlToGetResult";
function getTheUserProfile(nameFromSession, token, session) {
console.log("Incomung values " + nameFromSession);
console.log("Inside getUsersProfile Block");
var jsonToPass = {
"accesstoken": token,
"domain": "DomainName",
"lanid": nameFromSession
};
console.log("json to pass " + JSON.stringify(jsonToPass));
var options = {
uri: hostUrl+ "/api/admin/GetUserInfo",
method: "POST",
json: jsonToPass
};
request(options, function (error, resp, body) {
console.log("resp code is " + resp.statusCode);
if (!error && resp.statusCode == 200) {
if (body) {
console.log("Insode B1");
console.log(body.firstName);
} else {
console.log("I am unable to authenticate you. please disable the skill and re link your account");
}
} else {
console.log(error);
}
});
}
when I run this program, I'm able to print only till console.log("json to pass " + JSON.stringify(jsonToPass));, after that I'm unable to get any result from request() block.
please let me know where am I going wrong and how can I fix it.