Security / Authentication

Built-in Auth

Building secure login and registration systems entirely from scratch can be a headache. Archery provides robust session-based authentication out of the box so you can focus on building your application.

The Auth Object

The Auth object acts as an interface to the active AuthSession. You can use the Auth helpers anywhere in your application (like Controllers) to interact with the currently authenticated user.

Logging a User In

Log a user in by invoking Auth.login() and passing their respective model instance (usually the complete User object).

final user = await Model.firstWhere<User>(
  field: 'email', 
  value: email
);

if (user != null && Hasher.check(key: password, hash: user.password)) {
  await Auth.login(request, user);
  return request.redirectTo('/dashboard');
}

return request.redirectBack();

When you call Auth.login, Archery destroys the user's temporary Guest Session, promotes their session to a persistent AuthSession, securely signs a new cookie, and records the session signature in your configured database.

Checking Auth Status

To quickly check if the visitor is logged in, you can use Auth.check():

if (Auth.check(request)) {
  // The user is logged in...
}

Logging Out

Logging a user out destroys their AuthSession record in the database, invalidates their active session cookie, and demotes them back to a fresh guest session:

await Auth.logout(request);
return request.redirectTo('/login');

Protecting Routes

To restrict access to a route, simply attach the Auth.middleware to the route registration. If an unauthenticated user attempts to visit the route, they will be automatically redirected to /login:

router.get('/dashboard',
  middleware: [Auth.middleware],
  handler: (request) async {
    return request.view('dashboard.html');
  }
);

You can also apply this middleware to an entire group of routes easily:

router.group(
  prefix: '/admin',
  middleware: [Auth.middleware],
  define: (admin) {
    admin.get('/settings', (req) async => ...);
  }
);