Permalink
Browse files

feat(socket): enable session parsing for socket connections

  • Loading branch information...
jkuri committed Sep 4, 2017
1 parent 8d5d9ad commit 31d6c1f0f41a187df7f50e1daf59a852b3f9347a
Showing with 90 additions and 14 deletions.
  1. +20 −1 src/api/server.ts
  2. +70 −13 src/api/socket.ts
@@ -4,6 +4,9 @@ import * as bodyParser from 'body-parser';
import { Observable } from 'rxjs';
import * as routes from './server-routes';
import { webhooks } from './webhooks';
import { yellow, cyan } from 'chalk';
import * as session from 'express-session';
import * as uuid from 'uuid';

export interface ServerConfig {
port: number;
@@ -14,6 +17,12 @@ export interface IExpressServer {
start(): Observable<string>;
}

export const sessionParser = session({
saveUninitialized: false,
secret: 'sessionSecret',
resave: false
});

export class ExpressServer implements IExpressServer {
config: ServerConfig;

@@ -26,6 +35,7 @@ export class ExpressServer implements IExpressServer {
const app: express.Application = express();
app.use(cors());
app.use(bodyParser.json());
app.use(sessionParser);
app.use('/webhooks', webhooks);
app.use('/api/setup', routes.setupRoutes());
app.use('/api/user', routes.userRoutes());
@@ -36,8 +46,17 @@ export class ExpressServer implements IExpressServer {
app.use('/api/permissions', routes.permissionRoutes());
app.use('/badge', routes.badgeRoutes());
app.use(routes.webRoutes());


app.listen(this.config.port, () => {
observer.next(`Server running on port ${this.config.port}`);
let msg = [
yellow('['),
cyan('http'),
yellow(']'),
' --- ',
`server running on port ${this.config.port}`
].join('');
observer.next(msg);
});
});
}
@@ -22,6 +22,8 @@ import * as https from 'https';
import * as http from 'http';
import { readFileSync } from 'fs';
import * as express from 'express';
import { yellow, red, blue, green } from 'chalk';
import { sessionParser } from './server';

export interface ISocketServerOptions {
port: number;
@@ -31,6 +33,7 @@ export class SocketServer {
options: ISocketServerOptions;
connections: Observable<any>;
clients: any[];
connectingClient: any;

constructor(options: ISocketServerOptions) {
this.options = options;
@@ -40,10 +43,12 @@ export class SocketServer {
start(): Observable<string> {
return new Observable(observer => {
this.createRxServer(this.options)
.map(this.createRxSocket)
.map(data => {
this.connectingClient = data.session;
return this.createRxSocket(data.conn);
})
.subscribe(conn => {
const client = { connection: conn, sub: null };
this.clients.push(client);
this.clients.push({ connection: conn, sub: null, session: this.connectingClient });

// send server time for sync
conn.next({ type: 'time', data: new Date().getTime() });
@@ -53,11 +58,27 @@ export class SocketServer {

conn.subscribe(event => {
if (event.type === 'disconnected') {
const connIndex = this.clients.findIndex(client => client.connection === conn);
if (connIndex !== -1) {
this.clients.splice(connIndex, 1);
logger.info(`client ${connIndex + 1} disconnected`);
}
const index = this.clients.findIndex(client => client.connection === conn);
const session = this.clients[index].session;
let msg = [
yellow('['),
green('socket'),
yellow(']'),
' --- ',
`user ${session.userId} disconnected. clearing session ...`
].join('');
logger.info(msg);

this.clients.splice(index, 1);

msg = [
yellow('['),
green('socket'),
yellow(']'),
' --- ',
`session cleared after user ${session.userId}`
].join('');
logger.info(msg);
}

switch (event.type) {
@@ -158,12 +179,48 @@ export class SocketServer {
}

server.listen(options.port);
logger.info(`Socket server running at port ${options.port}`);
let msg = [
yellow('['),
green('socket'),
yellow(']'),
' --- ',
`socket server running at port ${options.port}`
].join('');
logger.info(msg);

let wss: ws.Server = new ws.Server({
verifyClient: (info: any, done) => {
const id = uuid();
const ip = info.req.headers['x-forwarded-for'] || info.req.connection.remoteAddress;
let msg = [
yellow('['),
green('socket'),
yellow(']'),
' --- ',
`updating session for user ${id} (${ip})`
].join('');
logger.info(msg);

sessionParser(info.req, {} as any, () => {
info.req.session.userId = id;
info.req.session.ip = ip;
done(info.req.session.userId);
});
},
server
});

let wss: ws.Server = new ws.Server({ server: server });
wss.on('connection', (connection: ws) => {
observer.next(connection);
logger.info(`socket connection established.`);
wss.on('connection', (connection: any, req: any) => {
observer.next({ conn: connection, session: req.session });

let msg = [
yellow('['),
green('socket'),
yellow(']'),
' --- ',
`socket connection established ${req.session.userId}`
].join('');
logger.info(msg);
});

return () => {

0 comments on commit 31d6c1f

Please sign in to comment.