sessionMiddleware function

Middleware sessionMiddleware({
  1. required String secret,
  2. int duration = 1800,
  3. String cookieName = 'darto.session',
})

Middleware that reads and validates the signed session cookie on every request.

Register once globally; then use sessionContext in any handler.

import 'package:darto/session.dart';

app.use(sessionMiddleware(secret: 'at-least-32-chars-long-secret!!'));

app.get('/login', [], (c) async {
  final session = sessionContext(c);
  await session.update({'userId': '42', 'role': 'admin'});
  return c.ok({'message': 'logged in'});
});

app.get('/me', [], (c) async {
  final data = sessionContext(c).get();
  if (data == null) return c.unauthorized({'error': 'no session'});
  return c.ok(data);
});

app.get('/logout', [], (c) async {
  sessionContext(c).delete();
  return c.ok({'message': 'logged out'});
});

Implementation

Middleware sessionMiddleware({
  required String secret,
  int duration = 1800,
  String cookieName = 'darto.session',
}) {
  return (Context c, Next next) async {
    final raw = getCookie(c, cookieName);
    if (raw != null) {
      final dot = raw.lastIndexOf('.');
      if (dot > 0) {
        final payload = raw.substring(0, dot);
        final sig = raw.substring(dot + 1);
        if (sig == _sign(payload, secret)) {
          try {
            final json = utf8.decode(base64Url.decode(base64Url.normalize(payload)));
            final data = jsonDecode(json);
            if (data is Map<String, dynamic>) {
              c.set(_sessionDataKey, data);
            }
          } catch (_) {}
        }
      }
    }
    c.set(_sessionCtrlKey, SessionController(c, secret, duration, cookieName));
    await next();
  };
}