basicAuth function

Middleware basicAuth({
  1. String? username,
  2. String? password,
  3. bool verifyUser(
    1. String username,
    2. String password,
    3. Context c
    )?,
  4. void onAuthSuccess(
    1. Context c,
    2. String username
    )?,
  5. String realm = 'Secure Area',
})

Implementation

Middleware basicAuth({
  String? username,
  String? password,
  bool Function(String username, String password, Context c)? verifyUser,
  void Function(Context c, String username)? onAuthSuccess,
  String realm = 'Secure Area',
}) {
  return (Context c, Next next) async {
    final header = c.req.header('authorization');

    if (header == null || !header.startsWith('Basic ')) {
      _unauthorized(c, realm);
      return;
    }

    final encoded = header.substring(6);
    final decoded = utf8.decode(base64.decode(encoded));
    final parts = decoded.split(':');

    if (parts.length != 2) {
      _unauthorized(c, realm);
      return;
    }

    final user = parts[0];
    final pass = parts[1];

    final valid = verifyUser != null
        ? verifyUser(user, pass, c)
        : (user == username && pass == password);

    if (!valid) {
      _unauthorized(c, realm);
      return;
    }

    onAuthSuccess?.call(c, user);

    await next();
  };
}