enableCookie function

Handler<Response> enableCookie({
  1. String? secret,
  2. Hash algorithm = sha256,
  3. bool autoSecureSet = true,
  4. DateTime? expires,
  5. int? maxAge,
  6. String? domain,
  7. String? path,
  8. bool? secure,
  9. bool? httpOnly,
  10. SameSite? sameSite,
  11. bool? partitioned,
})

Enable cookie suppory.

The enableCookie create a Spry handler.

app.use(enableCookie());

Implementation

Handler<Response> enableCookie({
  String? secret,
  Hash algorithm = sha256,
  bool autoSecureSet = true,
  DateTime? expires,
  int? maxAge,
  String? domain,
  String? path,
  bool? secure,
  bool? httpOnly,
  SameSite? sameSite,
  bool? partitioned,
}) {
  final hmac = switch (secret) {
    String secret => Hmac(algorithm, utf8.encode(secret)),
    _ => null
  };

  return (event) async {
    final cookies = _createCookies(event, hmac);
    event.set(_kCookies, cookies);

    final response = await next(event);
    final hasSchema = useRequestURI(event).isScheme;
    final autoSecure = switch (autoSecureSet) {
      true => hasSchema('https') || hasSchema('wss'),
      _ => false,
    };

    for (final cookie in cookies) {
      cookie
        ..expires = cookie.expires ?? expires
        ..maxAge = cookie.maxAge ?? maxAge
        ..domain = cookie.domain ?? domain
        ..path = cookie.path ?? path
        ..secure = cookie.secure ?? secure ?? autoSecure
        ..httpOnly = cookie.httpOnly ?? httpOnly
        ..sameSite = cookie.sameSite ?? sameSite
        ..partitioned = cookie.partitioned ?? partitioned;

      response.headers.add('set-cookie', cookie.toString());
    }

    cookies.clear();

    return response;
  };
}