-
Notifications
You must be signed in to change notification settings - Fork 33
/
AuthManager.ts
77 lines (63 loc) · 2.57 KB
/
AuthManager.ts
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// Copyright (c) Microsoft.
// Licensed under the MIT license.
import AsyncStorage from '@react-native-async-storage/async-storage';
import {authorize, refresh, AuthConfiguration} from 'react-native-app-auth';
import {compareAsc, parseISO, sub} from 'date-fns';
import {AuthConfig} from './AuthConfig';
const config: AuthConfiguration = {
clientId: AuthConfig.appId,
redirectUrl: 'graph-sample://react-native-auth/',
scopes: AuthConfig.appScopes,
additionalParameters: {prompt: 'select_account'},
serviceConfiguration: {
authorizationEndpoint:
'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',
tokenEndpoint: 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
},
};
export class AuthManager {
static signInAsync = async () => {
const result = await authorize(config);
console.log(result.accessToken);
// Store the access token, refresh token, and expiration time in storage
await AsyncStorage.setItem('userToken', result.accessToken);
await AsyncStorage.setItem('refreshToken', result.refreshToken);
await AsyncStorage.setItem('expireTime', result.accessTokenExpirationDate);
};
static signOutAsync = async () => {
// Clear storage
await AsyncStorage.removeItem('userToken');
await AsyncStorage.removeItem('refreshToken');
await AsyncStorage.removeItem('expireTime');
};
static getAccessTokenAsync = async () => {
const expireTime = await AsyncStorage.getItem('expireTime');
if (expireTime !== null) {
// Get expiration time - 5 minutes
// If it's <= 5 minutes before expiration, then refresh
const expire = sub(parseISO(expireTime), {minutes: 5});
const now = new Date();
if (compareAsc(now, expire) >= 0) {
// Expired, refresh
console.log('Refreshing token');
const refreshToken = await AsyncStorage.getItem('refreshToken');
console.log(`Refresh token: ${refreshToken}`);
const result = await refresh(config, {
refreshToken: refreshToken || '',
});
// Store the new access token, refresh token, and expiration time in storage
await AsyncStorage.setItem('userToken', result.accessToken);
await AsyncStorage.setItem('refreshToken', result.refreshToken || '');
await AsyncStorage.setItem(
'expireTime',
result.accessTokenExpirationDate,
);
return result.accessToken;
}
// Not expired, just return saved access token
const accessToken = await AsyncStorage.getItem('userToken');
return accessToken;
}
return null;
};
}