init static method
- HttpRequest request
Restores or creates a guest session, refreshing activity on each reuse.
Requests under /api/ do not receive a guest session. Expired records are
deleted and replaced with a new session and cookie.
Implementation
static Future<Session?> init(HttpRequest request) async {
// API routes bypass browser guest-session initialization.
if (request.uri.path.startsWith('/api/')) {
return null;
}
final cookie = request.cookies.firstWhereOrNull((cookie) => cookie.name == "archery_guest_session");
// A first-time visitor has no session token to restore.
if (cookie == null) {
return await _createNewSession(request);
}
// Prefer the shared in-memory instance when it is available.
final containerSession = _checkContainer(cookie.value);
if (containerSession != null) {
if (_validateSession(containerSession)) {
containerSession.lastActivity = DateTime.now();
await containerSession.save();
return containerSession;
}
await containerSession.delete();
_containerSessions?.remove(containerSession);
return await _createNewSession(request);
}
// Restore persisted sessions that are absent from the container cache.
final dbSession = await _checkDB(cookie.value);
if (dbSession != null) {
if (_validateSession(dbSession)) {
dbSession.lastActivity = DateTime.now();
_containerSessions?.add(dbSession);
await dbSession.save();
return dbSession;
}
await dbSession.delete();
return await _createNewSession(request);
}
// An unknown cookie token is replaced rather than reused.
return await _createNewSession(request);
}