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;
});
Related
I'm building web app using Node.js Express.js for the server-side and Angular 6 SPA for the client.
Using the simple Express.js code, below, I've successfully authenticated a user via SAML2.js ADFS and now I want to access the user on the client side Angular SPA. How do I do that?
I found a similar setup here, but there is not an answer there and its a bit dated.
var saml2 = require('saml2-js');
var fs = require('fs');
var express = require('express');
var https = require('https');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: true
}));
// Create service provider
var sp_options = {
entity_id: "https://localhost:44301/",
private_key: fs.readFileSync("key.pem").toString(),
certificate: fs.readFileSync("certificate.crt").toString(),
assert_endpoint: "https://localhost:44301/assert",
force_authn: true,
auth_context: { comparison: "minimum", class_refs: ["urn:oasis:names:tc:SAML:2.0:ac:classes:password"] },
nameid_format: "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified",
sign_get_request: false,
allow_unencrypted_assertion: true
};
var sp = new saml2.ServiceProvider(sp_options);
// Create identity provider
var idp_options = {
sso_login_url: "https://mmusmaadfs.company.com/adfs/ls/",
sso_logout_url: "https://mmusmaadfs.company.com/adfs/ls/",
certificates: [fs.readFileSync("./2018ADFSSigningBase64Cert.cer").toString()],
force_authn: true,
sign_get_request: false,
allow_unencrypted_assertion: true
};
var idp = new saml2.IdentityProvider(idp_options);
// ------ Define express endpoints ------
// Endpoint to retrieve metadata
app.get("/metadata.xml", function(req, res) {
res.type('application/xml');
res.send(sp.create_metadata());
});
// Starting point for login
app.get("/login", function(req, res) {
sp.create_login_request_url(idp, {}, function(err, login_url, request_id) {
if (err != null)
return res.send(500);
res.redirect(login_url);
});
});
// Assert endpoint for when login completes
app.post("/assert", function(req, res) {
var options = {request_body: req.body};
sp.post_assert(idp, options, function(err, saml_response) {
if (err != null){
console.log("got here");
console.log(err);
return res.send(err);
}
// Save name_id and session_index for logout
// Note: In practice these should be saved in the user session, not globally.
name_id = saml_response.user.name_id;
session_index = saml_response.user.session_index;
res.send("Hello " +name_id +".");
//res.send("Hello #{saml_response.user.name_id}!");
});
});
// Starting point for logout
app.get("/logout", function(req, res) {
var options = {
name_id: name_id,
session_index: session_index
};
sp.create_logout_request_url(idp, options, function(err, logout_url) {
if (err != null)
return res.send(500);
res.redirect(logout_url);
});
});
var httpsOptions = {
key: fs.readFileSync('./key.pem')
, cert: fs.readFileSync('./certificate.crt')
}
var httpsServer = https.createServer(httpsOptions, app);
// app.listen(44301,console.log("App on 44301"));
httpsServer.listen(44301,console.log("App on 44301"));
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));
});
});
};
....
I have a node server running on port 3000 to serve api request.
this works fine...
http://www.skoolaide.com:3000/api/accounts
this does not.
https://www.skoolaide.com:3000/api/accounts
Can someone tell me why? If you go to https://www.skoolaide.com, the ssl cert is configured correctly, but do I need to do something on the node side?
this is my server js file. Please note: is only runs the middleware(api) on port 3000. For some reason I cannot access the middleware via https...
'use strict';
var express = require('express');
var router = express.Router();
var app = express();
var http = require('http');
var open = require('open');
var cors = require('cors');
var path = require('path');
var morgan = require('morgan');
var errorhandler = require('errorhandler');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var config = require('./config/config');
var jwt = require('jsonwebtoken');
var compression = require('compression');
var runMiddleware = require('run-middleware')(app);
var fs = require('fs');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
var multer = require('multer');
var node_xj = require("xls-to-json");
var moment = require('moment');
var async = require('async');
var btoa = require('btoa');
var sharp = require('sharp');
var students = require("./middleware/students.api");
var accounts = require("./middleware/accounts.api");
var messages = require("./middleware/messages.api");
var advocates = require("./middleware/advocates.api");
var authenticate = require("./middleware/authenticate.api");
var email = require("./middleware/email.api");
var text = require("./middleware/text.api");
var colleges = require("./middleware/colleges.api");
var amazon = require("./middleware/amazon.api");
var rewards = require("./middleware/rewards.api");
var files = require("./middleware/files.api");
var validations = require("./middleware/validations.api");
var points = require("./middleware/points.api");
var notifications = require("./middleware/notifications.api");
var notificationsMap = require("./middleware/notificationsMap.api");
var trivia = require("./middleware/trivia.api");
var tasks = require("./middleware/rewardgoals.api");
var classes = require("./middleware/classes.api");
var connections = require("./middleware/connections.api");
var badges = require("./middleware/badges.api");
var fixpasswords = require("./middleware/fixpasswords.api");
var Files = require('./models/files');
mongoose.connect(config.database);
process.on('SIGINT', function() {
mongoose.connection.close(function () {
console.log('Mongoose disconnected on app termination');
process.exit(0);
});
});
// use body parser so we can get info from POST and/or URL parameters
app.use(bodyParser.json({
limit: '50mb'
}));
app.use(bodyParser.urlencoded({
limit: '50mb',
extended: true
}));
app.set('uploads', path.join(__dirname, 'uploads'));
app.get("/uploads/*", function (req, res, next) {
res.sendFile(__dirname + req.url);
});
var whitelist = ['https://www.skoolaide.com', 'https://skoolaide.com'];
var corsOptionsDelegate = function (req, callback) {
var corsOptions;
if (whitelist.indexOf(req.headers['origin']) !== -1) {
corsOptions = { origin: true, credentials: true } // reflect (enable) the requested origin in the CORS response
} else {
corsOptions = { origin: false, credentials: false } // disable CORS for this request
}
callback(null, corsOptions) // callback expects two parameters: error and options
}
app.use(cors(corsOptionsDelegate));
//this is used because the body parser removes undefined values from the database.
app.set('json replacer', function (key, value) {
// undefined values are set to `null`
if (typeof value === "undefined") {
return null;
}
return value;
});
app.use(multer({
dest: './uploads/',
rename: function (fieldname, filename) {
return filename.replace(/\W+/g, '-').toLowerCase() + Date.now()
},
onFileUploadStart: function (file) {
//console.log(file.fieldname + ' is starting ...')
},
onFileUploadData: function (file, data) {
//console.log(data.length + ' of ' + file.fieldname + ' arrived')
},
onFileUploadComplete: function (file) {
//console.log(file.fieldname + ' uploaded to ' + file.path)
}
}).any());
// "files" should be the same name as what's coming from the field name on the client side.
app.post("/api/upload", function (req, res) {
//console.log(req.files[0].mimetype)
fs.readFile(req.files[0].path, function (err, data) {
var newPath = __dirname + "/uploads/" + req.headers["account_id"] + '_' + moment().format('MM_DD_YYYY_HH-mm-ss') + '_' + req.files[0].originalname.replace(/[^a-zA-Z0-9.]/g, '_');
var readPath = "/uploads/" + req.headers["account_id"] + '_' + moment().format('MM_DD_YYYY_HH-mm-ss') + '_' + req.files[0].originalname.replace(/[^a-zA-Z0-9.]/g, '_');
if(req.files[0].mimetype.indexOf('image') > -1){
sharp(data)
.rotate()
.resize(800, 800)
.max()
.toFile(newPath, function(err, info){
var file = new Files();
file.owner = req.headers.account_id || null;
file.classId = req.body.classId || null;
file.rewardGoalId = req.body.rewardGoalId || null;
file.avatarId = req.body.avatarId || null;
file.mimeType = req.files[0].mimetype || null;
file.originalName = req.files[0].originalname || null;
file.path = readPath;
file.save(function (err, newFile) {
if (err) {
res.send(err);
} else {
res.send({ success: true, data: newFile }).end();
}
});
});
} else{
//not an image file...
var newPath = __dirname + "/uploads/" + req.headers["account_id"] + '_' + moment().format('MM_DD_YYYY_HH-mm-ss') + '_' + req.files[0].originalname.replace(/[^a-zA-Z0-9.]/g, '_');
//console.log('Writing file: ', newPath);
fs.writeFile(newPath, data, function (err) {
var readPath = "/uploads/" + req.headers["account_id"] + '_' + moment().format('MM_DD_YYYY_HH-mm-ss') + '_' + req.files[0].originalname.replace(/[^a-zA-Z0-9.]/g, '_');
//console.log(readPath)
var file = new Files();
file.owner = req.headers.account_id || null;
file.classId = req.body.classId || null;
file.rewardGoalId = req.body.rewardGoalId || null;
file.profileId = req.body.profileId || null;
file.mimeType = req.files[0].mimetype || null;
file.originalName = req.files[0].originalname || null;
file.path = readPath;
file.save(function (err, newFile) {
if (err) {
res.send(err);
} else {
res.send({ success: true, data: newFile }).end();
}
});
});
}
});
});
app.use(express.static('www'))
var a = ['/'];
//all get requests resolve to index.
app.get(a, function (req, res) {
console.log('This is a test', req.originalUrl, req.url);
res.setHeader('Cache-Control', 'private, no-cache, no-store, must-revalidate');
res.setHeader('Expires', '-1');
res.setHeader('Pragma', 'no-cache');
res.setHeader('X-UA-Compatible', 'IE=Edge,chrome=1');
res.setHeader('Judson', 'Rocks!');
if (req.originalUrl == '/') {
res.sendFile('www/index.html', {root: __dirname});
}
});
app.set("superSecret", config.secret)
//var upload = require("./middleware/upload.api");
app.use('/api', router);
app.use('/api/students', students);
app.use('/api/accounts', accounts);
app.use('/api/messages', messages);
app.use('/api/advocates', advocates);
app.use('/api/authenticate', authenticate);
app.use('/api/email', email);
app.use('/api/text', text);
app.use('/api/colleges', colleges);
app.use('/api/amazon', amazon);
app.use('/api/rewards', rewards);
app.use('/api/files', files);
app.use('/api/validate', validations);
app.use('/api/points', points);
app.use('/api/notifications', notifications);
app.use('/api/notificationsMap', notificationsMap);
app.use('/api/trivia', trivia);
app.use('/api/rewardgoals', tasks);
app.use('/api/classes', classes);
app.use('/api/badges', badges);
app.use('/api/connections', connections);
app.use('/api/fixpasswords', fixpasswords);
/**SERVER*************************************/
// all environments
app.set('port', process.env.PORT || 3000);
app.engine('html', require('ejs').renderFile);
// express/connect middleware
app.use(morgan('dev'));
app.use(compression()); //use compression
// development only
if ('development' === app.get('env')) {
app.use(errorhandler());
}
/**END SERVER*************************************/
var cluster = require('cluster');
if (cluster.isMaster) {
var numWorkers = require('os').cpus().length;
console.log('Master cluster setting up ' + numWorkers + ' workers...');
for (var i = 0; i < numWorkers; i++) {
cluster.fork();
}
cluster.on('online', function (worker) {
console.log('Worker ' + worker.process.pid + ' is online');
});
cluster.on('exit', function (worker, code, signal) {
console.log('Worker ' + worker.process.pid + ' died with code: ' + code + ', and signal: ' + signal);
console.log('Starting a new worker');
cluster.fork();
});
} else {
app.listen(app.get('port'),
function () {
console.log('myApp server listening on port ' + app.get('port'));
});
}
Your code only starts an HTTP server. This line:
app.listen(app.get('port'))
starts only an http server. If you want support for HTTPS, you have to also start an HTTPS server and you have to start it on a different port. The express doc for app.listen() shows you how to do that and it's basicaly like this:
var express = require('express');
var https = require('https');
var http = require('http');
var app = express();
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
where options contains your SSL certificates and where you fill in the desired port numbers for your http server and your https server.
If you were operating under the illusion that you don't need a port number in the browser in order to access both an http and https server, that's because the browser fills in a default port number for you. If you just type an http URL, it uses port 80. If you type an https URL with no port, it uses port 443. If you're not on those two specific ports, you have to specify the desired port in the browser URL. In either case, you need a separate server on separate ports for both http and https.
Use var https = require("https"); not
Var http = require ("http");
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;
I don't understand where is my problem.
When I put this:
io = require('socket.io').listen(server).of("/");
I my handshake looks like running fine, but all my socket.io's event (like connection) never works.
And when I when i put this
io = require('socket.io').listen(server);
I got this :
TypeError: Object # has no method 'authorization'
If I remove my handshake, all the socket.io's will works, but i need it :/
Here my app.js
const express = require('express')
, app = express()
, http = require('http')
, ejs = require('ejs')
, server = http.createServer(app)
, port = process.env.PORT || 1337
, io = require('socket.io').listen(server).of("/")
;
module.exports = { app: app, server: server };
// Grab "cookie" and "connect" from express
var connect = require('express/node_modules/connect')
var cookie = require('express/node_modules/cookie')
var connectes =[];
app.configure(function(){
this.use("/public", express.static(__dirname + '/public'));
this.use(express.cookieParser());
this.use(express.json());
this.use(express.urlencoded());
this.sessionStore = new express.session.MemoryStore({ reapInterval: 60000 * 10 });
this.use(express.session({
"secret": "some private string",
"store": this.sessionStore
}));
});
app.engine('html', ejs.renderFile);
app.set('views', __dirname + '/views');
app.get('/', [requireLogin], function(request, response) {
var pseudo = request.session.pseudo;
response.render('index.ejs.html',{connectes:connectes});
});
app.get('/login', function(request, response) {
response.render('login.ejs.html');
});
app.post("/login", function(req, res){
if (req.param("user") != "") {
req.session.pseudo = req.param("user");
//socket.set('pseudo',req.param("user"));
connectes.push(req.param("user"));
res.render('index.ejs.html',{connectes:connectes});
}else{
res.render('login.ejs.html');
}
});
const parseCookie = require('connect').utils.parseCookie;
io.authorization(function (handshakeData, callback) {
var cookies = cookie.parse(handshakeData.headers.cookie);
console.log(cookie);
});
io.on('connection', function(socket){
console.log("This never appear in log :/");
socket.on('login',function(user,callback){
var pseudoValide = true;
for (var i = 0; i < connectes.length; i++) {
if(connectes[i]==user.pseudo){
pseudoValide = false;
callback(true);
}
}
if (pseudoValide) {
socket.set('pseudo',user.pseudo);
pseudo = user.pseudo;
socket.broadcast.emit('newuser', pseudo);
socket.broadcast.emit('nvluseronline', pseudo);
connectes.push(pseudo);
callback(false,pseudo);
}
});
socket.on('message',function(message){
messageUser = message.message;
socket.get('pseudo',function(error, pseudo){
io.sockets.emit('nouveauMessage',{pseudo:pseudo,message:messageUser});
})
});
socket.on('disconnect',function(){
socket.get('pseudo',function(error, pseudo){
connectes = unset(connectes, pseudo);
io.sockets.emit('nvldisc', pseudo);
})
});
});
function unset(array, value){
var output=[];
var index = array.indexOf(value)
{
var j = 0;
for(var i in array)
{
if (i!=index)
{
output[j]=array[i];
j++;
}
}
return output;
}
}
/** Middleware */
function requireLogin (req, res, next) {
if (req.session.pseudo) {
console.log(req.session.pseudo);
next();
}else{
res.redirect("/login");
}
}
if (!module.parent) {
server.listen(port, function () {
console.log('Listening', this.address());
})
}
Like you can see i'm a beginner lost !
Thank you guys !
You should read the documentation on authorization carefully. authorization method only exists for namespaces. When doing global authorization, you have to do:
io.configure(function (){
io.set('authorization', function (handshakeData, callback) {
callback(null, true); // error first callback style
});
});
It'll work fine if you have .of("/") as server endpoint, but it is a namespace. Without namespaces you would have to use above method.