-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth_repository.dart
59 lines (45 loc) · 1.46 KB
/
auth_repository.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'auth_repository.g.dart';
// Will or will not throw exception on refreshToken()
final isToThrowExceptionOnRefresh = ValueNotifier(false);
@Riverpod(keepAlive: true)
AuthRepository authRepository(AuthRepositoryRef ref) {
return AuthRepository(ref.watch(fakeRemoteServerProvider));
}
class AuthRepository {
AuthRepository(this._fakeRemoteServer);
final FakeRemoteServer _fakeRemoteServer;
var _accessToken = 'initial-valid-token';
String get accessToken => _accessToken;
Future<void> refreshToken() async {
if (isToThrowExceptionOnRefresh.value) {
throw Exception('Unable to refresh token');
}
_accessToken = await _fakeRemoteServer.getNewToken();
}
}
//
// Fake remote server
//
// Will or will not the remote server return a new valid token
final isAbleToRefreshToken = ValueNotifier(true);
@Riverpod(keepAlive: true)
FakeRemoteServer fakeRemoteServer(FakeRemoteServerRef ref) {
return FakeRemoteServer();
}
class FakeRemoteServer {
var _accessToken = 'initial-valid-token';
String get accessToken => _accessToken;
Future<String> getNewToken() async {
await Future.delayed(const Duration(seconds: 2));
if (!isAbleToRefreshToken.value) {
return 'unable-to-get-new-token';
}
return _accessToken;
}
void invalidateToken() async {
_accessToken = Random().nextInt(1000).toString();
}
}