Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(dart_frog_auth): add custom unauthenticated responses to all aut… #1632

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions docs/docs/advanced/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,36 @@ Handler middleware(Handler handler) {

In the above example, only routes that are not `POST` will have authentication checked.

### Custom Authenticated Responses

In some applications, you'll wish to send a custom response when the request is unauthenticated.
For example, a website will probably send an HTML page explaining to the user they need to log in before accessing the site.

To accomplish this, simply pass a `Handler` to the `unauthenticatedResponse` parameter to your authentication middleware.

```dart
Handler middleware(Handler handler) {
final userRepository = UserRepository();

return handler
.use(requestLogger())
.use(provider<UserRepository>((_) => userRepository))
.use(
basicAuthentication<User>(
authenticator: (context, username, password) {
final userRepository = context.read<UserRepository>();
return userRepository.userFromCredentials(username, password);
},
unauthenticatedResponse : (RequestContext context) async =>
Response(
body: '<html><body>You are not logged in :(</body></html>',
statusCode: HttpStatus.unauthorized,
),
),
);
}
```

### Authentication vs. Authorization

Both Authentication and authorization are related, but are different concepts that are often confused.
Expand Down
12 changes: 9 additions & 3 deletions packages/dart_frog_auth/lib/src/dart_frog_auth.dart
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ Middleware basicAuthentication<T extends Object>({
String password,
)? authenticator,
Applies applies = _defaultApplies,
Handler? unauthenticatedResponse,
}) {
assert(
userFromCredentials != null || authenticator != null,
Expand Down Expand Up @@ -102,7 +103,8 @@ Middleware basicAuthentication<T extends Object>({
}
}

return Response(statusCode: HttpStatus.unauthorized);
return unauthenticatedResponse?.call(context) ??
Response(statusCode: HttpStatus.unauthorized);
};
}

Expand Down Expand Up @@ -134,6 +136,7 @@ Middleware bearerAuthentication<T extends Object>({
Future<T?> Function(String token)? userFromToken,
Future<T?> Function(RequestContext context, String token)? authenticator,
Applies applies = _defaultApplies,
Handler? unauthenticatedResponse,
}) {
assert(
userFromToken != null || authenticator != null,
Expand Down Expand Up @@ -162,7 +165,8 @@ Middleware bearerAuthentication<T extends Object>({
}
}

return Response(statusCode: HttpStatus.unauthorized);
return unauthenticatedResponse?.call(context) ??
Response(statusCode: HttpStatus.unauthorized);
};
}

Expand Down Expand Up @@ -195,6 +199,7 @@ Middleware cookieAuthentication<T extends Object>({
Map<String, String> cookies,
) authenticator,
Applies applies = _defaultApplies,
Handler? unauthenticatedResponse,
}) {
return (handler) => (context) async {
if (!await applies(context)) {
Expand All @@ -210,6 +215,7 @@ Middleware cookieAuthentication<T extends Object>({
}
}

return Response(statusCode: HttpStatus.unauthorized);
return unauthenticatedResponse?.call(context) ??
Response(statusCode: HttpStatus.unauthorized);
};
}
252 changes: 252 additions & 0 deletions packages/dart_frog_auth/test/src/dart_frog_auth_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ class _MockRequestContext extends Mock implements RequestContext {}

class _MockRequest extends Mock implements Request {}

class _MockResponse extends Mock implements Response {}

class _User {
const _User(this.id);
final String id;
Expand Down Expand Up @@ -87,6 +89,60 @@ void main() {
},
);

group('and custom unauthenticated response is provided', () {
test(
'returns custom response when Authorization header is not present',
() async {
final response = _MockResponse();
final middleware = basicAuthentication<_User>(
userFromCredentials: (_, __) async => user,
unauthenticatedResponse: (context) => response,
);
expect(
await middleware((_) async => Response())(context),
equals(response),
);
},
);

test(
'returns custom response when Authorization header is present but '
'invalid',
() async {
final response = _MockResponse();
when(() => request.headers)
.thenReturn({'Authorization': 'not valid'});
final middleware = basicAuthentication<_User>(
userFromCredentials: (_, __) async => user,
unauthenticatedResponse: (context) => response,
);
expect(
await middleware((_) async => Response())(context),
equals(response),
);
},
);

test(
'returns custom response when Authorization header is present and '
'valid but no user is returned',
() async {
final response = _MockResponse();
when(() => request.headers).thenReturn({
'Authorization': 'Bearer 1234',
});
final middleware = basicAuthentication<_User>(
userFromCredentials: (_, __) async => null,
unauthenticatedResponse: (context) => response,
);
expect(
await middleware((_) async => Response())(context),
equals(response),
);
},
);
});

test(
'sets the user when everything is valid',
() async {
Expand Down Expand Up @@ -190,6 +246,60 @@ void main() {
},
);

group('and custom unauthenticated response is provided', () {
test(
'returns custom response when Authorization header is not present',
() async {
final response = _MockResponse();
final middleware = basicAuthentication<_User>(
authenticator: (_, __, ___) async => user,
unauthenticatedResponse: (context) => response,
);
expect(
await middleware((_) async => Response())(context),
equals(response),
);
},
);

test(
'returns custom response when Authorization header is present but '
'invalid',
() async {
final response = _MockResponse();
when(() => request.headers)
.thenReturn({'Authorization': 'not valid'});
final middleware = basicAuthentication<_User>(
authenticator: (_, __, ___) async => user,
unauthenticatedResponse: (context) => response,
);
expect(
await middleware((_) async => Response())(context),
equals(response),
);
},
);

test(
'returns custom response when Authorization header is present and '
'valid but no user is returned',
() async {
final response = _MockResponse();
when(() => request.headers).thenReturn({
'Authorization': 'Basic dXNlcjpwYXNz',
});
final middleware = basicAuthentication<_User>(
authenticator: (_, __, ___) async => null,
unauthenticatedResponse: (context) => response,
);
expect(
await middleware((_) async => Response())(context),
equals(response),
);
},
);
});

test(
'sets the user when everything is valid',
() async {
Expand Down Expand Up @@ -307,6 +417,60 @@ void main() {
},
);

group('and custom unauthenticated response is provided', () {
test(
'returns custom response when Authorization header is not present',
() async {
final response = _MockResponse();
final middleware = bearerAuthentication<_User>(
userFromToken: (_) async => user,
unauthenticatedResponse: (context) => response,
);
expect(
await middleware((_) async => Response())(context),
equals(response),
);
},
);

test(
'returns custom response when Authorization header is present but '
'invalid',
() async {
final response = _MockResponse();
when(() => request.headers)
.thenReturn({'Authorization': 'not valid'});
final middleware = bearerAuthentication<_User>(
userFromToken: (_) async => user,
unauthenticatedResponse: (context) => response,
);
expect(
await middleware((_) async => Response())(context),
equals(response),
);
},
);

test(
'returns custom response when Authorization header is present and '
'valid but no user is returned',
() async {
final response = _MockResponse();
when(() => request.headers).thenReturn({
'Authorization': 'Bearer 1234',
});
final middleware = bearerAuthentication<_User>(
userFromToken: (_) async => null,
unauthenticatedResponse: (context) => response,
);
expect(
await middleware((_) async => Response())(context),
equals(response),
);
},
);
});

test(
'sets the user when everything is valid',
() async {
Expand Down Expand Up @@ -410,6 +574,60 @@ void main() {
},
);

group('and custom unauthenticated response is provided', () {
test(
'returns custom response when Authorization header is not present',
() async {
final response = _MockResponse();
final middleware = bearerAuthentication<_User>(
authenticator: (_, __) async => user,
unauthenticatedResponse: (context) => response,
);
expect(
await middleware((_) async => Response())(context),
equals(response),
);
},
);

test(
'returns custom response when Authorization header is present but '
'invalid',
() async {
final response = _MockResponse();
when(() => request.headers)
.thenReturn({'Authorization': 'not valid'});
final middleware = bearerAuthentication<_User>(
authenticator: (_, __) async => user,
unauthenticatedResponse: (context) => response,
);
expect(
await middleware((_) async => Response())(context),
equals(response),
);
},
);

test(
'returns custom response when Authorization header is present and '
'valid but no user is returned',
() async {
final response = _MockResponse();
when(() => request.headers).thenReturn({
'Authorization': 'Bearer 1234',
});
final middleware = bearerAuthentication<_User>(
authenticator: (_, __) async => null,
unauthenticatedResponse: (context) => response,
);
expect(
await middleware((_) async => Response())(context),
equals(response),
);
},
);
});

test(
'sets the user when everything is valid',
() async {
Expand Down Expand Up @@ -504,6 +722,40 @@ void main() {
},
);

group('and custom unauthenticated response is provided', () {
test(
'returns custom response when Cookie header is not present',
() async {
final response = _MockResponse();
final middleware = cookieAuthentication<_User>(
authenticator: (_, __) async => user,
unauthenticatedResponse: (context) => response,
);
expect(
await middleware((_) async => Response())(context),
equals(response),
);
},
);

test(
'returns custom response when Cookie header is present '
'but no user is returned',
() async {
final response = _MockResponse();
when(() => request.headers).thenReturn({'Cookie': 'session=abc123'});
final middleware = cookieAuthentication<_User>(
authenticator: (_, __) async => null,
unauthenticatedResponse: (context) => response,
);
expect(
await middleware((_) async => Response())(context),
equals(response),
);
},
);
});

test(
'sets the user when everything is valid',
() async {
Expand Down
Loading