TF-605 Use bearer token download attachment on Android

This commit is contained in:
dab246
2022-06-02 17:37:39 +07:00
committed by Dat H. Pham
parent 69b2dbf3cf
commit ba49d7699a
16 changed files with 243 additions and 14 deletions
+12 -1
View File
@@ -27,6 +27,7 @@ import 'package:path_provider/path_provider.dart';
import 'package:tmail_ui_user/features/composer/domain/model/email_request.dart'; import 'package:tmail_ui_user/features/composer/domain/model/email_request.dart';
import 'package:model/model.dart'; import 'package:model/model.dart';
import 'package:tmail_ui_user/features/email/domain/model/move_to_mailbox_request.dart'; import 'package:tmail_ui_user/features/email/domain/model/move_to_mailbox_request.dart';
import 'package:tmail_ui_user/features/login/domain/exceptions/authentication_exception.dart';
class EmailAPI { class EmailAPI {
@@ -160,6 +161,12 @@ class EmailAPI {
String baseDownloadUrl, String baseDownloadUrl,
AccountRequest accountRequest AccountRequest accountRequest
) async { ) async {
if (accountRequest.authenticationType == AuthenticationType.oidc &&
accountRequest.token?.isExpired == true &&
accountRequest.token?.refreshToken.isNotEmpty == true) {
throw DownloadAttachmentHasTokenExpiredException(accountRequest.token!.refreshToken);
}
String externalStorageDirPath; String externalStorageDirPath;
if (Platform.isAndroid) { if (Platform.isAndroid) {
externalStorageDirPath = await ExternalPath.getExternalStoragePublicDirectory(ExternalPath.DIRECTORY_DOWNLOADS); externalStorageDirPath = await ExternalPath.getExternalStoragePublicDirectory(ExternalPath.DIRECTORY_DOWNLOADS);
@@ -169,12 +176,16 @@ class EmailAPI {
throw DeviceNotSupportedException(); throw DeviceNotSupportedException();
} }
final authentication = accountRequest.authenticationType == AuthenticationType.oidc
? accountRequest.bearerToken
: accountRequest.basicAuth;
final taskIds = await Future.wait( final taskIds = await Future.wait(
attachments.map((attachment) async => await FlutterDownloader.enqueue( attachments.map((attachment) async => await FlutterDownloader.enqueue(
url: attachment.getDownloadUrl(baseDownloadUrl, accountId), url: attachment.getDownloadUrl(baseDownloadUrl, accountId),
savedDir: externalStorageDirPath, savedDir: externalStorageDirPath,
headers: { headers: {
HttpHeaders.authorizationHeader: accountRequest.basicAuth, HttpHeaders.authorizationHeader: authentication,
HttpHeaders.acceptHeader: DioClient.jmapHeader HttpHeaders.acceptHeader: DioClient.jmapHeader
}, },
fileName: attachment.name, fileName: attachment.name,
@@ -4,13 +4,26 @@ import 'package:dartz/dartz.dart';
import 'package:jmap_dart_client/jmap/account_id.dart'; import 'package:jmap_dart_client/jmap/account_id.dart';
import 'package:tmail_ui_user/features/email/domain/repository/email_repository.dart'; import 'package:tmail_ui_user/features/email/domain/repository/email_repository.dart';
import 'package:tmail_ui_user/features/email/domain/state/download_attachments_state.dart'; import 'package:tmail_ui_user/features/email/domain/state/download_attachments_state.dart';
import 'package:tmail_ui_user/features/login/data/network/config/authorization_interceptors.dart';
import 'package:tmail_ui_user/features/login/domain/exceptions/authentication_exception.dart';
import 'package:tmail_ui_user/features/login/domain/repository/account_repository.dart';
import 'package:tmail_ui_user/features/login/domain/repository/authentication_oidc_repository.dart';
import 'package:tmail_ui_user/features/login/domain/repository/credential_repository.dart'; import 'package:tmail_ui_user/features/login/domain/repository/credential_repository.dart';
class DownloadAttachmentsInteractor { class DownloadAttachmentsInteractor {
final EmailRepository emailRepository; final EmailRepository emailRepository;
final CredentialRepository credentialRepository; final CredentialRepository credentialRepository;
final AccountRepository _accountRepository;
final AuthenticationOIDCRepository _authenticationOIDCRepository;
final AuthorizationInterceptors _authorizationInterceptors;
DownloadAttachmentsInteractor(this.emailRepository, this.credentialRepository); DownloadAttachmentsInteractor(
this.emailRepository,
this.credentialRepository,
this._accountRepository,
this._authenticationOIDCRepository,
this._authorizationInterceptors,
);
Stream<Either<Failure, Success>> execute( Stream<Either<Failure, Success>> execute(
List<Attachment> attachments, List<Attachment> attachments,
@@ -18,14 +31,34 @@ class DownloadAttachmentsInteractor {
String baseDownloadUrl String baseDownloadUrl
) async* { ) async* {
try { try {
final taskIds = await Future.wait( final account = await _accountRepository.getCurrentAccount();
[credentialRepository.getUserName(), credentialRepository.getPassword()],
eagerError: true log('ExportAttachmentInteractor::execute(): account: $account');
final taskIds = await Future.wait([
if (account.authenticationType == AuthenticationType.oidc)
_authenticationOIDCRepository.getStoredTokenOIDC(account.id)
else
...[
credentialRepository.getUserName(),
credentialRepository.getPassword()
]
], eagerError: true
).then((List responses) async { ).then((List responses) async {
final accountRequest = AccountRequest( AccountRequest accountRequest;
userName: responses.first,
password: responses.last, if (account.authenticationType == AuthenticationType.oidc) {
authenticationType: AuthenticationType.basic); final tokenOidc = responses.first as TokenOIDC;
accountRequest = AccountRequest(
token: tokenOidc.toToken(),
authenticationType: AuthenticationType.oidc);
} else {
accountRequest = AccountRequest(
userName: responses.first as UserName,
password: responses.last as Password,
authenticationType: AuthenticationType.basic);
}
return await emailRepository.downloadAttachments( return await emailRepository.downloadAttachments(
attachments, attachments,
accountId, accountId,
@@ -33,8 +66,63 @@ class DownloadAttachmentsInteractor {
accountRequest); accountRequest);
}); });
yield Right<Failure, Success>(DownloadAttachmentsSuccess(taskIds));
} catch (exception) {
log('DownloadAttachmentsInteractor::execute(): $exception');
if (exception is DownloadAttachmentHasTokenExpiredException) {
yield* _retryDownloadAttachments(
accountId,
baseDownloadUrl,
attachments,
exception.refreshToken);
} else {
yield Left<Failure, Success>(DownloadAttachmentsFailure(exception));
}
}
}
Stream<Either<Failure, Success>> _retryDownloadAttachments(
AccountId accountId,
String baseDownloadUrl,
List<Attachment> attachments,
String refreshToken) async* {
log('DownloadAttachmentsInteractor::_retryDownloadAttachments(): $refreshToken');
try {
final accountCurrent = await _accountRepository.getCurrentAccount();
final oidcConfig = await _authenticationOIDCRepository.getStoredOidcConfiguration();
final newTokenOIDC = await _authenticationOIDCRepository.refreshingTokensOIDC(
oidcConfig.clientId,
oidcConfig.redirectUrl,
oidcConfig.discoveryUrl,
oidcConfig.scopes,
refreshToken);
await Future.wait([
_authenticationOIDCRepository.persistTokenOIDC(newTokenOIDC),
_accountRepository.deleteCurrentAccount(accountCurrent.id),
_accountRepository.setCurrentAccount(Account(
newTokenOIDC.tokenIdHash,
AuthenticationType.oidc,
isSelected: true))
]);
_authorizationInterceptors.setTokenAndAuthorityOidc(
newToken: newTokenOIDC.toToken(),
newConfig: oidcConfig);
final accountRequest = AccountRequest(
token: newTokenOIDC.toToken(),
authenticationType: AuthenticationType.oidc);
final taskIds = await emailRepository.downloadAttachments(
attachments,
accountId,
baseDownloadUrl,
accountRequest);
yield Right<Failure, Success>(DownloadAttachmentsSuccess(taskIds)); yield Right<Failure, Success>(DownloadAttachmentsSuccess(taskIds));
} catch (e) { } catch (e) {
logError('RefreshTokenOIDCInteractor::execute(): $e');
yield Left<Failure, Success>(DownloadAttachmentsFailure(e)); yield Left<Failure, Success>(DownloadAttachmentsFailure(e));
} }
} }
@@ -25,6 +25,7 @@ import 'package:tmail_ui_user/features/login/data/datasource_impl/hive_account_d
import 'package:tmail_ui_user/features/login/data/local/account_cache_manager.dart'; import 'package:tmail_ui_user/features/login/data/local/account_cache_manager.dart';
import 'package:tmail_ui_user/features/login/data/local/oidc_configuration_cache_manager.dart'; import 'package:tmail_ui_user/features/login/data/local/oidc_configuration_cache_manager.dart';
import 'package:tmail_ui_user/features/login/data/local/token_oidc_cache_manager.dart'; import 'package:tmail_ui_user/features/login/data/local/token_oidc_cache_manager.dart';
import 'package:tmail_ui_user/features/login/data/network/config/authorization_interceptors.dart';
import 'package:tmail_ui_user/features/login/data/network/oidc_http_client.dart'; import 'package:tmail_ui_user/features/login/data/network/oidc_http_client.dart';
import 'package:tmail_ui_user/features/login/data/repository/account_repository_impl.dart'; import 'package:tmail_ui_user/features/login/data/repository/account_repository_impl.dart';
import 'package:tmail_ui_user/features/login/data/repository/authentication_oidc_repository_impl.dart'; import 'package:tmail_ui_user/features/login/data/repository/authentication_oidc_repository_impl.dart';
@@ -32,6 +33,7 @@ import 'package:tmail_ui_user/features/login/data/repository/credential_reposito
import 'package:tmail_ui_user/features/login/domain/repository/account_repository.dart'; import 'package:tmail_ui_user/features/login/domain/repository/account_repository.dart';
import 'package:tmail_ui_user/features/login/domain/repository/authentication_oidc_repository.dart'; import 'package:tmail_ui_user/features/login/domain/repository/authentication_oidc_repository.dart';
import 'package:tmail_ui_user/features/login/domain/repository/credential_repository.dart'; import 'package:tmail_ui_user/features/login/domain/repository/credential_repository.dart';
import 'package:tmail_ui_user/features/login/domain/usecases/refresh_token_oidc_interactor.dart';
class EmailBindings extends BaseBindings { class EmailBindings extends BaseBindings {
@@ -79,6 +81,9 @@ class EmailBindings extends BaseBindings {
Get.lazyPut(() => DownloadAttachmentsInteractor( Get.lazyPut(() => DownloadAttachmentsInteractor(
Get.find<EmailRepository>(), Get.find<EmailRepository>(),
Get.find<CredentialRepository>(), Get.find<CredentialRepository>(),
Get.find<AccountRepository>(),
Get.find<AuthenticationOIDCRepository>(),
Get.find<AuthorizationInterceptors>(),
)); ));
Get.lazyPut(() => ExportAttachmentInteractor( Get.lazyPut(() => ExportAttachmentInteractor(
Get.find<EmailRepository>(), Get.find<EmailRepository>(),
@@ -92,6 +97,10 @@ class EmailBindings extends BaseBindings {
Get.find<EmailRepository>(), Get.find<EmailRepository>(),
Get.find<CredentialRepository>(), Get.find<CredentialRepository>(),
)); ));
Get.lazyPut(() => RefreshTokenOIDCInteractor(
Get.find<AuthenticationOIDCRepository>(),
Get.find<AccountRepository>(),
));
} }
@override @override
@@ -228,7 +228,7 @@ class EmailController extends BaseController {
final status = await Permission.storage.status; final status = await Permission.storage.status;
switch (status) { switch (status) {
case PermissionStatus.granted: case PermissionStatus.granted:
_downloadAttachmentsAction(context, attachments); _downloadAttachmentsAction(attachments);
break; break;
case PermissionStatus.permanentlyDenied: case PermissionStatus.permanentlyDenied:
_appToast.showToast(AppLocalizations.of(context).you_need_to_grant_files_permission_to_download_attachments); _appToast.showToast(AppLocalizations.of(context).you_need_to_grant_files_permission_to_download_attachments);
@@ -237,7 +237,7 @@ class EmailController extends BaseController {
final requested = await Permission.storage.request(); final requested = await Permission.storage.request();
switch (requested) { switch (requested) {
case PermissionStatus.granted: case PermissionStatus.granted:
_downloadAttachmentsAction(context, attachments); _downloadAttachmentsAction(attachments);
break; break;
default: default:
_appToast.showToast(AppLocalizations.of(context).you_need_to_grant_files_permission_to_download_attachments); _appToast.showToast(AppLocalizations.of(context).you_need_to_grant_files_permission_to_download_attachments);
@@ -246,11 +246,11 @@ class EmailController extends BaseController {
} }
} }
} else { } else {
_downloadAttachmentsAction(context, attachments); _downloadAttachmentsAction(attachments);
} }
} }
void _downloadAttachmentsAction(BuildContext context, List<Attachment> attachments) async { void _downloadAttachmentsAction(List<Attachment> attachments) async {
final accountId = mailboxDashBoardController.accountId.value; final accountId = mailboxDashBoardController.accountId.value;
if (accountId != null && mailboxDashBoardController.sessionCurrent != null) { if (accountId != null && mailboxDashBoardController.sessionCurrent != null) {
final baseDownloadUrl = mailboxDashBoardController.sessionCurrent!.getDownloadUrl(); final baseDownloadUrl = mailboxDashBoardController.sessionCurrent!.getDownloadUrl();
@@ -258,7 +258,7 @@ class EmailController extends BaseController {
} }
} }
void _downloadAttachmentsFailure(Failure failure) { void _downloadAttachmentsFailure(DownloadAttachmentsFailure failure) {
if (currentContext != null) { if (currentContext != null) {
_appToast.showErrorToast(AppLocalizations.of(currentContext!).attachment_download_failed); _appToast.showErrorToast(AppLocalizations.of(currentContext!).attachment_download_failed);
} }
@@ -4,4 +4,6 @@ abstract class AccountDatasource {
Future<Account> getCurrentAccount(); Future<Account> getCurrentAccount();
Future<void> setCurrentAccount(Account newCurrentAccount); Future<void> setCurrentAccount(Account newCurrentAccount);
Future<void> deleteCurrentAccount(String accountId);
} }
@@ -15,4 +15,11 @@ abstract class AuthenticationOIDCDataSource {
Future<void> persistAuthorityOidc(String authority); Future<void> persistAuthorityOidc(String authority);
Future<OIDCConfiguration> getStoredOidcConfiguration(); Future<OIDCConfiguration> getStoredOidcConfiguration();
Future<TokenOIDC> refreshingTokensOIDC(
String clientId,
String redirectUrl,
String discoveryUrl,
List<String> scopes,
String refreshToken);
} }
@@ -62,4 +62,11 @@ class AuthenticationOIDCDataSourceImpl extends AuthenticationOIDCDataSource {
Future<void> persistAuthorityOidc(String authority) { Future<void> persistAuthorityOidc(String authority) {
return _oidcConfigurationCacheManager.persistAuthorityOidc(authority); return _oidcConfigurationCacheManager.persistAuthorityOidc(authority);
} }
@override
Future<TokenOIDC> refreshingTokensOIDC(String clientId, String redirectUrl,
String discoveryUrl, List<String> scopes, String refreshToken) {
return _oidcHttpClient.refreshingTokensOIDC(
clientId, redirectUrl, discoveryUrl, scopes, refreshToken);
}
} }
@@ -19,4 +19,9 @@ class HiveAccountDatasourceImpl extends AccountDatasource {
log('HiveAccountDatasourceImpl::setCurrentAccount(): $_accountCacheManager'); log('HiveAccountDatasourceImpl::setCurrentAccount(): $_accountCacheManager');
return _accountCacheManager.setSelectedAccount(newCurrentAccount); return _accountCacheManager.setSelectedAccount(newCurrentAccount);
} }
@override
Future<void> deleteCurrentAccount(String accountId) {
return _accountCacheManager.deleteSelectedAccount(accountId);
}
} }
@@ -49,6 +49,8 @@ class AuthorizationInterceptors extends InterceptorsWrapper {
_token = newToken; _token = newToken;
} }
OIDCConfiguration? get oidcConfig => _configOIDC;
@override @override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) { void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
switch(_authenticationType) { switch(_authenticationType) {
@@ -19,4 +19,9 @@ class AccountRepositoryImpl extends AccountRepository {
log('AccountRepositoryImpl::setCurrentAccount(): $newCurrentAccount'); log('AccountRepositoryImpl::setCurrentAccount(): $newCurrentAccount');
return _accountDatasource.setCurrentAccount(newCurrentAccount); return _accountDatasource.setCurrentAccount(newCurrentAccount);
} }
@override
Future<void> deleteCurrentAccount(String accountId) {
return _accountDatasource.deleteCurrentAccount(accountId);
}
} }
@@ -44,4 +44,20 @@ class AuthenticationOIDCRepositoryImpl extends AuthenticationOIDCRepository {
Future<void> persistAuthorityOidc(String authority) { Future<void> persistAuthorityOidc(String authority) {
return _oidcDataSource.persistAuthorityOidc(authority); return _oidcDataSource.persistAuthorityOidc(authority);
} }
@override
Future<TokenOIDC> refreshingTokensOIDC(
String clientId,
String redirectUrl,
String discoveryUrl,
List<String> scopes,
String refreshToken
) {
return _oidcDataSource.refreshingTokensOIDC(
clientId,
redirectUrl,
discoveryUrl,
scopes,
refreshToken);
}
} }
@@ -36,3 +36,10 @@ class NotFoundAccessTokenException implements Exception {
class AccessTokenInvalidException implements Exception { class AccessTokenInvalidException implements Exception {
AccessTokenInvalidException(); AccessTokenInvalidException();
} }
class DownloadAttachmentHasTokenExpiredException implements Exception {
final String refreshToken;
DownloadAttachmentHasTokenExpiredException(this.refreshToken);
}
@@ -5,4 +5,6 @@ abstract class AccountRepository {
Future<Account> getCurrentAccount(); Future<Account> getCurrentAccount();
Future<void> setCurrentAccount(Account newCurrentAccount); Future<void> setCurrentAccount(Account newCurrentAccount);
Future<void> deleteCurrentAccount(String accountId);
} }
@@ -15,4 +15,11 @@ abstract class AuthenticationOIDCRepository {
Future<void> persistAuthorityOidc(String authority); Future<void> persistAuthorityOidc(String authority);
Future<OIDCConfiguration> getStoredOidcConfiguration(); Future<OIDCConfiguration> getStoredOidcConfiguration();
Future<TokenOIDC> refreshingTokensOIDC(
String clientId,
String redirectUrl,
String discoveryUrl,
List<String> scopes,
String refreshToken);
} }
@@ -0,0 +1,21 @@
import 'package:core/core.dart';
import 'package:model/model.dart';
class RefreshTokenOIDCSuccess extends UIState {
final TokenOIDC tokenOIDC;
RefreshTokenOIDCSuccess(this.tokenOIDC);
@override
List<Object> get props => [tokenOIDC];
}
class RefreshTokenOIDCFailure extends FeatureFailure {
final dynamic exception;
RefreshTokenOIDCFailure(this.exception);
@override
List<Object> get props => [exception];
}
@@ -0,0 +1,40 @@
import 'package:core/core.dart';
import 'package:dartz/dartz.dart';
import 'package:model/model.dart';
import 'package:tmail_ui_user/features/login/domain/repository/account_repository.dart';
import 'package:tmail_ui_user/features/login/domain/repository/authentication_oidc_repository.dart';
import 'package:tmail_ui_user/features/login/domain/state/refresh_token_oidc_state.dart';
class RefreshTokenOIDCInteractor {
final AuthenticationOIDCRepository authenticationOIDCRepository;
final AccountRepository _accountRepository;
RefreshTokenOIDCInteractor(this.authenticationOIDCRepository, this._accountRepository);
Future<Either<Failure, Success>> execute(
OIDCConfiguration config,
String refreshToken) async {
try {
final newTokenOIDC = await authenticationOIDCRepository.refreshingTokensOIDC(
config.clientId,
config.redirectUrl,
config.discoveryUrl,
config.scopes,
refreshToken);
await Future.wait([
_accountRepository.setCurrentAccount(Account(
newTokenOIDC.tokenId.hashCode.toString(),
AuthenticationType.oidc,
isSelected: true)),
authenticationOIDCRepository.persistTokenOIDC(newTokenOIDC),
]);
return Right<Failure, Success>(RefreshTokenOIDCSuccess(newTokenOIDC));
} catch (e) {
logError('RefreshTokenOIDCInteractor::execute(): $e');
return Left<Failure, Success>(RefreshTokenOIDCFailure(e));
}
}
}