refactor(http)!: fix cascade dart good practices + docs

This commit is contained in:
2023-04-13 23:29:27 +02:00
parent 216a6c2aae
commit 07c2f4aeff
33 changed files with 303 additions and 974 deletions
@@ -1,294 +0,0 @@
// Copyright (C) 2022 WYATT GROUP
// Please see the AUTHORS file for details.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import 'dart:async';
import 'dart:io';
import 'package:wyatt_http_client/wyatt_http_client.dart';
String lastToken = '';
int token = 0;
void printAuth(HttpRequest req) {
print(
'Authorization => '
"${req.headers.value('Authorization') ?? 'no authorization header'}",
);
}
Future<void> handleBasic(HttpRequest req) async {
printAuth(req);
}
Future<void> handleBasicNegotiate(HttpRequest req) async {
if (req.headers.value('Authorization') == null) {
req.response.statusCode = HttpStatus.unauthorized.statusCode;
req.response.headers.set(HeaderKeys.wwwAuthenticate, 'Basic realm="Wyatt"');
print(req.response.headers.value('WWW-Authenticate'));
return req.response.close();
}
printAuth(req);
}
Future<void> handleBearer(HttpRequest req) async {
printAuth(req);
}
Future<void> handleDigest(HttpRequest req) async {
if (req.headers.value('Authorization') == null) {
req.response.statusCode = HttpStatus.unauthorized.statusCode;
req.response.headers.set(
'WWW-Authenticate',
'Digest realm="Wyatt", '
'qop="auth,auth-int", '
'nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", '
'opaque="5ccc069c403ebaf9f0171e9517f40e41"',
);
print(req.response.headers.value('WWW-Authenticate'));
return req.response.close();
}
printAuth(req);
}
Future<void> handleUnsafe(HttpRequest req) async {
print(
'Query parameters => '
'${req.uri.queryParameters}',
);
}
Future<void> handleOauth2RefreshToken(HttpRequest req) async {
final action = req.uri.queryParameters['action'];
if (action == null) {
printAuth(req);
}
switch (action) {
case 'login':
if (req.method == 'POST') {
token++;
req.response.write(
'{"accessToken": "access-token-awesome$token", '
'"refreshToken": "refresh-token-awesome$token"}',
);
}
break;
case 'refresh':
printAuth(req);
if (req.method == 'GET') {
token++;
req.response.write('{"accessToken": "access-token-refreshed$token"}');
}
break;
case 'access-denied':
final String receivedToken = req.headers.value('Authorization') ?? '';
if (receivedToken != '' &&
lastToken != '' &&
receivedToken != lastToken) {
lastToken = receivedToken;
printAuth(req);
return req.response.close();
} else {
lastToken = receivedToken;
req.response.statusCode = HttpStatus.unauthorized.statusCode;
return req.response.close();
}
default:
break;
}
}
Future<void> server() async {
final server = await HttpServer.bind(InternetAddress.anyIPv6, 8080);
var error = 0;
var token = 0;
await server.forEach((request) {
print('[${request.method}] ${request.uri}');
switch (request.uri.path) {
case '/test/basic-test':
handleBasic(request);
break;
case '/test/basic-test-with-negotiate':
handleBasicNegotiate(request);
break;
case '/test/digest-test':
handleDigest(request);
break;
case '/test/apikey-test':
handleBearer(request);
break;
case '/test/bearer-test':
handleBearer(request);
break;
case '/test/unsafe-test':
handleUnsafe(request);
break;
case '/test/oauth2-test':
handleOauth2RefreshToken(request);
break;
case '/test/bearer-login':
if (request.method == 'POST') {
request.response.write('{"token": "access-token-test"}');
}
break;
case '/test/oauth2-test-error':
error++;
print('Error $error');
if (error >= 3) {
print('Authorized');
error = 0;
} else {
request.response.statusCode = HttpStatus.unauthorized.statusCode;
}
break;
case '/test/oauth2-test-timeout':
error++;
print('Error $error');
request.response.statusCode = HttpStatus.unauthorized.statusCode;
break;
case '/test/oauth2-login':
if (request.method == 'POST') {
token++;
request.response.write(
'{"accessToken": "access-token-awesome$token", '
'"refreshToken": "refresh-token-awesome$token"}',
);
}
break;
case '/test/oauth2-refresh':
print(
'Authorization => '
"${request.headers.value('Authorization') ?? 'no refresh token'}",
);
if (request.method == 'GET') {
token++;
request.response
.write('{"accessToken": "access-token-refreshed$token"}');
}
break;
case '/test/oauth2-refresh-error':
request.response.statusCode = HttpStatus.unauthorized.statusCode;
break;
default:
print(' => Unknown path or method');
request.response.statusCode = HttpStatus.notFound.statusCode;
}
request.response.close();
print('====================');
});
}
Future<void> main() async {
unawaited(server());
const base = 'localhost:8080';
final uriPrefix = UriPrefixMiddleware(
protocol: Protocols.http,
authority: base,
);
final jsonEncoder = BodyToJsonMiddleware();
final logger = SimpleLoggerMiddleware();
// Basic
final basicAuth = BasicAuthMiddleware(
username: 'username',
password: 'password',
);
final basic = MiddlewareClient(
pipeline: Pipeline.fromIterable([
uriPrefix,
basicAuth,
logger,
]),
);
await basic.get(Uri.parse('/test/basic-test'));
// Digest
final digestAuth = DigestAuthMiddleware(
username: 'Mufasa',
password: 'Circle Of Life',
);
final digest = MiddlewareClient(
pipeline: Pipeline.fromIterable([
uriPrefix,
digestAuth,
logger,
]),
);
await digest.get(Uri.parse('/test/digest-test'));
// // Bearer
// final bearer = BearerAuthenticationClient(
// token: 'access-token-test',
// inner: restClient,
// );
// await bearer.get(Uri.parse('/test/bearer-test'));
// // API Key
// final apiKey = BearerAuthenticationClient(
// token: 'awesome-api-key',
// authenticationMethod: 'ApiKey',
// inner: restClient,
// );
// await apiKey.get(Uri.parse('/test/apikey-test'));
// Unsafe URL
final unsafeAuth = UnsafeAuthMiddleware(
username: 'Mufasa',
password: 'Circle Of Life',
);
final unsafe = MiddlewareClient(
pipeline: Pipeline.fromIterable([
uriPrefix,
unsafeAuth,
logger,
]),
);
await unsafe.get(Uri.parse('/test/unsafe-test'));
// OAuth2
final refreshTokenAuth = RefreshTokenAuthMiddleware(
authorizationEndpoint: '/test/oauth2-test?action=login',
tokenEndpoint: '/test/oauth2-test?action=refresh',
accessTokenParser: (body) => body['accessToken']! as String,
refreshTokenParser: (body) => body['refreshToken']! as String,
);
final refreshToken = MiddlewareClient(
pipeline: Pipeline.fromIterable([
uriPrefix,
jsonEncoder,
refreshTokenAuth,
logger,
]),
);
await refreshToken.get(Uri.parse('/test/oauth2-test'));
// Login
await refreshToken.post(
Uri.parse('/test/oauth2-test'),
body: <String, String>{
'username': 'username',
'password': 'password',
},
);
await refreshToken.get(Uri.parse('/test/oauth2-test'));
// await refreshToken.refresh();
// await refreshToken.get(Uri.parse('/test/oauth2-test'));
// await refreshToken.get(Uri.parse('/test/oauth2-test?action=access-denied'));
exit(0);
}
@@ -1,371 +0,0 @@
// Copyright (C) 2022 WYATT GROUP
// Please see the AUTHORS file for details.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'dart:convert';
import 'package:wyatt_http_client/src/middleware_client.dart';
import 'package:wyatt_http_client/src/middlewares/body_to_json_middleware.dart';
import 'package:wyatt_http_client/src/middlewares/refresh_token_auth_middleware.dart';
import 'package:wyatt_http_client/src/middlewares/simple_logger_middleware.dart';
import 'package:wyatt_http_client/src/middlewares/uri_prefix_middleware.dart';
import 'package:wyatt_http_client/src/pipeline.dart';
import 'package:wyatt_http_client/src/utils/http_status.dart';
import 'package:wyatt_http_client/src/utils/protocols.dart';
enum EmailVerificationAction {
signUp,
resetPassword,
changeEmail;
String toSnakeCase() => name.splitMapJoin(
RegExp('[A-Z]'),
onMatch: (m) => '_${m[0]?.toLowerCase()}',
onNonMatch: (n) => n,
);
factory EmailVerificationAction.fromString(String str) =>
EmailVerificationAction.values.firstWhere(
(element) => element.toSnakeCase() == str,
);
}
class VerifyCode {
final String email;
final String verificationCode;
final EmailVerificationAction action;
VerifyCode({
required this.email,
required this.verificationCode,
required this.action,
});
VerifyCode copyWith({
String? email,
String? verificationCode,
EmailVerificationAction? action,
}) =>
VerifyCode(
email: email ?? this.email,
verificationCode: verificationCode ?? this.verificationCode,
action: action ?? this.action,
);
Map<String, dynamic> toMap() => <String, dynamic>{
'email': email,
'verification_code': verificationCode,
'action': action.toSnakeCase(),
};
factory VerifyCode.fromMap(Map<String, dynamic> map) => VerifyCode(
email: map['email'] as String,
verificationCode: map['verification_code'] as String,
action: EmailVerificationAction.fromString(map['action'] as String),
);
String toJson() => json.encode(toMap());
factory VerifyCode.fromJson(String source) =>
VerifyCode.fromMap(json.decode(source) as Map<String, dynamic>);
@override
String toString() => 'VerifyCode(email: $email, verificationCode: '
'$verificationCode, action: $action)';
}
class Account {
final String email;
final String? sessionId;
Account({
required this.email,
this.sessionId,
});
Account copyWith({
String? email,
String? sessionId,
}) =>
Account(
email: email ?? this.email,
sessionId: sessionId ?? this.sessionId,
);
Map<String, dynamic> toMap() => <String, dynamic>{
'email': email,
'session_id': sessionId,
};
factory Account.fromMap(Map<String, dynamic> map) => Account(
email: map['email'] as String,
sessionId:
map['session_id'] != null ? map['session_id'] as String : null,
);
String toJson() => json.encode(toMap());
factory Account.fromJson(String source) =>
Account.fromMap(json.decode(source) as Map<String, dynamic>);
@override
String toString() => 'Account(email: $email, sessionId: $sessionId)';
}
class SignUp {
final String sessionId;
final String password;
SignUp({
required this.sessionId,
required this.password,
});
SignUp copyWith({
String? sessionId,
String? password,
}) =>
SignUp(
sessionId: sessionId ?? this.sessionId,
password: password ?? this.password,
);
Map<String, dynamic> toMap() => <String, dynamic>{
'session_id': sessionId,
'password': password,
};
factory SignUp.fromMap(Map<String, dynamic> map) => SignUp(
sessionId: map['session_id'] as String,
password: map['password'] as String,
);
String toJson() => json.encode(toMap());
factory SignUp.fromJson(String source) =>
SignUp.fromMap(json.decode(source) as Map<String, dynamic>);
@override
String toString() => 'SignUp(sessionId: $sessionId, password: $password)';
}
class TokenSuccess {
final String accessToken;
final String refreshToken;
final Account account;
TokenSuccess({
required this.accessToken,
required this.refreshToken,
required this.account,
});
TokenSuccess copyWith({
String? accessToken,
String? refreshToken,
Account? account,
}) =>
TokenSuccess(
accessToken: accessToken ?? this.accessToken,
refreshToken: refreshToken ?? this.refreshToken,
account: account ?? this.account,
);
Map<String, dynamic> toMap() => <String, dynamic>{
'access_token': accessToken,
'refresh_token': refreshToken,
'account': account.toMap(),
};
factory TokenSuccess.fromMap(Map<String, dynamic> map) => TokenSuccess(
accessToken: map['access_token'] as String,
refreshToken: map['refresh_token'] as String,
account: Account.fromMap(map['account'] as Map<String, dynamic>),
);
String toJson() => json.encode(toMap());
factory TokenSuccess.fromJson(String source) =>
TokenSuccess.fromMap(json.decode(source) as Map<String, dynamic>);
@override
String toString() => 'TokenSuccess(accessToken: $accessToken, refreshToken: '
'$refreshToken, account: $account)';
}
class Login {
final String email;
final String password;
Login({
required this.email,
required this.password,
});
Login copyWith({
String? email,
String? password,
}) =>
Login(
email: email ?? this.email,
password: password ?? this.password,
);
Map<String, dynamic> toMap() => <String, dynamic>{
'email': email,
'password': password,
};
factory Login.fromMap(Map<String, dynamic> map) => Login(
email: map['email'] as String,
password: map['password'] as String,
);
String toJson() => json.encode(toMap());
factory Login.fromJson(String source) =>
Login.fromMap(json.decode(source) as Map<String, dynamic>);
@override
String toString() => 'Login(email: $email, password: $password)';
}
class FastAPI {
final String baseUrl;
final MiddlewareClient client;
final int apiVersion;
FastAPI({
this.baseUrl = 'localhost:80',
MiddlewareClient? client,
this.apiVersion = 1,
}) : client = client ?? MiddlewareClient();
String get apiPath => '/api/v$apiVersion';
Future<void> sendSignUpCode(String email) async {
final r = await client.post(
Uri.parse('$apiPath/auth/send-sign-up-code'),
body: <String, String>{
'email': email,
},
);
if (r.statusCode != 201) {
throw Exception('Invalid reponse: ${r.statusCode}');
}
}
Future<Account> verifyCode(VerifyCode verifyCode) async {
final r = await client.post(
Uri.parse('$apiPath/auth/verify-code'),
body: verifyCode.toMap(),
);
if (r.statusCode != 202) {
throw Exception('Invalid reponse: ${r.statusCode}');
} else {
return Account.fromMap(
(jsonDecode(r.body) as Map<String, dynamic>)['account']
as Map<String, dynamic>,
);
}
}
Future<Account> signUp(SignUp signUp) async {
final r = await client.post(
Uri.parse('$apiPath/auth/sign-up'),
body: signUp.toMap(),
);
if (r.statusCode != 201) {
throw Exception('Invalid reponse: ${r.statusCode}');
} else {
return Account.fromJson(r.body);
}
}
Future<TokenSuccess> signInWithPassword(Login login) async {
final r = await client.post(
Uri.parse('$apiPath/auth/sign-in-with-password'),
body: login.toMap(),
);
if (r.statusCode != 200) {
throw Exception('Invalid reponse: ${r.statusCode}');
} else {
return TokenSuccess.fromJson(r.body);
}
}
// Future<TokenSuccess> refresh() async {
// final r = await client.refresh();
// return TokenSuccess.fromJson(r?.body ?? '');
// }
Future<List<Account>> getAccountList() async {
final r = await client.get(
Uri.parse('$apiPath/account'),
);
if (r.statusCode != 200) {
throw Exception('Invalid reponse: ${r.statusCode}');
} else {
final list = (jsonDecode(r.body) as Map<String, dynamic>)['founds']
as List<Map<String, dynamic>>;
final result = <Account>[];
for (final element in list) {
result.add(Account.fromMap(element));
}
return result;
}
}
}
void main(List<String> args) async {
final Pipeline pipeline = Pipeline()
.addMiddleware(
UriPrefixMiddleware(
protocol: Protocols.http,
authority: 'localhost:80',
),
)
.addMiddleware(BodyToJsonMiddleware())
.addMiddleware(
RefreshTokenAuthMiddleware(
authorizationEndpoint: '/api/v1/auth/sign-in-with-password',
tokenEndpoint: '/api/v1/auth/refresh',
accessTokenParser: (body) => body['access_token']! as String,
refreshTokenParser: (body) => body['refresh_token']! as String,
unauthorized: HttpStatus.forbidden,
),
)
.addMiddleware(SimpleLoggerMiddleware());
print(pipeline);
final client = MiddlewareClient(pipeline: pipeline);
final api = FastAPI(
client: client,
);
await api.sendSignUpCode('git@pcl.ovh');
// final verifiedAccount = await api.verifyCode(
// VerifyCode(
// email: 'git@pcl.ovh',
// verificationCode: '000000000',
// action: EmailVerificationAction.signUp,
// ),
// );
// final registeredAccount = await api.signUp(
// SignUp(sessionId: verifiedAccount.sessionId ?? '', password: 'password'),
// );
// final signedInAccount = await api.signInWithPassword(
// Login(email: 'git@pcl.ovh', password: 'password'),
// );
final accountList = await api.getAccountList();
print(accountList);
}
@@ -1,164 +0,0 @@
// ignore_for_file: public_member_api_docs, sort_constructors_first
// Copyright (C) 2022 WYATT GROUP
// Please see the AUTHORS file for details.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import 'package:wyatt_http_client/src/middleware_client.dart';
import 'package:wyatt_http_client/src/middlewares/body_to_json_middleware.dart';
import 'package:wyatt_http_client/src/middlewares/simple_logger_middleware.dart';
import 'package:wyatt_http_client/src/middlewares/unsafe_auth_middleware.dart';
import 'package:wyatt_http_client/src/middlewares/uri_prefix_middleware.dart';
import 'package:wyatt_http_client/src/pipeline.dart';
import 'package:wyatt_http_client/src/utils/protocols.dart';
// class RequestMutatorMiddleware implements Middleware {
// @override
// Middleware? parent;
// @override
// Middleware? child;
// RequestMutatorMiddleware({
// this.parent,
// this.child,
// });
// @override
// BaseRequest onRequest(BaseRequest request) {
// print('RequestMutator::OnRequest: ${request.method} -> ${request.url}');
// return child?.onRequest(request) ?? request;
// }
// @override
// BaseResponse onResponse(BaseResponse response) {
// final res = child?.onResponse(response) ?? response;
// print(
// 'RequestMutator::OnResponse: ${res.statusCode} -> ${res.contentLength}
// bytes',
// );
// return res;
// }
// }
// typedef Middleware = Handler Function(Handler innerHandler);
// Middleware createMiddleware({
// FutureOr<Response?> Function(Request)? requestHandler,
// FutureOr<Response> Function(Response)? responseHandler,
// FutureOr<Response> Function(Object error, StackTrace)? errorHandler,
// }) {
// requestHandler ??= (request) => null;
// responseHandler ??= (response) => response;
// FutureOr<Response> Function(Object, StackTrace)? onError;
// if (errorHandler != null) {
// onError = (error, stackTrace) {
// if (error is Exception) throw error;
// return errorHandler(error, stackTrace);
// };
// }
// return (Handler innerHandler) {
// return (request) {
// return Future.sync(() => requestHandler!(request)).then((response) {
// if (response != null) return response;
// return Future.sync(() => innerHandler(request))
// .then((response) => responseHandler!(response), onError:
// onError);
// });
// };
// };
// }
// extension MiddlewareX on Middleware {
// Middleware addMiddleware(Middleware other) =>
// (Handler handler) => this(other(handler));
// Handler addHandler(Handler handler) => this(handler);
// }
// typedef Handler = FutureOr<Response> Function(Request request);
// final headerMutator = createMiddleware(
// responseHandler: (response) {
// print(response.headers);
// return response;
// },);
// class Pipeline {
// const Pipeline();
// Pipeline addMiddleware(Middleware middleware) =>
// _Pipeline(middleware, addHandler);
// Handler addHandler(Handler handler) => handler;
// Middleware get middleware => addHandler;
// }
// class _Pipeline extends Pipeline {
// final Middleware _middleware;
// final Middleware _parent;
// _Pipeline(this._middleware, this._parent);
// @override
// Handler addHandler(Handler handler) => _parent(_middleware(handler));
// }
Future<void> main(List<String> args) async {
final UnsafeAuthMiddleware auth = UnsafeAuthMiddleware();
final Pipeline pipeline = Pipeline()
.addMiddleware(
UriPrefixMiddleware(
protocol: Protocols.http,
authority: 'localhost:80',
),
)
.addMiddleware(BodyToJsonMiddleware())
.addMiddleware(
UnsafeAuthMiddleware(
username: 'wyatt',
password: 'motdepasse',
),
)
.addMiddleware(SimpleLoggerMiddleware());
// .addMiddleware(
// RefreshTokenMiddleware(
// authorizationEndpoint: '/api/v1/account/test?action=authorize',
// tokenEndpoint: '/api/v1/account/test?action=refresh',
// accessTokenParser: (body) => body['access_token']! as String,
// refreshTokenParser: (body) => body['refresh_token']! as String,
// ),
// );
print(pipeline);
final client = MiddlewareClient(pipeline: pipeline);
await client.post(
Uri.parse('/api/v1/account/test'),
body: <String, String>{
'email': 'test@test.fr',
},
);
auth
..username = 'username'
..password = 'password';
await client.post(
Uri.parse('/api/v1/account/test'),
body: <String, String>{
'email': 'test@test.fr',
},
);
}