Created
January 5, 2023 07:21
-
-
Save taghassan54/527476bd7ef92166a724327f178d7e73 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:dio/dio.dart'; | |
final Dio client = Dio(); | |
client.interceptors.add(kDebugMode | |
? LogInterceptor( | |
request: true, | |
responseBody: true, | |
requestHeader: true, | |
error: true, | |
requestBody: true, | |
responseHeader: true, | |
) | |
: LogInterceptor( | |
request: false, | |
responseBody: false, | |
requestHeader: false, | |
error: false, | |
requestBody: false, | |
responseHeader: false, | |
)); | |
client.interceptors.add(TokenInterceptor(userSession)); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:dio/dio.dart'; | |
import 'package:janstore/src/config/session.dart'; | |
class TokenInterceptor extends Interceptor { | |
final UserSession userSession; | |
TokenInterceptor(this.userSession); | |
@override | |
onRequest(RequestOptions options,RequestInterceptorHandler handler) async { | |
if (await userSession.hasToken()) { | |
var token = await userSession.token(); | |
if (token != null && token.isNotEmpty) { | |
options.headers['authorization'] = 'Bearer $token'; | |
print("token found. "); | |
} | |
} else { | |
print("token not found,ignored. probably a guest."); | |
} | |
return super.onRequest(options, handler); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const TOKEN_KEY = "token"; | |
class UserSession { | |
GetStorage box=GetStorage(); | |
/// this function check if user has access token */ | |
bool hasToken() { | |
return box.read(tokenKey) != null ? true : false; | |
} | |
/// this function retrieve user access token */ | |
String? token() { | |
return box.read(tokenKey); | |
} | |
logout() { | |
box.remove(tokenKey); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment