client manager complete, client and client channels next

This commit is contained in:
Josh Burman
2019-03-07 20:19:13 -05:00
parent 97ed2476f4
commit 8fa7f98493
131 changed files with 10059 additions and 63 deletions

5
src/channelManager.ts Normal file
View File

@ -0,0 +1,5 @@
class ChannelManager {
};
module.exports = ChannelManager;

22
src/clientManager.ts Normal file
View File

@ -0,0 +1,22 @@
class ClientManager {
ws: any;
constructor(data: object, ws: object) {
this.ws = ws;
this.client(data);
}
client(data: any) {
if (data.site) {
console.log('legit: ' + data.site)
} else {
console.log('no client type designated, socket disconnect.')
this.ws.close();
}
}
};
module.exports = ClientManager;
// user_type: 'user', user_id: 125, site: 'mhs' }

15
src/config/app.ts Normal file
View File

@ -0,0 +1,15 @@
module.exports = {
version : '0.5.1',
whitelist : (process.env.WHITELIST || "http://admin.localhost").split(','),
secret : (process.env.API_TOKENS || "test").split(','),
devToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoidGVzdCBkYXRhIiwiYXVkIjoiaW50ZXJuYWwiLCJpc3MiOiJZYXJkc3RpY2sgU29mdHdhcmUiLCJzdWIiOiJCcmFpZCBKV1QifQ.t6LFXWPEVz3aLXwtrucarggqTkGY_2NnZB8ZTMaJ2oI',
port: process.env.PORT || 8443,
hostname: process.env.HOSTNAME || 'ysbraid.localhost',
environment: process.env.ENVIRONMENT || 'development',
signOptions : {
issuer: 'Yardstick Software',
subject: 'Braid JWT',
audience: 'internal',
algorithm: ["HS256"]
}
}

View File

@ -0,0 +1,7 @@
var app = require('../config/app')
module.exports = {
home : (req: any, res: any) => {
res.send(`Welcome to Braid v${app.version}`)
}
}

View File

@ -0,0 +1,12 @@
import * as jwt from 'jsonwebtoken';
var app = require('../config/app')
module.exports = {
confirmToken : (req: any, res: any) => {
var token = req.body.token
res.json({
response: JSON.stringify(jwt.verify(token, app.secret, app.signOptions))
});
}
}

25
src/routes.ts Normal file
View File

@ -0,0 +1,25 @@
import * as cors from 'cors';
import * as express from 'express';
var app = require('./config/app')
var corsOptions = {
origin: (origin: string, callback: Function) => {
if (app.whitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error(`Not allowed by CORS. Origin: ${origin}`))
}
}
}
var router = express.Router();
//application
var appController = require('./controllers/appController');
router.route(['/', '/home']).get(appController.home)
//auth
var authController = require('./controllers/authController');
router.route('/auth/user').post(cors(corsOptions), authController.confirmToken);
module.exports = router;

View File

@ -1,49 +1,92 @@
//external imports
import * as express from 'express';
import * as https from 'https';
import * as WebSocket from 'ws';
import * as fs from 'fs';
import * as jwt from 'jsonwebtoken';
import * as url from 'url';
//internal imports
var routes = require('./routes');
var app = require('./config/app');
var privateKey = fs.readFileSync('certs/key.pem', 'utf8');
var certificate = fs.readFileSync('certs/cert.pem', 'utf8');
var credentials = {key: privateKey, cert: certificate};
var options = {key: privateKey, cert: certificate, hostname: app.hostname};
const app = express();
const server = https.createServer(credentials, app);
const wss = new WebSocket.Server({ server, maxPayload:250000 });
const application = express();
const server = https.createServer(options, application);
const wss = new WebSocket.Server({ noServer: true, maxPayload:250000, host: app.hostname });
wss.on('connection', (ws: WebSocket) => {
console.log('client connected')
application.use(express.json());
application.use('', routes);
ws.on('message', (message: string) => {
wss.on('connection', (ws: WebSocket, request: object, args: string) => {
console.log('client connected');
var data = JSON.parse(args).data
var ClientManager = require('./clientManager');
let clientManager = new ClientManager(data, ws);
console.log('received: %s', message);
// ws.on('message', (message: string) => {
const broadcastRegex = /^broadcast\:/;
// console.log('received: %s', message);
if (broadcastRegex.test(message)) {
message = message.replace(broadcastRegex, '');
// const broadcastRegex = /^broadcast\:/;
//send back the message to the other clients
wss.clients
.forEach(client => {
if (client != ws) {
client.send(`Hello, broadcast message -> ${message}`);
}
});
// if (broadcastRegex.test(message)) {
// message = message.replace(broadcastRegex, '');
} else {
ws.send(`Hello, you sent -> ${message}`);
// //send back the message to the other clients
// wss.clients
// .forEach(client => {
// if (client != ws) {
// client.send(`Hello, broadcast message -> ${message}`);
// }
// });
// } else {
// ws.send(`Hello, you sent -> ${message}`);
// }
// });
ws.send('Hi there, welcome to braid, Measures Web Socket server.\nConnecting all our services!');
});
server.on('upgrade', async function upgrade(request, socket, head) {
let args: {};
try {
args = await verifyConnection()
} catch (e) {
socket.destroy();
console.log('connection terminated.');
return;
}
function verifyConnection() {
return new Promise((resolve, reject) => {
var data = url.parse(request.url, true).query;
var token = data["token"] || (app.environment == 'development' ? app.devToken : '');
var accepted = true;
var result: string;
jwt.verify(token, app.secret, app.signOptions, function(err, decoded) {
if (err) {
console.log(err);
accepted = false;
}
result = JSON.stringify(decoded)
accepted ? resolve(result) : reject('rejected');
});
});
}
ws.send('Hi there, welcome to braid, Measures Web Socket server.\nConnecting all our services!');
wss.handleUpgrade(request, socket, head, function done(ws) {
wss.emit('connection', ws, request, args);
});
});
// start our server
server.listen(process.env.PORT || 8443, () => {
console.log(`Server started :)`);
});
app.get('/', (req, res) => {
res.send('Braid v0.1.2 is running!\n');
server.listen(app.port, () => {
console.log(`Braid v${app.version} is running!\n`);
});