forbidden method

Future<HttpResponse> forbidden()

Renders errors.403 or falls back to a plain 403 response.

A CSRF cookie is also attached to the response, reusing the current token when available or generating a new one otherwise.

Example:

if (!user.can('delete-post')) {
  return request.forbidden();
}

Implementation

Future<HttpResponse> forbidden() async {
  final engine = App().container.make<TemplateEngine>();

  try {
    final html = await engine.render("errors.403", {});
    response.headers.contentType = ContentType.html;
    final csrfCookie = cookies.firstWhereOrNull((c) => c.name == 'archery_csrf_token');
    final cookie = Cookie('archery_csrf_token', csrfCookie?.value ?? App.generateKey())
      ..httpOnly = true
      ..secure = true
      ..sameSite = SameSite.lax
      ..path = '/';

    return response
      ..statusCode = HttpStatus.forbidden
      ..cookies.add(cookie)
      ..write(html)
      ..close();
  } catch (e) {
    return response
      ..statusCode = HttpStatus.forbidden
      ..write("403 Forbidden")
      ..close();
  }
}