2023-03-15 23:29:07 +02:00
|
|
|
import 'dart:io';
|
|
|
|
|
2022-02-03 18:06:44 +02:00
|
|
|
import 'package:auto_route/auto_route.dart';
|
2022-07-13 14:23:48 +02:00
|
|
|
import 'package:immich_mobile/routing/router.dart';
|
2024-02-27 05:25:39 +02:00
|
|
|
import 'package:immich_mobile/shared/models/store.dart';
|
2022-07-13 14:23:48 +02:00
|
|
|
import 'package:immich_mobile/shared/services/api.service.dart';
|
2023-07-28 05:05:27 +02:00
|
|
|
import 'package:logging/logging.dart';
|
2023-03-15 23:29:07 +02:00
|
|
|
import 'package:openapi/api.dart';
|
2022-02-03 18:06:44 +02:00
|
|
|
|
|
|
|
class AuthGuard extends AutoRouteGuard {
|
2022-07-13 14:23:48 +02:00
|
|
|
final ApiService _apiService;
|
2023-07-28 05:05:27 +02:00
|
|
|
final _log = Logger("AuthGuard");
|
2022-07-13 14:23:48 +02:00
|
|
|
AuthGuard(this._apiService);
|
2022-02-03 18:06:44 +02:00
|
|
|
@override
|
|
|
|
void onNavigation(NavigationResolver resolver, StackRouter router) async {
|
2023-07-28 05:05:27 +02:00
|
|
|
resolver.next(true);
|
|
|
|
|
2022-02-03 18:06:44 +02:00
|
|
|
try {
|
2024-02-27 05:25:39 +02:00
|
|
|
// Look in the store for an access token
|
|
|
|
Store.get(StoreKey.accessToken);
|
|
|
|
|
|
|
|
// Validate the access token with the server
|
|
|
|
final res = await _apiService.authenticationApi.validateAccessToken();
|
2023-07-28 05:05:27 +02:00
|
|
|
if (res == null || res.authStatus != true) {
|
|
|
|
// If the access token is invalid, take user back to login
|
2024-02-27 05:25:39 +02:00
|
|
|
_log.fine('User token is invalid. Redirecting to login');
|
2022-07-13 14:23:48 +02:00
|
|
|
router.replaceAll([const LoginRoute()]);
|
2022-02-03 18:06:44 +02:00
|
|
|
}
|
2024-02-27 05:25:39 +02:00
|
|
|
} on StoreKeyNotFoundException catch (_) {
|
|
|
|
// If there is no access token, take us to the login page
|
|
|
|
_log.warning('No access token in the store.');
|
|
|
|
router.replaceAll([const LoginRoute()]);
|
|
|
|
return;
|
2023-03-15 23:29:07 +02:00
|
|
|
} on ApiException catch (e) {
|
2024-02-27 05:25:39 +02:00
|
|
|
// On an unauthorized request, take us to the login page
|
|
|
|
if (e.code == HttpStatus.unauthorized) {
|
|
|
|
_log.warning("Unauthorized access token.");
|
2023-03-15 23:29:07 +02:00
|
|
|
router.replaceAll([const LoginRoute()]);
|
2023-07-28 05:05:27 +02:00
|
|
|
return;
|
2023-03-15 23:29:07 +02:00
|
|
|
}
|
2023-07-28 05:05:27 +02:00
|
|
|
} catch (e) {
|
2024-02-27 05:25:39 +02:00
|
|
|
// Otherwise, this is not fatal, but we still log the warning
|
|
|
|
_log.warning('Error validating access token from server: $e');
|
2022-02-03 18:06:44 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|