搜尋套件、儲存庫與 APP 分類

套件詳情v0.1.2

shelf_session

`shelf_session` 是 `shelf` 的 `cookiesMiddleware` 和 `sessionMiddleware` 的實現。

AndroidiOSmacOSWindowsLinux
近 30 天下載
22
喜歡數
2
Pub 分數
160

安裝套件

flutter pub add shelf_session

套件介紹

根據套件公開資料產生的選型評估,僅供參考。

shelf_session 套件為 Dart 中的 Shelf HTTP 伺服器框架提供會話管理與 cookie 處理中間件。它透過使用 cookies 儲存與取得會話資料,實現狀態化互動,讓使用 Shelf 建構的 Web 應用程式更輕鬆地管理使用者會話。該套件與 Shelf 的中間件架構無縫整合,提供輕量級的解決方案,適用於驗證、使用者追蹤以及跨請求的持續狀態。它支援安全的 cookie 設定,適合簡單與複雜的伺服器端邏輯。

適用情境

  • 在基於 Shelf 的伺服器中管理使用者會話
  • 在HTTP請求之間儲存使用者特定資料
  • 實現驗證流程
  • 處理有狀態的Web互動
  • 使用會話支援建構 REST API

主要特色

  • Shelf 的會話中間件
  • 基於 Cookie 的會話儲存
  • 安全的 cookie 設定
  • 與 Shelf 中間件輕鬆整合
  • 支援會話資料的序列化

適合對象

  • 基於書架的Web伺服器
  • 有狀態的Web應用程式
  • 認證系統
  • 需要會話管理的後端服務
  • 使用 Shelf 框架的 Dart 開發人員

使用建議

  • 需要正確的 Cookie 安全設定
  • 儲存在伺服器端的會話資料可能需要持久化
  • 不適用於需要額外協調的高規模分散式系統
  • 僅限貨架生態系統
  • 會話過期和清理必須手動管理

原始 README

以下為關聯原始碼儲存庫的 README 原文快照,最新內容請造訪原始碼儲存庫。

shelf_session

The shelf_session is the implementation of cookiesMiddleware and sessionMiddleware for shelf.

Version: 0.1.0

About

Adds two middleware for shelf:

  • cookiesMiddleware
  • sessionMiddleware

The cookiesMiddleware can be used independently.
The sessionMiddleware depends on cookiesMiddleware and must be used after it.

final pipeline = const Pipeline()
    .addMiddleware(cookiesMiddleware())
    .addMiddleware(sessionMiddleware())
    .addHandler(handler);

A small workable example:

import 'dart:io' show Cookie;

import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;
import 'package:shelf_router/shelf_router.dart';
import 'package:shelf_session/cookies_middleware.dart';
import 'package:shelf_session/session_middleware.dart';
import 'package:shelf_static/shelf_static.dart';

void main(List<String> args) async {
  final router = Router();
  router.get('/', _handleHome);
  router.get('/login', _handleLogin);
  router.get('/login/', _handleLogin);
  router.post('/login', _handleLogin);
  router.post('/login/', _handleLogin);
  router.get('/logout', _handleLogout);
  router.get('/logout/', _handleLogout);
  final staticHandler =
      createStaticHandler('web', defaultDocument: 'index.html');
  final handler = Cascade().add(staticHandler).add(router).handler;
  final pipeline = const Pipeline()
      .addMiddleware(logRequests())
      .addMiddleware(cookiesMiddleware())
      .addMiddleware(sessionMiddleware())
      .addHandler(handler);
  const address = 'localhost';
  const port = 8080;
  final server = await io.serve(pipeline, address, port);
  print('Serving at http://${server.address.host}:${server.port}');
}

const _menu = '''
<a href="/">Home</a><br />
<a href="/login">Log in</a><br />
<a href="/logout">Log out</a><br />''';

Future<Response> _handleHome(Request request) async {
  final userManager = UserManager();
  final user = userManager.getUser(request);
  var body = '$_menu{{message}}<br />{{cookies}}';
  if (user == null) {
    body = body.replaceAll('{{message}}', 'You are not logged in');
  } else {
    body = body.replaceAll('{{message}}', 'You are logged in as ${user.name}');
  }

  final cookies = request.getCookies();
  body = body.replaceAll('{{cookies}}',
      cookies.entries.map((e) => '${e.key}: ${e.value}').join('<br />'));
  request.addCookie(Cookie('foo', 'Foo'));
  if (!cookies.containsKey('baz')) {
    request.addCookie(Cookie('baz', 'Baz'));
  } else {
    request.removeCookie(Cookie('baz', ''));
  }

  return _render(body);
}

Future<Response> _handleLogin(Request request) async {
  const html = '''
<form action="" method="post">
<label>Login</label><br />
<input name="login" type="text" /><br />
<label>Password</label><br />
<input name="password" type="password" /><br /><br />
<button>Log in</button>
</form>
''';

  if (request.method == 'GET') {
    return _render(_menu + html);
  }

  final body = await request.readAsString();
  final queryParameters = Uri(query: body).queryParameters;
  final login = queryParameters['login'] ?? ''
    ..trim();
  final password = queryParameters['password'] ?? ''
    ..trim();
  if (login.isEmpty || password.isEmpty) {
    return _render(_menu + html);
  }

  final user = User(login);
  final userManager = UserManager();
  userManager.setUser(request, user);
  return Response.found('/');
}

Future<Response> _handleLogout(Request request) async {
  Session.deleteSession(request);
  return Response.found('/');
}

Response _render(String body) {
  return Response.ok(body, headers: {
    'Content-type': 'text/html; charset=UTF-8',
  });
}

class User {
  final String name;

  User(this.name);
}

class UserManager {
  User? getUser(Request request) {
    final session = Session.getSession(request);
    if (session == null) {
      return null;
    }

    final user = session.data['user'];
    if (user is User) {
      return user;
    }

    return null;
  }

  User setUser(Request request, User user) {
    var session = Session.getSession(request);
    session ??= Session.createSession(request);
    session.data['user'] = user;
    return user;
  }
}

Session data is stored in a hash map at runtime.
This implementation implies that session data should only be created for authorized users.
This approach eliminates memory overflow in the case of various types of attacks.
After the expiration of the lifetime, the session data is deleted automatically (which causes the memory to be freed).
Timers are not used for these purposes. This happens during the creation of new sessions.

所屬分類

依賴

依賴清單 1 項

原始碼儲存庫

使用此套件的專案

暫無相關資料。