paldepind / synceddb

Makes it easy to write offline-first applications with realtime syncing and server side persistence.
MIT License
411 stars 34 forks source link

Pass req to handlers #21

Closed piglovesyou closed 8 years ago

piglovesyou commented 8 years ago

For flexible authentication, we need follows:

This is a short example to use session in handlers with using npm Express. (I don't guarantee, I did't run)

const http = require('http');
const express = require('express');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const MemoryPersistence = require('synceddb-persistence-memory');
const SyncedDBBackend = require('synceddb-server');

const app = express();
const server = http.createServer(app);
const sessionParser = session({
  secret: 'baaa',
  resave: false,
  saveUninitialized: true
});

app.set('port', 3000);
app.use(cookieParser());

MemoryPersistence.create().then((p) => {
  const ws = new SyncedDBBackend({
    store: p,
    server: server,
    verifyClient: (info, done) => {
      const {req} = info;
      sessionParser(req, null, () => {
        console.log(req.session); // session available
        done(!!req.sesion.user); // If true, a user accepts a handshake.
      });
    }
  });
  ws.handlers.create = (clientData, store, msg, respond, broadcast, req) => {
    sessionParser(req, null, () => {
      console.log(req.session); // session available
      req.session.user.type; // We can change what we do in terms of a user state.
    });
  };
  server.listen(port);
});