Nodejs - Disable or destroy vhost subdomains/proxies - node.js

I have the follow code which dynamically proxies a website to a subdomain.
var app = require('express')();
var proxy = require('express-http-proxy');
var vhost = require('vhost');
app.get('/make', function (req, res) {
app.use(vhost('sub1.mysite.com', proxy("www.example.com");
res.send("Proxy Created");
});
app.get('/destroy', function (req, res) {
// Disable or Destroy the subdomain/proxy created above
// ???
});
app.listen(8080);
How would I disable or destroy this newly created proxy/subdomain from the /destroy route?

app.js
var Ex = require('express');
var app = Ex();
app.listen(8080);
var DomainProxy = require('./DomainProxy').DomainProxy;
// Pass express instance 'app' into dp,
// dp will create a vhost router internally
var dp = new DomainProxy(app);
var proxies = [
{ domain: '1.local', site: 'http://www.bing.com' },
{ domain: '2.local', site: 'http://samanthagooden.com' },
{ domain: '3.local', site: 'http://www.courtleigh.com' },
{ domain: '4.local', site: 'http://example.com' }
];
dp.create(proxies);
app.get('/make', function (req, res) {
var subDomain = 'sub1.mysite.com';
var site = 'http://www.example.com'; // site need to contain 'http://', else dp link rewrite will not work correctly
dp.create([{domain:subDomain,site:site}]);
res.send("Proxy Created");
});
app.get('/destroy', function (req, res) {
var subDomain = 'sub1.mysite.com';
dp.destroy(subDomain);
res.send("Proxy Destroyed");
});
DomainProxy.js
I also incorporated my answer from Nodejs - BrowserSync running on express server
var proxy = require('express-http-proxy');
var url = require('url');
var vhost = require('vhost');
var Ex = require('express');
var DomainProxy = (function () {
function DomainProxy(app) { // DomainProxy
this.list = []; // vhost list array
this.router = Ex.Router();
app.use(this.router);
}
DomainProxy.prototype.create = function (proxies) {
proxies.forEach(p => {
// Destroy old proxy first
this.destroy(p.domain);
this.list.push(p.domain); // Add domain into list
this.router.use(vhost(p.domain, proxy(p.site, {
forwarDomainProxyath: (req, res) => url.parse(req.url).path,
intercept: (rsp, data, req, res, callback) => {
if (res._headers['content-type']) {
var contentType = res._headers['content-type'];
// console.log(contentType);
if (
contentType.indexOf('text') !== -1 ||
contentType.indexOf('javascript') !== -1
) {
// Rewrite links
var reg = new RegExp(p.site, 'g');
res.send(data.toString().replace(reg, ''));
} else {
res.send(data);
}
} else {
res.send(data);
}
}
})));
})
};
DomainProxy.prototype.destroy = function (domain) {
var i = this.list.indexOf(domain);
if (i !== -1) {
this.list.splice(i, 1);
this.router.stack.splice(i, 1);
}
};
return DomainProxy;
} ());
exports.DomainProxy = DomainProxy;

Related

Parse Server : user information cannot be changed on cloud code

I want to change user information in the cloud but information does not change on the cloud
index.js
// Example express application adding the parse-server module to expose Parse
// compatible API routes.
var express = require('express');
var ParseServer = require('parse-server').ParseServer;
var path = require('path');
var databaseUri = process.env.DATABASE_URI || process.env.MONGODB_URI;
if (!databaseUri) {
console.log('DATABASE_URI not specified, falling back to localhost.');
}
var api = new ParseServer({
databaseURI: databaseUri || 'mongodb://localhost:27017/meet2me',
cloud: __dirname + '/cloud/main.js',
appId: 'app',
masterKey: 'burak21', //Add your master key here. Keep it secret!
serverURL: 'http://localhost:1337/parse', // Don't forget to change to https if needed
liveQuery: {
classNames: ["Posts", "Comments"] // List of classes to support for query subscriptions
}
});
// Client-keys like the javascript key or the .NET key are not necessary with parse-server
// If you wish you require them, you can set them as options in the initialization above:
// javascriptKey, restAPIKey, dotNetKey, clientKey
var app = express();
// Serve static assets from the /public folder
app.use('/public', express.static(path.join(__dirname, '/public')));
// Serve the Parse API on the /parse URL prefix
var mountPath = process.env.PARSE_MOUNT || '/parse';
app.use(mountPath, api);
// Parse Server plays nicely with the rest of your web routes
app.get('/', function(req, res) {
res.status(200).send('I dream of being a website. Please star the parse-server repo on GitHub!');
});
// There will be a test page available on the /test path of your server url
// Remove this before launching your app
app.get('/test', function(req, res) {
res.sendFile(path.join(__dirname, '/public/test.html'));
});
var port = process.env.PORT || 1337;
var httpServer = require('http').createServer(app);
httpServer.listen(port, function() {
console.log('parse-server-example running on port ' + port + '.');
});
// This will enable the Live Query real-time server
ParseServer.createLiveQueryServer(httpServer);
Main.js
Parse.Cloud.define('changeSearchStatus', async (request) => {
//Parse.Cloud.useMasterKey();
var search_yn = request.params.search_yn == true ? '1' : '0';
var only_gold_write = request.params.only_gold_write == true ? '1' : '0';
var only_gold_call = request.params.only_gold_call == true ? '1' : '0';
var min_age = request.params.min_age;
var max_age = request.params.max_age;
var query = new Parse.Query("User");
query.equalTo("objectId", request.params.token);
var out_data = {
error:"0",
mesaj:'success'
};
query.first({ useMasterKey: true },{
success: function (user) {
console.log("USERBILGI : "+user.get("email"));
user.set("search_yn", search_yn);
user.set("only_gold_write", only_gold_write);
user.set("only_gold_call", only_gold_call);
user.set("age_lower", min_age);
user.set("age_upper", max_age);
user.save(null, { useMasterKey: true });
}, error: function (error) {
var out_data = {
error:"1",
mesaj:'Fail'
};
console.log("error HATA");
}
});
return out_data;
});
İonic Code
async changeSearchStatus(){
console.log("gelen:"+this.rangedualKnobs+" : "+this.rangedualKnobs['lower']);
var body = {
useMasterKey: true,
token:this.apiService.getToken(),
search_yn:this.search_yn,
only_gold_write:this.only_gold_write,
only_gold_call:this.only_gold_call,
min_age:this.rangedualKnobs['lower'],
max_age:this.rangedualKnobs['upper']
};
const response = await Parse.Cloud.run("changeSearchStatus", body);
}
Console Output :
info: Ran cloud function changeSearchStatus for user undefined with:
Input: {"useMasterKey":true,"token":"X38ZMM2At9","search_yn":1,"only_gold_write":true,"only_gold_call":false,"min_age":"18","max_age":"55"}
Result: {"error":"0","mesaj":"success"} {"functionName":"changeSearchStatus","params":{"useMasterKey":true,"token":"X38ZMM2At9","search_yn":1,"only_gold_write":true,"only_gold_call":false,"min_age":"18","max_age":"55"}}
it does not give an error but the user information does not change
Try the following code for your cloud code:
Parse.Cloud.define('changeSearchStatus', async (request) => {
//Parse.Cloud.useMasterKey();
var search_yn = request.params.search_yn == true ? '1' : '0';
var only_gold_write = request.params.only_gold_write == true ? '1' : '0';
var only_gold_call = request.params.only_gold_call == true ? '1' : '0';
var min_age = request.params.min_age;
var max_age = request.params.max_age;
var query = new Parse.Query("User");
query.equalTo("objectId", request.params.token);
var out_data = {
error:"0",
mesaj:'success'
};
try {
const user = await query.first({ useMasterKey: true });
console.log("USERBILGI : "+user.get("email"));
user.set("search_yn", search_yn);
user.set("only_gold_write", only_gold_write);
user.set("only_gold_call", only_gold_call);
user.set("age_lower", min_age);
user.set("age_upper", max_age);
await user.save(null, { useMasterKey: true });
} catch (e) {
var out_data = {
error:"1",
mesaj:'Fail'
};
console.log("error HATA");
}
return out_data;
});

MEAN API using node-restful no response

I'm trying to setup API for multiple projects that use same database structure (running on same CMS) but when I'm trying to reach some data I get no response.
index.js
var express = require("express");
var cors = require("cors");
var mongoose = require("mongoose");
var bodyParser = require("body-parser");
var methodOverride = require("method-override");
var _ = require("lodash");
var passport = require("passport");
var dbconfig = require("./app/config/database");
// Create the application
var app = express();
var user = require("./app/routes/User");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(methodOverride('X-HTTP-Method-Override'));
var connections = [];
// Auto CORS
app.use(cors());
/* Mnual CORS Start
app.use(function(req, res, next){
res.header("Access-Controll-Allow-Origin", "*");
res.header("Access-Controll-Allow-Methods", "GET,PUT,POST,DELETE");
res.header("Access-Controll-Allow-Headers", "Content-Type");
next();
});
/* Manual Cords end */
// Passport Middleware
app.use(passport.initialize());
app.use(passport.session());
require("./app/config/passport")(passport);
app.get("/", (req, res) => {
res.json({ msg: "Nothing here mate" });
});
//------------ THIS IS WORKING ----------------
app.get("/db/:database/navigation", (req, res) => {
var dbname = req.params.database;
var conn = connections[dbname];
var navs = conn.model("navigation", app.models[dbname].navigation);
// Send json data/error
if (navs) navs.find({}, (err, data) => res.json(data));
else res.json({ error: true, msg: "Model not found" });
});
// -------------------------------------------------------
// Setup databases for all projects
_.each(dbconfig.databases, db => {
var appModels = require("./app/models/index");
var processed = 0;
// We will use prefix for all routes /db/:database/
var routePrefix = "/db/" + db.name;
// Use user section
app.use(routePrefix + "/user", user);
// Connection callback - we need to wait for modules to initialize
var connect = () => {
// Initialize connection
connections[db.name] = new mongoose.Mongoose().createConnection(db.url);
// Create some callbacks
connections[db.name].on("connected", () => { console.log("Connected to database " + db.url); });
connections[db.name].on("error", onDatabaseError)
// Once we initialize connection, we need to setup all routes
connections[db.name].once("open", function () {
// Load routes
var routes = require('./app/routes');
// Loop trough routes and use all of them
_.each(routes, function (controller, route) {
var newRoute = routePrefix + route;
app.use(newRoute, controller(app, newRoute, db.name));
});
});
};
// Initialize models
_.each(appModels, (model, index) => {
// Create object if doenst exist
if (app.models == null)
app.models = {};
if (app.models[db.name] == null) {
app.models[db.name] = { [model.name]: model.model };
}
else {
app.models[db.name] = Object.assign(app.models[db.name], { [model.name]: model.model });
}
processed++;
// if this was the last process we are ready to connect
if (processed === appModels.length)
connect();
});
});
app.listen(3000);
app/models/index.js
module.exports = [
{
name: "navigation",
model: require('./Navigation.js')
},
...
];
app/routes.js
module.exports = {
'/navigation': require('./controllers/NavigationController'),
....
};
app/controllers/NavigationController.js
var restful = require("node-restful");
module.exports = function(app, route, dbname){
console.log(route);
var rest = restful.model(
"navigation",
app.models[dbname].navigation
).methods(['get', 'put', 'post', 'delete']);
rest.register(app, route);
// Return middleware
return function(req, res, next){
next();
};
};
Navigation.js is basically just a schema. If I set up route manually like this:
app.get("/db/:database/navigation", (req, res) => {
var dbname = req.params.database;
var conn = connections[dbname];
var navs = conn.model("navigation", app.models[dbname].navigation);
// Send json data/error
if (navs) navs.find({}, (err, data) => res.json(data));
else res.json({ error: true, msg: "Model not found" });
});
it works just fine. I guess I need to assign connection somewhere to restful but I have no idea where. If I use single connection with mongoose.connect() everything works perfectly, but that's not what I need :)
Does anyone have any idea what to do next to get this to work? Will appreciate any help, thanks.
Kind of dug into it and made an extension to change driver reference
Here are all the changes, hope it helps someone in future :)
extensions/restful/index.js
var restful = require("node-restful"),
model = require("./model"),
mongoose = require('mongoose');
exports = module.exports = restful;
exports.model = model;
exports.mongoose = mongoose;
extensions/restful/model.js
exports = module.exports = model;
exports.changeDriver = function(driver){
mongoose = driver;
}
// original model function from node-restful/lib/model.js
function model() {
var result = mongoose.model.apply(mongoose, arguments),
default_properties = defaults();
if (1 === arguments.length) return result;
for (var key in default_properties) {
result[key] = default_properties[key];
}
return result;
}
app/controllers/navigation.js
var restful = require("../extensions/restful");
module.exports = function(app, route, db)
{
restful.model.changeDriver(db.mongoose);
// Setup controller REST
var rest = restful.model(
"navigation",
app.models[db.name].navigation
).methods(['get', 'put', 'post', 'delete']);
// Register this endpoint with the application
rest.register(app, route);
// Return middleware
return function(req, res, next){
next();
};
};
index.js
....
var connect = () => {
// Initialize connection
var $db = databases[_db.name] = {
mongoose: new mongoose.Mongoose(),
name: _db.name
};
$db.mongoose.connect(_db.url);
// Create some callbacks
$db.mongoose.connection.on("connected", () => { console.log("Connected to database " + _db.url); });
$db.mongoose.connection.on("error", (err) => { console.log("Database error: " + err); });
// Once we initialize connection, we need to setup all routes
$db.mongoose.connection.once("open", function () {
// Custom routes for user section
var userRoutes = new UserRoutes($db.mongoose);
app.use(routePrefix + "/user", userRoutes.getRouter());
// Load routes
var routes = require('./app/routes');
// Loop trough routes and use all of them
_.each(routes, function (controller, route) {
var newRoute = routePrefix + route;
app.use(newRoute, controller(app, newRoute, $db));
});
});
};
....

How do I modularize my Node.js, express project?

I have created a API for different webpages with some CRUD functionality for POST, GET, etc. methods using Node.js, express and mongoose. I also have a big app.js file, where my routing logic and functions for CRUD methods reside.
So in the app.js file, I have to do the CRUD functionality and routing logic for every model in my models folder. This is quite much for on file, how can I separate the CRUD logic for my models, and the routing logic? So that it still works as normal without hosing my file?
I was thinking to separate the CRUD into a "controllers" folder and the routing into the "routes" folder, but I dont know how exactly, and what to require at what place..
My app.js looks like:
var express = require('express');
var app = express();
var bodyParser = require("body-parser");
var morgan = require("morgan");
var routes = require('./routes');
var cors = require('cors')
//configure app
app.use(morgan('dev')); //log requests to the console
//configure body parser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 5000;
//DATABASE SETUP
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/DNZ'); //connect to uor datbaase
//Handle the connection event, get reference to database.
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("DB connection alive");
});
//DNZ models live here
var FA = require('./models/DNZmodels/FA');
var FP = require('./models/DNZmodels/FP');
//ROUTES FOR OUR API
//=============================================================================
//create our router
var router = express.Router();
//middleware to use for all requests
router.use(function(req, res, next) {
// do logging
console.log('Something is happening.');
console.log('Today is:', Date())
next();
});
//test route to make sure everything is working (accessed at GET http://localhost:5000/DNZ/)
router.get('/', function(req, res) {
res.json({ message: 'Welcome to DNZ API!' });
});
//on routes that end in /FA
//----------------------------------------------------
router.route('/FA')
// create a FA (accessed at POST http://localhost:8080/DNZ/FA)
.post(function(req, res) {
//console.log(req.body);
//console.log(req.body.params);
//res.setHeader('Content-Type', 'application/json')
//res.send(JSON.stringify(req.body));
/*
var timestamp = req.body.Timestamp;
var prognostizierterBetriebswert = req.body.PrognostizierterBetriebswert;
var posFlexPot = req.body.posFlexPot;
var negFlexPot = req.body.negFlexPot;
var leistungsuntergrenze = req.body.Leistungsuntergrenze;
var leistungsobergrenze = req.body.Leistungsobergrenze;
var posGesEnergie = req.body.posGesEnergie;
var negGesEnergie = req.body.negGesEnergie;
var preissignal = req.body.Preissignal;
var dummy1 = req.body.Dummy1;
var dummy2 = req.body.Dummy2;
var dummy3 = req.body.Dummy3;
var fa = new FA({
Timestamp: timestamp,
Leistungsuntergrenze: leistungsuntergrenze,
Leistungsobergrenze:leistungsobergrenze,
PrognostizierterBetriebswert :prognostizierterBetriebswert,
posFlexPot: posFlexPot,
negFlexPot:negFlexPot,
posGesEnergie: posGesEnergie,
negGesEnergie: negGesEnergie,
Preissignal:preissignal,
Dummy1: dummy1,
Dummy2: dummy2,
Dummy3: dummy3
})
*/
//fa.name = req.body.name;
console.log("Erzeugen der Instanz FA..");
//console.log(Dummy1);
//res.send(JSON.stringify(timestamp));
// create a new instance of the FA model
var fa = new FA(req.body);
//SAVE the new instance
fa.save(function(err) {
if (err) {
console.log(err);
res.status(400);
res.send(err);
}
else {
console.log("Instanz FA in Datenbank erzeugt!");
res.status(200);
res.json({ message: 'FA-Instance created in datbase!' });
}
});
})
// get all the FAs (accessed at GET http://localhost:8080/DNZ/FA)
.get(function(req, res) {
FA.find(function(err, fas) {
if (err)
res.send(err);
res.json(fas);
});
});
//on routes that end in /FA/:FA_id
//----------------------------------------------------
router.route('/FA/:FA_id')
// get the bear with that id
.get(function(req, res) {
FA.findById(req.params.bear_id, function(err, fa) {
if (err)
res.send(err);
res.json(fa);
});
})
/*
* Athlete.
find().
where('sport').equals('Tennis').
where('age').gt(17).lt(50). //Additional where query
limit(5).
sort({ age: -1 }).
select('name age').
exec(callback);
*/
// update the bear with this id
.put(function(req, res) {
FA.findById(req.params.FA_id, function(err, fa) {
if (err)
res.send(fa);
//bear.name = req.body.name;
/*
FA.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'FA updated!' });
});
*/
});
});
/*
// delete the bear with this id
.delete(function(req, res) {
FA.remove({
_id: req.params.bear_id
}, function(err, FA) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
*/
//*************************************************************************
//CREATE FP ROUTE
//*************************************************************************
router.route('/FP')
// create a FA (accessed at POST http://localhost:8080/DNZ/FP)
.post(function(req, res) {
//res.setHeader('Content-Type', 'application/json')
console.log("Erzeugen der Instanz FP..");
// create a new instance of the FP model
var fp = new FP(req.body);
//SAVE the new instance
fp.save(function(err) {
if (err) {
console.log(err);
res.status(400);
res.send(err);
}
else {
console.log("Instanz FP in Datenbank erzeugt!");
res.status(200);
res.json({ message: 'FP-Instance created in datbase!' });
}
});
})
// get all the FAs (accessed at GET http://localhost:8080/DNZ/FA)
.get(function(req, res) {
FP.find(function(err, fps) {
if (err) {
console.log(err);
res.status(400);
res.send(err);
}
else {
//res.send("Willkommen auf /FP");
res.json(fps);
}
});
});
//REGISTER OUR ROUTES -------------------------------and listen to requests
app.use('/DNZ', router);
//START THE SERVER
//=============================================================================
// set static directories
app.use(express.static('./dist'));
app.use(cors());
// Define Routes
var index = require('./routes/index');
var users = require('./routes/users');
//Set up routes
routes.init(app)
//run
app.listen(port);
console.log('Listen on port: ' + port);
console.log('Server started, Listening on port ', port);
This is primarily opinion based, but I had the same thing a while back and developed a way to extract route/model logic from the main file, using the module require-dir
In my app.js
/**
* Process ALL routes from routes dir utilising require-dir
*
* Allows us to include an entire directory, without replicating
* code, creating similar routes on a per end-point basis. This
* nicely keeps all end-point routes separate.
*/
var routes = requireDir('./routes');
for(var x in routes) {
application.use('/', routes[x]); // here, application is your express server instance
}
Then create a directory called routes and add whatever, for instance routes/branding.js:
var expressFramework = require('express');
var Branding = require('../models/branding');
var responseHelper = require('../shared/responseHelper');
var responseStatusCodes = require('../shared/responseStatusCodes');
var responseMessages = require('../shared/responseMessages');
var queryHelper = require('../shared/queryHelper');
var routerObject = expressFramework.Router();
var branding = new Branding();
var responsehelper = new responseHelper();
var queryhelper = new queryHelper();
/**
* Endpoint /branding/{chain_id}/{site_id}
*/
routerObject.get('/branding/:chain_id/:site_id', function(req, res, next) {
var requiredFields = [
{
chain_id: true, where: 'path'
},
{
site_id: true, where: 'path'
}
];
if (!queryhelper.authenticateToken(req.headers.authorization)) {
responsehelper.sendResponse(res, responseStatusCodes.STATUS_UNAUTHORISED,
responseMessages.RESPONSE_AUTHENTICATION_FAILED);
return;
}
if (!queryhelper.validateQuery(req, requiredFields)) {
responsehelper.sendResponse(res, responseStatusCodes.STATUS_INVALID_QUERY_PARAMS,
responseMessages.RESPONSE_INVALID_QUERY_PARAMS);
return;
}
branding.getBranding(req, function(err, results, pagination) {
if (err) return next(err);
if (results.length >= 1) {
responsehelper.sendResponse(res, responseStatusCodes.STATUS_OK, results);
} else {
responsehelper.sendResponse(res, responseStatusCodes.STATUS_NOT_FOUND,
responseMessages.RESPONSE_NO_RECORDS_FOUND);
}
});
});
module.exports = routerObject;
The key point here, is that you eventually export the express Router object, which your application, can 'use'. You'll also notice, that branding uses an include var Branding = require('../models/branding'); - This contains all the logic, whereas the route contains the end point definitions only, a snippet:
var Promise = require('bluebird');
var db = require('../shared/db');
var queryHelper = require('../shared/queryHelper');
var schemas = require('../schemas/schemas');
var _ = require('lodash');
var serverSettings = require('../shared/coreServerSettings');
// Create new instance of mysql module
var connection = new db();
var queryhelper = new queryHelper();
var queryAndWait = Promise.promisify(connection.query);
// Branding Object
var Branding = function(data) {
this.data = data;
};
Branding.prototype.data = {};
/**
* Branding methods
*/
Branding.prototype.getBranding = function(req, callback) {
var params = [];
var queryFoundRows = `select FOUND_ROWS() as total`;
var query = `select
id
from
company
where
1=1
and chain_id=?`;
params.push(req.params.chain_id);
queryAndWait(query + '; ' + queryFoundRows, params).then(function(result) {
return Promise.map(result[0], function(row) {
var params = [];
var query = `select
*
from
location
where
1=1
and company_id=?
and site_id=?`;
params.push(row.id);
params.push(req.params.site_id);
return queryAndWait(query, params).then(function(result) {
return result[0];
});
}).then(function(payload) {
callback(null, payload);
}).catch(function(err) {
callback(err, null, null);
});
});
};
module.exports = Branding;
May not be exactly what you're after, but should provide a good start point. Good luck!
This topic is subjective however - it is important to take a standard and stick to it. The way I handled this was by creating a subfolder with a module (using module.exports) and an init function that constructs the express app.
For every route I have another module that has an init function which accepts the express application as a parameter and then adds the routes in there.
Main code file:
var Api = require('./API/index.js');
File /API/Index.js:
var express = require('express');
/* Instantiations */
var app = express();
module.exports = {
...
apply();
...
}
var route1 = require('./Routes/route1.js');
var route2 = require('./Routes/route2.js');
/* all additional routes */
var Routes = [route1,route2,...]
function apply(){
for(var i=0;i<Routes.length;i++){
Routes[i].init(app);
}
}
Then in API/Routes/route1.js and API/Routes/route2.js...
module.exports = {
init: function(app){
/* add your route logic here */
}
}
The benefits of this approach in my experience is that you can optionally choose to add or remove routes as needed and it provides a readable route-path via the file system which is handy in most modern text editors.

Node: letsencrypt-express module not working while using http and https node server

I am trying to use Letsencrypt without using a reverse proxy like Nginx, I found a module called letsencrypt-express (greenlock-express) on npm. But I cant get it working.
Working Example:
var express = require('express')
var letsencript = require('greenlock-express')
var leclg = require('le-challenge-fs')
var lestore = require('le-store-certbot')
var http = require('http');
var https = require('https');
var redHttps = require('redirect-https')
var app = express();
app.get('/', (req, res) => {
res.send('Ok Working');
})
var lex = letsencript.create({
server: 'staging',
// agreeTos: true,
approveDomains: (opts, certs, cb) => {
if (certs) {
// change domain list here
opts.domains = ['10hd.in']
} else {
// change default email to accept agreement
opts.email = 'test#gmail.com',
opts.agreeTos = true;
}
cb(null, { options: opts, certs: certs });
},
// app: app,
// challenges: { 'http-01': leclg.create({ webrootPath: '/tmp/acme-challenges' }) },
// store: lestore.create({ webrootPath: '/tmp/acme-challenges' })
}).listen(80, 443);
The Upper Example is working as expected. Redirects http to https and issues a certificate from the Letsencript stagging server. and stores them in ~/letsencript folder.
And Here is what I Want but not working.
var express = require('express')
var letsencript = require('greenlock-express')
var leclg = require('le-challenge-fs')
var lestore = require('le-store-certbot')
var http = require('http');
var https = require('https');
var redHttps = require('redirect-https')
var app = express();
app.get('/', (req, res) => {
res.send('Ok Working');
})
var lex = letsencript.create({
server: 'staging',
// agreeTos: true,
approveDomains: (opts, certs, cb) => {
if (certs) {
// change domain list here
opts.domains = ['10hd.in']
} else {
// change default email to accept agreement
opts.email = 'test#gmail.com',
opts.agreeTos = true;
}
cb(null, { options: opts, certs: certs });
},
// app: app,
// challenges: { 'http-01': leclg.create({ webrootPath: '/tmp/acme-challenges' }) },
// store: lestore.create({ webrootPath: '/tmp/acme-challenges' })
})
// .listen(80, 443);
const middlewareWrapper = lex.middleware;
// redHttps()
http.createServer(lex.middleware(redHttps())).listen(80, ()=> {
console.log("Listening for ACME http-01 challenges");
});
//
https.createServer(
lex.httpsOptions,
lex.middleware(app)
).listen(433, () => {
console.log("Listening for ACME tls-sni-01 challenges and serve app");
});
I Want to serve the server through https node module. and wanna do something in the callback provided in .listen() function.
But It does not even create let's encrypt the folder in home dir.
Console Output:
bubundas17#instance-2:~/test$ sudo node app.js
le.challenges[tls-sni-01].loopback should be defined as function (opts, domain, token, cb) { ... } and should prove (by external means) that the ACME server challenge 'tls-sni-01' will succeed
Listening for ACME http-01 challenges
Listening for ACME tls-sni-01 challenges and serve app
I solved the problem myself. the "greenlock-express" is just an interceptor of "greenlock" module.
Here is a working Code.
const http = require('http');
const https = require('https');
const redirectHttps = require('redirect-https')
var app = require('express')();
app.get('/', (req, res) => {
res.send("Test Server")
})
var le = require('greenlock').create({
server: 'staging',
configDir: 'certs/etc',
approveDomains: (opts, certs, cb) => {
if (certs) {
opts.domains = ['10hd.in']
} else {
opts.email = 'test#gmail.com',
opts.agreeTos = true;
}
cb(null, {
options: opts,
certs: certs
});
},
});
http.createServer(le.middleware(redirectHttps())).listen(80, function() {
console.log("Server Running On http" + 80);
})
https.createServer(le.httpsOptions, le.middleware(app)).listen(443, function() {
console.log("Server Running On https" + 443);
})
I don't Know Why this code is working and why the previous code is not! But the code is working, that's enough!

Node: send response after all work is done

If I call "http://localhost:3000/?fqn=mfgthun.ch&port=80" then i get back the following string:
{"source":"U259636","destination":"mfgthun.ch","ips":[]}
The resoult should be the following:
{"source":"U259636","destination":"mfgthun.ch","ips":[{"ip":"87.237.169.85","reachable":false}]}
The part in the function Write is missing... Do i need to add another callback here? Or is there any other solution for that?
Why is it not waiting until the first app.get block has finished?
const express = require('express')
const app = express()
const isReachable = require('is-reachable');
var dns = require('dns');
var os = require('os');
var url = require('url');
var jsonResponse;
function Write (ipPort, ip) {
this.ipPort = ipPort;
this.ip = ip;
this.callback = function(reachable) {
var temp = {ip: ip, reachable: reachable };
global.jsonResponse.ips.push(temp);
};
}
app.get("/", function(httpRequest, httpResponse, next){
try {
var url_parts = url.parse(httpRequest.url, true);
var query = url_parts.query;
global.jsonResponse = { source: os.hostname(), destination: query.fqn, ips: [] };
dns.resolve4(query.fqn, function (err, addresses) {
if (err) throw err;
for(var i = 0; i < addresses.length; i++) {
var ipPort = addresses[i] + ':' + query.port;
var write = new Write(ipPort, addresses[i]);
isReachable(ipPort).then(write.callback);
};
});
} catch(err) {
console.log(err);
};
next();
});
app.get("/", function(httpRequest, httpResponse){
httpResponse.write(JSON.stringify(global.jsonResponse));
httpResponse.end();
});
app.listen(3000)

Resources