Cookie 与 Session

Finch 为客户端 Cookie 和服务端 Session 提供独立的 API。

Cookie 存储在用户浏览器中。

var theme = rq.getCookie('theme', def: 'light');
// 明文 Cookie(safe: false)
rq.addCookie('theme', 'dark', safe: false);

// 加密 Cookie(safe: true)
rq.addCookie('user_id', user.id.toString(), safe: true);

safe 参数使用 FinchConfigs 中的 cookiePassword 对 Cookie 进行加密。

rq.removeCookie('theme');

完整示例

Future<String> setTheme() async {
  var theme = rq.get<String>('theme', def: 'light');
  rq.addCookie('theme', theme, safe: false);
  return rq.redirect(url: '/settings');
}

Session

Session 存储在服务端(Finch 使用加密 Cookie 保存 Session ID)。

读取 Session

var userId = rq.getSession('userId', def: '');

写入 Session

rq.addSession('userId', user.id);
rq.addSession('role', 'admin');

删除 Session 值

rq.removeSession('userId');

清除所有 Session

rq.clearSession();

示例:登录 / 退出

// 登录
Future<String> login() async {
  var email    = rq.get<String>('email', def: '');
  var password = rq.get<String>('password', def: '');
  var user     = await UserModel().findByCredentials(email, password);

  if (user == null) {
    return rq.renderView(path: 'auth/login', params: {'error': '凭据无效'});
  }

  rq.addSession('userId', user.id);
  return rq.redirect(url: '/dashboard');
}

// 退出
Future<String> logout() async {
  rq.clearSession();
  return rq.redirect(url: '/login');
}

使用 safe: true 时,Cookie 值使用 FinchConfigs 中定义的 cookiePassword 进行加密。在生产环境中始终使用强且唯一的密码:

FinchConfigs(
  cookiePassword: env['COOKIE_PASSWORD'] ?? 'change-me-in-production',
)