Skip to content

Commit

Permalink
feat: logout on getting 401 Unauthorized response
Browse files Browse the repository at this point in the history
  • Loading branch information
NanoNish authored Oct 1, 2023
2 parents e900e43 + dddd059 commit 93568db
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
1 change: 0 additions & 1 deletion lib/presentation/app/bloc/app_bloc.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import 'dart:async';

import 'package:appetizer/data/constants/constants.dart';
import 'package:appetizer/data/services/local/local_storage_service.dart';
import 'package:appetizer/domain/models/user/user.dart';
Expand Down
30 changes: 27 additions & 3 deletions lib/utils/interceptors/auth_interceptor.dart
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
import 'dart:async';

import 'package:appetizer/data/constants/constants.dart';
import 'package:appetizer/data/services/local/local_storage_service.dart';
import 'package:appetizer/presentation/app/bloc/app_bloc.dart';
import 'package:appetizer/utils/app_extensions/app_extensions.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class AuthInterceptor extends Interceptor {
ValueGetter<FutureOr<String?>>? getToken;

AuthInterceptor({this.getToken});
AuthInterceptor({
this.getToken,
});

@override
void onRequest(
Expand All @@ -22,4 +28,22 @@ class AuthInterceptor extends Interceptor {

return super.onRequest(options, handler);
}

@override
void onError(DioException err, ErrorInterceptorHandler handler) {
if (err.response?.statusCode == 401) {
LocalStorageService.setValue(key: AppConstants.LOGGED_IN, value: false);
LocalStorageService.setValue(key: AppConstants.AUTH_TOKEN, value: null);
if (BaseApp.currentContext != null) {
const snackBar =
SnackBar(content: Text('User is inactive or unauthorized!'));
ScaffoldMessenger.of(BaseApp.currentContext!).showSnackBar(snackBar);
}
BaseApp.currentContext
?.read<AppBloc>()
.add(const NavigateToLoginScreen());
} else {
handler.next(err);
}
}
}

0 comments on commit 93568db

Please sign in to comment.