score:1

Accepted answer

right, what i should do is just use cookies for your session. that way any front end ajax calls (including websocket) will use the cookie in the request headers.

with the http only setting set on the cookie, no front end javascript can modify (or access) the session cookie, but it is still used by the browser on any outgoing request.

in my opinion this is the safest way for using the session id, without the front end needing to know about the existence of the cookie in the first place.

if the session in koa doesn't exist any more, you automatically know the user is logged out as well.

i've made a little example for this (there is a github link below):

first the index.js:

'use strict';

const session = require('koa-session');
const koa = require('koa');
const websockify = require('koa-websocket');
const route = require('koa-route');

const app = websockify(koa());

app.keys = ['some secret hurr'];
const sessionstore = session(app);

app.use(sessionstore);
app.ws.use(sessionstore);

app.use(route.all('/', function* (next) {
  // ignore favicon
  if (this.path === '/favicon.ico') return;

  let n = this.session.views || 0;
  this.session.views = ++n;
  yield next;
}));

app.ws.use(route.all('/', function* (next) {
  this.websocket.on('message', (message) => {
    let n = this.session.views || 0;
    this.session.views = ++n;

    if (message === 'ping') {
      // return the amount of sessions (n) when the client sends ping
      this.websocket.send('pong ' + n);
    }
  });

  yield next;
}));

app.use(require('koa-static')('./public'));

app.listen(3000);
console.log('listening on port 3000');

and then the index.html:

<html>
  <script>
    var ws = new websocket("ws://localhost:3000/");

    ws.onopen = function() {
      // sends a message
      ws.send("ping");  
    };

    ws.onmessage = function(e) {
      // receives a message.
      alert(e.data);
    };

    ws.onclose = function() {
      alert("closed");
    };
  </script>
</html>

i've put all of this in to a working example on github.


Related Query

More Query from same tag