unAuthenticated method
Renders errors.401 or falls back to a plain 401 response.
A CSRF cookie is also attached to the response, reusing the current token when available or generating a new one otherwise.
Example:
if (await request.user == null) {
return request.unAuthenticated();
}
Implementation
Future<HttpResponse> unAuthenticated() async {
final engine = App().container.make<TemplateEngine>();
try {
final html = await engine.render("errors.401", {});
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.unauthorized
..cookies.add(cookie)
..write(html)
..close();
} catch (e) {
return response
..statusCode = HttpStatus.unauthorized
..write("401 Unauthenticated")
..close();
}
}