express-ntlm: how to get additional attribute value in req.ntlm? - javascript

In express-ntlm package i have added password attribute but i'm not able to get its value while i provide in private window of chrome. I always getting empty value.
My code is:
/* jshint node:true */
// node.js modules
var url = require('url');
// 3rd-party modules
var _ = require('underscore'),
async = require('async');
// Custom modules
var Cache = require('./Cache'),
NTLM_AD_Proxy = require('./NTLM_AD_Proxy'),
NTLM_No_Proxy = require('./NTLM_No_Proxy'),
utils = require('./utils');
const { Domain } = require('domain');
// Globals
var cache = new Cache();
module.exports = function(options) {
// Overwrite the default options by the user-defined
options = _.extend({
badrequest: function(request, response, next) {
response.sendStatus(400);
},
internalservererror: function(request, response, next) {
response.sendStatus(500);
},
forbidden: function(request, response, next) {
response.sendStatus(403);
},
unauthorized: function(request, response, next) {
response.statusCode = 401;
response.setHeader('WWW-Authenticate', 'NTLM');
response.end();
},
prefix: '[express-ntlm]',
debug: function() {
},
domaincontroller: null,
getConnectionId(request, response) {
return utils.uuidv4();
}
}, options);
function ntlm_message_type(msg) {
if (msg.toString('utf8', 0, 8) != 'NTLMSSP\0') {
return new Error('Not a valid NTLM message:', msg.toString('hex'));
}
var msg_type = msg.readUInt8(8);
if (!~[1, 2, 3].indexOf(msg_type)) {
return new Error('Incorrect NTLM message Type', msg_type);
}
return msg_type;
}
function parse_ntlm_authenticate(msg) {
var DomainNameLen = msg.readUInt16LE(0x1C),
DomainNameBufferOffset = msg.readUInt32LE(0x20),
DomainName = msg.slice(DomainNameBufferOffset, DomainNameBufferOffset + DomainNameLen),
UserNameLen = msg.readUInt16LE(0x24),
UserNameBufferOffset = msg.readUInt32LE(0x28),
UserName = msg.slice(UserNameBufferOffset, UserNameBufferOffset + UserNameLen),
PasswordLen = msg.readUInt16LE(0x34),
PasswordBufferOffset = msg.readUInt32LE(0x38),
Password = msg.slice(PasswordBufferOffset, PasswordBufferOffset + PasswordLen),
WorkstationLen = msg.readUInt16LE(0x2C),
WorkstationBufferOffset = msg.readUInt32LE(0x30),
Workstation = msg.slice(WorkstationBufferOffset, WorkstationBufferOffset + WorkstationLen);
if (utils.isFlagSet(msg.readUInt8(0x3C), utils.toBinary('00000001'))) {
DomainName = DomainName.toString('utf16le');
UserName = UserName.toString('utf16le');
Password = Password.toString('utf16le');
Workstation = Workstation.toString('utf16le');
} else {
DomainName = DomainName.toString();
UserName = UserName.toString();
Password = Password.toString();
Workstation = Workstation.toString();
}
return [UserName, Password, DomainName, Workstation];
}
function decode_http_authorization_header(auth) {
var ah = auth.split(' ');
if (ah.length === 2) {
if (ah[0] === 'NTLM') {
return ['NTLM', new Buffer(ah[1], 'base64')];
}
}
return false;
}
function connect_to_proxy(type1, callback) {
var domain = options.domain;
var proxy,
ntlm_challenge;
async.eachSeries(!options.domaincontroller ? [ -1 ] : typeof options.domaincontroller === 'string' ? [ options.domaincontroller ] : options.domaincontroller, function(server, eachDomaincontrollerCallback) {
if (!server || ntlm_challenge) return eachDomaincontrollerCallback();
if (server === -1) {
options.debug(options.prefix, 'No domaincontroller was specified, all Authentication messages are valid.');
proxy = new NTLM_No_Proxy();
} else if (!server.indexOf('ldap')) {
var serverurl = url.parse(server),
use_tls = serverurl.protocol === 'ldaps:',
decoded_path = decodeURI(serverurl.path);
options.debug(options.prefix, 'Initiating connection to Active Directory server ' + serverurl.host + ' (domain ' + domain + ') using base DN "' + decoded_path + '".');
proxy = new NTLM_AD_Proxy(serverurl.hostname, serverurl.port, domain, decoded_path, use_tls, options.tlsOptions);
} else {
return eachDomaincontrollerCallback(new Error('Domaincontroller must be an AD and start with ldap://'));
}
proxy.negotiate(type1, function(error, challenge) {
if (error) {
proxy.close();
proxy = null;
options.debug(options.prefix, error);
return eachDomaincontrollerCallback();
}
ntlm_challenge = challenge;
return eachDomaincontrollerCallback();
});
}, function(error) {
if (error) return callback(error);
if (!proxy) {
return callback(new Error('None of the Domain Controllers are available.'));
}
return callback(null, proxy, ntlm_challenge);
});
}
function handle_type1(request, response, next, ntlm_message, callback) {
cache.remove(request.connection.id);
cache.clean();
connect_to_proxy(ntlm_message, function(error, proxy, challenge) {
if (error) return callback(error);
response.statusCode = 401;
response.setHeader('WWW-Authenticate', 'NTLM ' + challenge.toString('base64'));
response.end();
cache.add(request.connection.id, proxy);
return callback();
});
}
function handle_type3(request, response, next, ntlm_message, callback) {
var proxy = cache.get_proxy(request.connection.id);
var userDomainWorkstation = parse_ntlm_authenticate(ntlm_message),
user = userDomainWorkstation[0],
pass = userDomainWorkstation[1],
domain = userDomainWorkstation[2],
workstation = userDomainWorkstation[3];
if (!domain) {
domain = options.domain;
}
proxy.authenticate(ntlm_message, function(error, result) {
if (error) return callback(error);
var userData = {
DomainName: domain,
UserName: user,
Password: pass,
Workstation: workstation,
Authenticated: false
};
request.ntlm = userData;
response.locals.ntlm = userData;
request.connection.ntlm = userData;
if (!result) {
cache.remove(request.connection.id);
options.debug(options.prefix, 'User ' + domain + '/' + user + ' authentication for URI ' + request.protocol + '://' + request.get('host') + request.originalUrl);
return options.forbidden(request, response, next);
} else {
userData.Authenticated = true;
return next();
}
});
}
return function(request, response, next) {
if (!request.connection.id) {
request.connection.id = options.getConnectionId(request, response);
}
var auth_headers = request.headers.authorization;
var user = request.connection.ntlm;
if (user && user.Authenticated) {
options.debug(options.prefix, 'Connection already authenticated ' + user.DomainName + '/' + user.UserName);
if (auth_headers) {
if (request.method != 'POST') {
request.ntlm = user;
response.locals.ntlm = user;
return next();
}
} else {
request.ntlm = user;
response.locals.ntlm = user;
return next();
}
}
if (!auth_headers) {
options.debug(options.prefix, 'No Authorization header present');
return options.unauthorized(request, response, next);
}
var ah_data = decode_http_authorization_header(auth_headers);
if (!ah_data) {
options.debug(options.prefix, 'Error when parsing Authorization header for URI ' + request.protocol + '://' + request.get('host') + request.originalUrl);
return options.badrequest(request, response, next);
}
var ntlm_version = ntlm_message_type(ah_data[1]);
if (ntlm_version instanceof Error) {
options.debug(options.prefix, ntlm_version.stack);
return options.badrequest(request, response, next);
}
if (ntlm_version === 1) {
return handle_type1(request, response, next, ah_data[1], function(error) {
if (error) {
options.debug(options.prefix, error.stack);
return options.internalservererror(request, response, next);
}
});
}
if (ntlm_version === 3) {
if (cache.get_proxy(request.connection.id) !== null) {
return handle_type3(request, response, next, ah_data[1], function(error) {
if (error) {
options.debug(options.prefix, error.stack);
return options.internalservererror(request, response, next);
}
});
}
options.debug(options.prefix, 'Unexpected NTLM message Type 3 in new connection for URI ' + request.protocol + '://' + request.get('host') + request.originalUrl);
return options.internalservererror(request, response, next);
}
options.debug(options.prefix, 'Type 2 message in client request');
return options.badrequest(request, response, next);
};
};
my response is
{"DomainName":"ijk","UserName":"xyz","Password":"","Workstation":"some","Authenticated":true}

Related

AXIOS POST return result

I have created a non-JWT api call and it works. The moment I added JWT verifyToken it works but I cannot seems to get the return result set from AXIOS POST.
Function 2 --> /userget ----is working I can display result on HTML
Function 7 ---> /api/userget ---It can get data and token but I cannot display on HTML, it goes to "Bad response"
++++++++++++++++++++++++++++++++
function myFunction2() {
console.log("Going2");
var userid = document.getElementById("userid").value;
console.log(userid);
axios( {
method: 'post',
url:'http://localhost:8081/userget',
data : {
userid : userid
}
})
.then(function (response) {
console.log(response.data.result[0].username );
var userid = JSON.stringify(response.data.result[0].userid);
var username = JSON.stringify(response.data.result[0].username);
var email = JSON.stringify(response.data.result[0].email);
var userid = JSON.parse(userid);
var username = JSON.parse(username);
var email = JSON.parse(email);
var displaydata = ("User ID : " + userid + "<br><br>Name : " + username + "<br><br>Email :" + email);
document.getElementById("demo").innerHTML = displaydata;
})
.catch(function (error) {
document.getElementById("demo").innerHTML = "Bad response";
});
}
+++++++++++++++++++++++++++++++++
function myFunction7() {
console.log("Going7");
var userid = document.getElementById("userid").value;
console.log(userid);
console.log("Print local token == " + localStorage.getItem("token"));
var msgtxt = localStorage.getItem("token");
axios( {
method: 'post',
url:'http://localhost:8081/api/userget',
headers: {
'Authorization': `Bearer ${msgtxt}`
},
data : {
userid : userid
}
})
.then(function (response) {
console.log(response.data.result[0].username );
var userid = JSON.stringify(response.data.result[0].userid);
var username = JSON.stringify(response.data.result[0].username);
var email = JSON.stringify(response.data.result[0].email);
var userid = JSON.parse(userid);
var username = JSON.parse(username);
var email = JSON.parse(email);
var displaydata = ("User ID : " + userid + "<br><br>Name : " + username + "<br><br>Email :" + email);
document.getElementById("demo").innerHTML = displaydata;
})
.catch(function (error) {
document.getElementById("demo").innerHTML = "Bad response";
});
}
+++++++++++++++++++++++++++++
app.post('/userget', function (req, res) {
const userid = req.body.userid;
console.log ("User id == " + userid)
user.getUser(userid, function (err, result) {
if (!err) {
console.log(result)
res.send({result})
} else{
res.send(err.errno + " No record");
}
res.end()
});
});
+++++++++++++++++++++
app.post('/api/userget', verifyToken, (req, res) => {
const userid = req.body.userid;
console.log ("User id == " + userid)
jwt.verify(req.token, secretKey, (err, authData) => {
if(err) {
res.sendStatus(403);
} else {
user.getUser(userid, function (err, result) {
if (!err) {
console.log(result)
res.send({result})
} else{
res.send(err.errno + " No record");
}
res.end()
});
res.json({
message: 'Post created...',
authData : authData
});
}
});
});
Error in terminal
/home/ronaldtan/Programming/webservices/node_modules/mysql/lib/protocol/Parser.js:437
throw err; // Rethrow non-MySQL errors
^
Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:491:11)
at ServerResponse.setHeader (_http_outgoing.js:498:3)
at ServerResponse.header (/home/ronaldtan/Programming/webservices/node_modules/express/lib/response.js:771:10)
at ServerResponse.send (/home/ronaldtan/Programming/webservices/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/home/ronaldtan/Programming/webservices/node_modules/express/lib/response.js:267:15)
at ServerResponse.send (/home/ronaldtan/Programming/webservices/node_modules/express/lib/response.js:158:21)
at /home/ronaldtan/Programming/webservices/controller/app.js:170:17
at Query. (/home/ronaldtan/Programming/webservices/model/user.js:44:32)
at Query. (/home/ronaldtan/Programming/webservices/node_modules/mysql/lib/Connection.js:526:10)
at Query._callback (/home/ronaldtan/Programming/webservices/node_modules/mysql/lib/Connection.js:488:16)
The problem is the following:
user.getUser(userid, function (err, result) {
if (!err) {
console.log(result)
res.send({
result
})
} else {
res.send(err.errno + " No record");
}
res.end()
});
res.json({
message: 'Post created...',
authData: authData
});
The second statement (res.json(...)) is executed before the async-operation user.getUser(..) has finished. So once its callback is executed, res.json will already have finished and since you are trying to res.send again (res.json does the same operation under the hood) you get the error.
It seems like you can just remove the res.json(...) statement as you want to return the found user, not some info about creating a post.

JavaScript Global Variable Not Updating Value

I have the below JavaScript code to develop an app in Fuse Tools. There is one last error that I cannot seem to understand and that is that my variable b64data should be a global variable and is not updating it's value from the capturePhoto function and letting me send the updated value in the submitPhoto function to the server. It should send the base64 encoded value as the picture variable in my POST function. Any help is appreciated!
var Observable = require("FuseJS/Observable");
let ImageTools = require("FuseJS/ImageTools");
var FileSystem = require("FuseJS/FileSystem");
var Base64 = require("FuseJS/Base64");
var Camera = _camera;
var b64data;
var captureMode = Observable();
var flashMode = Observable();
function getCameraInfo() {
Camera.getCameraInfo()
.then(function(info) {
console.log("captureMode: " + info[Camera.INFO_CAPTURE_MODE]);
console.log("flashMode: " + info[Camera.INFO_FLASH_MODE]);
console.log("cameraFacing: " + info[Camera.INFO_CAMERA_FACING]);
console.log("supportedFlashModes: " + info[Camera.INFO_SUPPORTED_FLASH_MODES].join());
captureMode.value = info[Camera.INFO_CAPTURE_MODE];
flashMode.value = info[Camera.INFO_FLASH_MODE];
if (Camera.INFO_PHOTO_RESOLUTIONS in info) {
var availableResolutions = info[Camera.INFO_PHOTO_RESOLUTIONS];
availableResolutions.forEach(function(e) {
console.log(e.width + "x" + e.height);
});
photoResolution = availableResolutions[Math.floor(availableResolutions.length * 0.4)];
var options = {};
options[Camera.OPTION_PHOTO_RESOLUTION] = photoResolution;
Camera.setPhotoOptions(options)
.then(function() {
console.log("New photo options set: " + JSON.stringify(options));
})
.catch(function(error) {
console.log("Failed to set photo options: " + error);
});
}
})
.catch(function(err) {
console.log("Failed to get camera info: " + err);
});
}
getCameraInfo();
function nextFlashMode() {
if (flashMode.value == Camera.FLASH_MODE_AUTO) return Camera.FLASH_MODE_ON;
else if (flashMode.value == Camera.FLASH_MODE_ON) return Camera.FLASH_MODE_OFF;
else if (flashMode.value == Camera.FLASH_MODE_OFF) return Camera.FLASH_MODE_AUTO;
else throw "Invalid flash mode";
}
function setCaptureMode(cm) {
Camera.setCaptureMode(cm)
.then(function(mode) {
captureMode.value = mode;
console.log("Capture mode set to: " + mode);
})
.catch(function(err) {
console.log("Failed to set capture mode: " + err);
});
}
function capturePhoto() {
Camera.capturePhoto()
.then(function (photo) {
photo.save()
.then(function(filePath) {
console.log("Photo saved to: " + filePath);
var arrayBuff = FileSystem.readBufferFromFileSync(filePath);
var b64data = Base64.encodeBuffer(arrayBuff); // send this to the backend
photo.release();
})
.catch(function(error) {
console.log("Failed to save photo: " + error);
photo.release();
});
})
.catch(function (error) {
console.log("Failed to capture photo: " + error);
});
}
var isRecording = Observable(false);
var recordingSession = null;
function startRecording() {
isRecording.value = true;
Camera.startRecording()
.then(function (session) {
recordingSession = session;
})
.catch(function (error) {
console.log("Failed to start recording: " + error);
isRecording.value = false;
});
}
function stopRecording() {
isRecording.value = false;
recordingSession.stop()
.then(function (recording) {
router.push("VideoPage", recording.filePath());
})
.catch(function (error) {
console.log("Failed to stop recording: " + error);
});
recordingSession = null;
}
var cameraBack = true;
function flipCameraFacing() {
var front = Camera.CAMERA_FACING_FRONT;
var back = Camera.CAMERA_FACING_BACK;
Camera.setCameraFacing(cameraBack ? front : back)
.then(function (newFacing) {
cameraBack = newFacing == back;
getCameraInfo();
console.log("Camera facing set to: " + (newFacing == back ? "back" : "front"));
})
.catch(function (err) {
console.log("Failed to set camera facing: " + err);
});
}
function changeFlashMode() {
Camera.setFlashMode(nextFlashMode())
.then(function(newFlashMode) {
flashMode.value = newFlashMode;
console.log("Flash mode set to: " + flashMode.value);
})
.catch(function(err) {
console.log("Failed to set flash mode: " + err);
});
}
var name = Observable();
var email = Observable();
var market = Observable();
module.exports = {
name: name,
email: email,
market: market,
b64data: b64data,
submitPhoto: submitPhoto,
captureMode: captureMode,
setCaptureModePhoto: function () { setCaptureMode(Camera.CAPTURE_MODE_PHOTO); },
setCaptureModeVideo: function () { setCaptureMode(Camera.CAPTURE_MODE_VIDEO); },
capturePhoto: capturePhoto,
startRecording: startRecording,
stopRecording: stopRecording,
isRecording: isRecording,
flipCameraFacing: flipCameraFacing,
flashMode: flashMode,
changeFlashMode: changeFlashMode,
}
function submitPhoto(){
console.log("name: "+name);
console.log("email: "+email);
console.log("market: "+market);
fetch('http://fanbeauties.com/app/submit-photo.php?pass=MY_PASS', {
method: "POST",
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: '&name='+name+'&email='+email+'&market='+market+'&picture='+b64data
});
};
May be because of you are declaring b64data again in capturePhoto function on line 72 in your shared code.
try
b64data = ...
instead of
var b64data = ...

Remove name file html from url

I am using Angular JS for my Front End and Express Server for backend.
I am trying to remove the init.html from my url.
I have read other post and I have not managed to fix it.
Now : http://localhost:3000/init.html#!/export
I want look like : http://localhost:3000/#!/export
I tried : $locationProvider.hashPrefix() and
locationProvider.html5Mode(true) but it is not working.
manager-app.js
angular.module("ManagerApp", ["angularUtils.directives.dirPagination", "ngRoute"]).config(function($routeProvider, $locationProvider) {
$routeProvider
.when("/", {
templateUrl: "/index.html"
})
.when("/export", {
templateUrl: "export/listExport.html",
controller: "ListCtrlExport"
});
index.html is a static html
init.html
<html ng-app="ManagerApp">
<head>
<title>
ManagerApp
</title>
<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap-theme.min.css" type="text/css" />
<script type="text/javascript" src="/bower_components/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/bower_components/angular/angular.min.js"></script>
<script type="text/javascript" src="/bower_components/angular-route/angular-route.min.js"></script>
<script type="text/javascript" src="/bower_components/angularUtils-pagination/dirPagination.js"></script>
<script type="text/javascript" src="/bower_components/bootbox.js/bootbox.js"></script>
<script type="text/javascript" src="/manager-app.js"></script>
<script type="text/javascript" src="/export/list-ctrl.js"></script>
<script type="text/javascript" src="/export/edit-ctrl.js"></script>
</head>
<body>
<ng-view></ng-view>
</header>
</body>
</html>
index.js
var express = require("express");
var bodyParser = require("body-parser");;
var helmet = require("helmet");
var path = require('path');
var app = express();
var folder = path.join(__dirname, '/public');
var MongoClient = require('mongodb').MongoClient;
var mURL = "mongodb://XXXXXXXXXXXXXXXXXxXXXXXXXX";
var port = (process.env.PORT || 10000);
var BASE_API_PATH = "/api/v2";
var moduleExport = require("./api/v2/exportModule.js");
var dbAlberto;
var dbUser;
app.use("/", express.static(path.join(__dirname, "public")));
app.use(bodyParser.json()); //use default json enconding/decoding
app.use(helmet()); //improve security
app.use("/",express.static(path.join(__dirname, 'public')));
app.use("/api/v2/tests", express.static(path.join(__dirname , "public/test.html")));
MongoClient.connect(mURL, {
native_parser: true
}, function(err, database) {
if (err) {
console.log("CANNOT connect to database" + err);
process.exit(1);
}
dbAlberto = database.collection("exports");
dbUser = database.collection("user");
moduleExport.register(app, dbAlberto, dbUser, BASE_API_PATH);
app.listen(port, () => {
console.log("Magic is happening on port " + port);
});
});
exportModule
var exports = module.exports = {};
exports.register = function(app, dbAlberto, dbUser, BASE_API_PATH) {
// Authentication apikey
var key = function(request, callback) {
var d;
dbUser.find({
apikey: request
}).toArray(function(err, sExport) {
if (sExport.length > 0) {
d = 1;
}
else {
d = 0;
}
callback(d);
});
}
function searchFrom(sExport,from,to){
var from = parseInt(from);
var to = parseInt(to);
var res=[];
sExport.forEach((filt)=>{
if(filt.year>=from && filt.year<=to){
res.push(filt);
}
});
return res;
// GET a collection and Search
app.get(BASE_API_PATH + "/export-and-import", function(request, response) {
var url = request.query;
var province = url.province;
var year = url.year;
var importS = url.importS;
var exportS = url.exportS;
var off = 0;
var limite = 100;
var res = request.query.apikey;
var from = url.from;
var to = url.to;
var resul = key(res, function(d) {
if (d > 0) {
if (url.limit != undefined) {
limite = parseInt(url.limit);
off = parseInt(url.offset);
}
if (from != undefined && to != undefined) {
dbAlberto.find({}).toArray(function(err, sExport) {
if (err) {
console.error('WARNING: Error getting data from DB');
response.sendStatus(500); // internal server error
}
else {
if (sExport.length > 0) {
var filted=searchFrom(sExport,from,to);
response.send(filted);
}
else {
console.log("WARNING: There are not any stat with this properties");
response.sendStatus(404); // not found
}
}
});
}
else {
dbAlberto.find({}).skip(off).limit(limite).toArray(function(err, sExport) {
if (err) {
console.error('WARNING: Error getting data from DB');
response.sendStatus(500); // internal server error
}
else {
var filted = sExport.filter((stat) => {
if ((province == undefined || stat.province == province) && (year == undefined || stat.year == year) && (year == undefined || stat.year == year) && (importS == undefined || stat.importS == importS) && (exportS == undefined || stat.exportS == exportS)) {
return stat;
}
});
if (filted.length > 0) {
console.log("INFO: Sending stat: " + JSON.stringify(filted, 2, null));
response.send(filted);
}
else {
console.log("WARNING: There are not any stat with this properties");
response.sendStatus(404); // not found
}
}
});
}
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
// LoadInitialData
app.get(BASE_API_PATH + "/export-and-import/loadInitialData", function(request, response) {
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
dbAlberto.find({}).toArray(function(err, stats) {
if (err) {
console.error('WARNING: Error while getting initial data from DB');
return 0;
}
if (stats.length === 0) {
var initialStats = [{
"province": "jaen",
"year": "2013",
"oil": "375",
"importS": "802",
"exportS": "274"
}];
dbAlberto.insert(initialStats);
console.log("Date insert in db");
response.sendStatus(201, BASE_API_PATH + "/");
}
else {
console.log('INFO: DB has ' + stats.length + ' objects ');
response.sendStatus(200);
}
});
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
/*
// GET a collection
app.get(BASE_API_PATH + "/export-and-import", function(request, response) {
console.log("INFO: New GET request to /export-and-import");
dbAlberto.find({}).toArray(function(err, sExport) {
if (err) {
console.error('WARNING: Error getting data from DB');
response.sendStatus(500); // internal server error
}
else {
console.log("INFO: Sending export and import stats: " + JSON.stringify(sExport, 2, null));
response.send(sExport);
}
});
});
*/
// GET a single resource
app.get(BASE_API_PATH + "/export-and-import/:province", function(request, response) {
var province = request.params.province;
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
if (!province) {
console.log("WARNING: New GET request to /export-and-import-stats/:name without name, sending 400...");
response.sendStatus(400); // bad request
}
else {
console.log("INFO: New GET request to /export-and-import-stats/" + province);
dbAlberto.find({
province: province
}).toArray(function(err, sExport) {
if (err) {
console.error('WARNING: Error getting data from DB');
response.sendStatus(500); // internal server error
}
else {
if (sExport.length > 0) {
console.log("INFO: Sending stats: " + JSON.stringify(sExport, 2, null));
response.send(sExport);
}
else {
console.log("WARNING: There are not any export stats with name " + province);
response.sendStatus(404); // not found
}
}
});
}
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
//GET all stats of one year
app.get(BASE_API_PATH + "/export-and-import/:province/:year", function(request, response) {
var province = request.params.province;
var year = request.params.year;
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
if (!province) {
console.log("WARNING: New GET request to /export-and-import/ without province, sending 400...");
response.sendStatus(400); // bad request
}
else {
console.log("INFO: New GET request to /export-and-import/" + province);
dbAlberto.find({
province: province,
year: year
}).toArray(function(err, sExport) {
if (err) {
console.error('WARNING: Error getting data from DB');
response.sendStatus(500); // internal server error
}
else {
if (sExport.length > 0) {
console.log("INFO: Sending stats: " + JSON.stringify(sExport, 2, null));
response.send(sExport);
}
else {
console.log("WARNING: There are not any export stats with name " + province + " and " + year);
response.sendStatus(404); // not found
}
}
});
}
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
//POST over a collection
app.post(BASE_API_PATH + "/export-and-import", function(request, response) {
var newStats = request.body;
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
if (!newStats) {
console.log("WARNING: New POST request to /export-and-import without stats, sending 400...");
response.sendStatus(400); // bad request
}
else {
console.log("INFO: New POST request to /export-and-import with body: " + JSON.stringify(newStats, 2, null));
if (!newStats.province || !newStats.year || !newStats.oil || !newStats.importS || !newStats.exportS) {
console.log("WARNING: The stat " + JSON.stringify(newStats, 2, null) + " is not well-formed, sending 422...");
response.sendStatus(422); // unprocessable entity
}
else {
dbAlberto.find({
province: newStats.province,
year: newStats.year
}).toArray(function(err, sExport) {
if (err) {
console.error('WARNING: Error getting data from DB');
response.sendStatus(500); // internal server error
}
else {
var sExportBefore = sExport.filter((result) => {
return (result.province.localeCompare(newStats.province, "en", {
'sensitivity': 'base'
}) === 0);
});
if (sExportBefore.length > 0) {
console.log("WARNING: The contact " + JSON.stringify(newStats, 2, null) + " already extis, sending 409...");
response.sendStatus(409); // conflict
}
else {
console.log("INFO: Adding contact " + JSON.stringify(newStats, 2, null));
dbAlberto.insert(newStats);
response.sendStatus(201); // created
}
}
});
}
}
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
//POST over a single resource
app.post(BASE_API_PATH + "/export-and-import/:province/:year", function(request, response) {
var province = request.params.province;
var year = request.params.year;
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
console.log("WARNING: New POST request to /export-and-import-stats/" + province + " and " + year + ", sending 405...");
response.sendStatus(405); // method not allowed
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
//PUT over a collection
app.put(BASE_API_PATH + "/export-and-import", function(request, response) {
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
console.log("WARNING: New PUT request to /export-and-import-stats, sending 405...");
response.sendStatus(405); // method not allowed
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
//PUT over a single resource
app.put(BASE_API_PATH + "/export-and-import/:province/:year", function(request, response) {
var updateExp = request.body;
var province = request.params.province;
var year = request.params.year;
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
if (!updateExp) {
console.log("WARNING: New PUT request to /export-and-import-stats/ without contact, sending 400...");
response.sendStatus(400); // bad request
}
else {
console.log("INFO: New PUT request to /export-and-import-stats/" + province + " with data " + JSON.stringify(updateExp, 2, null));
if (!updateExp.province || !updateExp.year || !updateExp.oil || !updateExp.importS || !updateExp.exportS || updateExp.province !== province || updateExp.year !== year) {
console.log("WARNING: The contact " + JSON.stringify(updateExp, 2, null) + " is not well-formed, sending 422...");
response.sendStatus(422); // unprocessable entity
}
else {
dbAlberto.find({
province: province,
$and: [{
year: year
}]
}).toArray(function(err, sExport) {
if (err) {
console.error('WARNING: Error getting data from DB');
response.sendStatus(500); // internal server error
}
else {
if (sExport.length > 0) {
dbAlberto.update({
province: province,
year: year
}, updateExp);
console.log("INFO: Modifying contact with name " + province + " with data " + JSON.stringify(updateExp, 2, null));
response.send(updateExp); // return the updated contact
}
else {
console.log("WARNING: There are not any stats with provinc " + province);
response.sendStatus(404); // not found
}
}
});
}
}
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
//DELETE over a collection
app.delete(BASE_API_PATH + "/export-and-import", function(request, response) {
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
console.log("INFO: New DELETE request to /export-and-import-stats");
dbAlberto.remove({}, {
multi: true
}, function(err, doc) {
if (err) {
console.error('WARNING: Error removing data from DB');
response.sendStatus(500); // internal server error
}
else {
var n = doc.result.n;
if (n !== 0) {
console.log("INFO: Remove: " + n + " stats, sending 204...");
response.sendStatus(204); // no content
}
else {
console.log("WARNING: There are no contacts to delete");
response.sendStatus(404); // not found
}
}
});
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
//DELETE over a single resource
app.delete(BASE_API_PATH + "/export-and-import/:province/:year", function(request, response) {
var province = request.params.province;
var year = request.params.year;
var res = request.query.apikey;
var resul = key(res, function(d) {
if (d > 0) {
if (!province || !year) {
console.log("WARNING: New DELETE request to /export-and-import-stats/:name without name, sending 400...");
response.sendStatus(400); // bad request
}
else {
console.log("INFO: New DELETE request to /export-and-import-stats/" + province + " and " + year);
dbAlberto.remove({
province: province,
year: year
}, {}, function(err, doc) {
if (err) {
console.error('WARNING: Error removing data from DB');
response.sendStatus(500); // internal server error
}
else {
var n = doc.result.n;
if (n !== 0) {
console.log("INFO: The stat with name " + province + " and year " + year + " has been succesfully deleted, sending 204...");
response.sendStatus(204); // no content
}
else {
console.log("WARNING: There are no contacts to delete");
response.sendStatus(404); // not found
}
}
});
}
}
else {
if (!request.query.apikey) {
console.log("Err401: Login error.");
response.sendStatus(401);
}
else {
console.log("Err403: Login error.");
response.sendStatus(403);
}
}
});
});
}
Thanks in advance !

javasctipt - asynchronous issue for return value

I am working in MEAN STACK application and i want to set mail's parameters dynamic.
route.js
var Helper = require("../helper.js");
router
.route("/api/user/registration")
.POST(function (req, res) {
//after user insert send mail
Helper.sendCustomEmail(params, function (error, response) {
if (error) {
console.log("Mail : " + error);
res.json({"status": 0, "error": {"other": "Oops! something went wrong, please try again later"}});
} else {
console.log("Message sent");
res.json({status: 1, message: 'Thank you for registration. You will get verification email soon', token: res.locals.user.jwttoken});
}
});
});
Helper.js
exports.sendCustomEmail = function(params, callback) {
//Include nodejs mailer and smtp module
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
//read header email template
var headerHtml = params.fs.readFileSync(basePath + "emailHeader.html").toString();
//read footer email template
var footerHtml = params.fs.readFileSync(basePath + "emailFooter.html").toString();
//Your dynamic template html only
var dynamicMessage = params.message;
var message = headerHtml + dynamicMessage + footerHtml;
message = message.replace(/##DOMAIN_URL##/g, "http://" + params.domainUrl);
// create reusable transporter object using the default SMTP transport
var transporter = nodemailer.createTransport(smtpTransport({
host: this.getSiteSetting("SMTP_HOST"),
secure: true,
auth: {
user: this.getSiteSetting("SMTP_USER"),
pass: this.getSiteSetting("SMTP_PSSSWORD")
},
tls: {
rejectUnauthorized: false
}
}));
transporter.sendMail({
from: this.getSiteSetting("SMTP_FROM"),
to: params.to, // receiver
subject: params.subject,
html: message // body
}, function(error, response) { //callback
callback(error, response);
});
};
var SiteSetting = require('../models/siteSetting');
exports.getSiteSetting = function($keyword) {
if ($keyword !== undefined && $keyword !== null && $keyword !== "") {
SiteSetting.findOne({setting_key : $keyword},function(err,siteSetting){
if(err){
return null;
}else{
if(siteSetting !== null){
console.log(siteSetting.setting_value);
return siteSetting.setting_value;
}
}
});
}else{
return null;
}
};
dependencies
"express" => "version": "4.13.4",
"mongoose" => "version": "4.4.4",
"mongodb" => "version": "2.4.9",
"OS" => "ubuntu 14.04 lts 32bit",
from the following code SiteSetting function console.log print properly but before return mail send error occur.
Please give me a proper guideline for this code.
This can be solved as bellow.
exports.sendCustomEmail = function(params, callback) {
//Include nodejs mailer and smtp module
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
//read header email template
var headerHtml = fs.readFileSync(basePath + "app/client/views/layout/emailTemplates/emailHeader.html").toString();
//read footer email template
var footerHtml = fs.readFileSync(basePath + "app/client/views/layout/emailTemplates/emailFooter.html").toString();
//Your dynamic template html only
var dynamicMessage = params.message;
var message = headerHtml + dynamicMessage + footerHtml;
message = message.replace(/##DOMAIN_URL##/g, "http://" + params.domainUrl);
var host = null;
var user = null;
var pass = null;
var from = null;
this.getSiteSetting("SMTP_HOST", function(res) {
host = res;
setParams();
});
this.getSiteSetting("SMTP_USER", function(res) {
user = res;
setParams();
});
this.getSiteSetting("SMTP_PASS", function(res) {
pass = res;
setParams();
});
this.getSiteSetting("MAIL_FROM", function(res) {
from = res;
setParams();
});
var setParams = function() {
if (host !== null && user !== null && pass !== null && from !== null) {
// create reusable transporter object using the default SMTP transport
var transporter = nodemailer.createTransport(smtpTransport({
host: host,
//port: 25,
//port: 465,
secure: true,
auth: {
user: user,
pass: pass
},
tls: {
rejectUnauthorized: false
}
}));
transporter.sendMail({
from: from,
to: params.to, // receiver
subject: params.subject,
html: message // body
}, function(error, response) { //callback
callback(error, response);
});
}
};
}
var SiteSetting = require('../models/siteSetting');
exports.getSiteSetting = function(keyword, callback) {
if (keyword !== undefined && keyword !== null && keyword !== "") {
SiteSetting.findOne({ setting_key: keyword }, function(err, siteSetting) {
if (err) {
callback(null);
} else {
if (siteSetting !== null) {
//console.log(siteSetting.setting_value);
callback(siteSetting.setting_value);
}else{
callback(null);
}
}
});
} else {
callback(null);
}
};

How to use this node.js module in some file

This is my 3rd party node-js module:
var knox = require('knox')
, Resource = require('deployd/lib/resource')
, httpUtil = require('deployd/lib/util/http')
, formidable = require('formidable')
, fs = require('fs')
, util = require('util')
, path = require('path');
function S3Bucket(name, options) {
Resource.apply(this, arguments);
if (this.config.key && this.config.secret && this.config.bucket) {
this.client = knox.createClient({
key: this.config.key
, secret: this.config.secret
, bucket: this.config.bucket
});
}
}
util.inherits(S3Bucket, Resource);
module.exports = S3Bucket;
S3Bucket.label = "S3 Bucket";
S3Bucket.prototype.clientGeneration = true;
S3Bucket.events = ["upload", "get", "delete"];
S3Bucket.basicDashboard = {
settings: [{
name: 'bucket'
, type: 'string'
}, {
name: 'key'
, type: 'string'
}, {
name: 'secret'
, type: 'string'
}]
};
S3Bucket.prototype.handle = function (ctx, next) {
var req = ctx.req
, bucket = this
, domain = {url: ctx.url};
if (!this.client) return ctx.done("Missing S3 configuration!");
if (req.method === "POST" && !req.internal && req.headers['content-type'].indexOf('multipart/form-data') === 0) {
var form = new formidable.IncomingForm();
var remaining = 0;
var files = [];
var error;
var uploadedFile = function(err) {
if (err) {
error = err;
return ctx.done(err);
} else if (!err) {
remaining--;
if (remaining <= 0) {
if (req.headers.referer) {
httpUtil.redirect(ctx.res, req.headers.referer || '/');
} else {
ctx.done(null, files);
}
}
}
};
form.parse(req)
.on('file', function(name, file) {
remaining++;
if (bucket.events.upload) {
bucket.events.upload.run(ctx, {url: ctx.url, fileSize: file.size, fileName: file.filename}, function(err) {
if (err) return uploadedFile(err);
bucket.uploadFile(file.filename, file.size, file.mime, fs.createReadStream(file.path), uploadedFile);
});
} else {
bucket.uploadFile(file.filename, file.size, file.mime, fs.createReadStream(file.path), uploadedFile);
}
})
.on('error', function(err) {
ctx.done(err);
error = err;
});
req.resume();
return;
}
if (req.method === "POST" || req.method === "PUT") {
domain.fileSize = ctx.req.headers['content-length'];
domain.fileName = path.basename(ctx.url);
if (this.events.upload) {
this.events.upload.run(ctx, domain, function(err) {
if (err) return ctx.done(err);
bucket.upload(ctx, next);
});
} else {
this.upload(ctx, next);
}
} else if (req.method === "GET") {
if (ctx.res.internal) return next(); // This definitely has to be HTTP.
if (this.events.get) {
this.events.get.run(ctx, domain, function(err) {
if (err) return ctx.done(err);
bucket.get(ctx, next);
});
} else {
this.get(ctx, next);
}
} else if (req.method === "DELETE") {
if (this.events['delete']) {
this.events['delete'].run(ctx, domain, function(err) {
if (err) return ctx.done(err);
bucket.del(ctx, next);
});
} else {
this.del(ctx, next);
}
} else {
next();
}
};
S3Bucket.prototype.uploadFile = function(filename, filesize, mime, stream, fn) {
var bucket = this;
var headers = {
'Content-Length': filesize
, 'Content-Type': mime
};
this.client.putStream(stream, filename, headers, function(err, res) {
if (err) return ctx.done(err);
if (res.statusCode !== 200) {
bucket.readStream(res, function(err, message) {
fn(err || message);
});
} else {
fn();
}
});
};
S3Bucket.prototype.upload = function(ctx, next) {
var bucket = this
, req = ctx.req;
var headers = {
'Content-Length': req.headers['content-length']
, 'Content-Type': req.headers['content-type']
};
this.client.putStream(req, ctx.url, headers, function(err, res) {
if (err) return ctx.done(err);
if (res.statusCode !== 200) {
bucket.readStream(res, function(err, message) {
ctx.done(err || message);
});
} else {
ctx.done();
}
});
req.resume();
};
S3Bucket.prototype.get = function(ctx, next) {
var bucket = this;
var url = 'https://s3.amazonaws.com/' + this.config.bucket + ctx.url;
httpUtil.redirect(ctx.res, url);
};
S3Bucket.prototype.del = function(ctx, next) {
var bucket = this;
this.client.deleteFile(ctx.url, function(err, res) {
if (err) ctx.done(err);
if (res.statusCode !== 200) {
bucket.readStream(res, function(err, message) {
ctx.done(err || message);
});
} else {
ctx.done();
}
});
};
S3Bucket.prototype.readStream = function(stream, fn) {
var buffer = '';
stream.on('data', function(data) {
buffer += data;
}).on('end', function() {
fn(null, buffer);
}).on('error', function(err) {
fn(err);
});
};
inside s3-amazon-aws folder hence I do var s3bucket = require('s3-amazon-aws');
But, now if I have to call the handle function of the module, how do I do that? Also it requires 2 parameters such as ctx,next. How do I get those parameters?
Any help would be appreciated.
The module exports the S3Bucket constructor function. Use it to create a new object. You can then call the handle() method on this object (since it's part of the object's prototype).
var S3Bucket = require('s3-amazon-aws');
var bucket = new S3Bucket(name, options);
bucket.handle(ctx, next)
Regarding the various arguments you need to read the documentation of the library.

Categories