Skip to content

Commit

Permalink
Implement authenticator (#198)
Browse files Browse the repository at this point in the history
* Implement authenticator

* Changes for PR

Co-authored-by: Ivan Terekhin <[email protected]>
  • Loading branch information
grahamsmith and JEuler authored Feb 11, 2021
1 parent 2003663 commit bbddf16
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
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

0 comments on commit bbddf16

Please sign in to comment.