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

Implement authenticator #198

Merged
merged 2 commits into from
Feb 11, 2021
Merged
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
9 changes: 9 additions & 0 deletions chopper/lib/src/authenticator.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import 'dart:async';

import 'package:chopper/chopper.dart';

/// This method should return a [Request] that includes credentials to satisfy an authentication challenge received in
/// [response]. It should return `null` if the challenge cannot be satisfied.
abstract class Authenticator {
FutureOr<Request> authenticate(Request request, Response response);
}
14 changes: 14 additions & 0 deletions chopper/lib/src/base.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import 'dart:async';
import 'package:chopper/src/authenticator.dart';
import 'package:meta/meta.dart';
import 'package:http/http.dart' as http;
import 'constants.dart';
Expand Down Expand Up @@ -37,6 +38,10 @@ class ChopperClient {
/// the request and response interceptors are called respectively.
final Converter converter;

/// The [Authenticator] that can provide reactive authentication for a
/// request.
final Authenticator authenticator;

/// The [ErrorConverter] that handles response transformation before the
/// response interceptors are called, but only on error responses
/// (statusCode < 200 || statusCode >= 300\).
Expand Down Expand Up @@ -109,6 +114,7 @@ class ChopperClient {
this.baseUrl = '',
http.Client client,
Iterable interceptors = const [],
this.authenticator,
this.converter,
this.errorConverter,
Iterable<ChopperService> services = const [],
Expand Down Expand Up @@ -316,6 +322,14 @@ class ChopperClient {
final response = await http.Response.fromStream(streamRes);
dynamic res = Response(response, response.body);

if (authenticator != null) {
var updatedRequest = authenticator.authenticate(request, res);

if (updatedRequest != null) {
res = await send(updatedRequest);
}
}

if (_responseIsSuccessful(response.statusCode)) {
res = await _handleSuccessResponse<BodyType, InnerType>(
res,
Expand Down