-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathApp.tsx
More file actions
210 lines (192 loc) · 6.15 KB
/
Copy pathApp.tsx
File metadata and controls
210 lines (192 loc) · 6.15 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
import * as AuthSession from 'expo-auth-session';
import * as SecureStore from 'expo-secure-store';
import { useEffect, useState } from 'react';
import { Alert, Button, StyleSheet, Text, View } from 'react-native';
import * as WebBrowser from 'expo-web-browser';
import { Authorizer } from '@authorizerdev/authorizer-js';
// You need to swap out the Authorizer client id and domain with the one from your Authorizer client.
// In your Authorizer client, you need to also add a url to your authorized redirect urls.
const useProxy = false;
const redirectUri = AuthSession.makeRedirectUri();
console.log(redirectUri);
const authorizerClientID = 'YOUR_CLIENT_ID';
const authorizerURL = 'https://demo.authorizer.dev';
const authorizationEndpoint = `${authorizerURL}/authorize`;
const tokenEndpoint = `${authorizerURL}/oauth/token`;
const authorizerRef = new Authorizer({
clientID: authorizerClientID,
authorizerURL: authorizerURL,
redirectURL: redirectUri,
});
const authorizerRefreshTokenKey = `authorizer_refresh_token`;
export default function App() {
const [email, setEmail] = useState<string | undefined>();
const [loading, setLoading] = useState(true);
const [request, result, promptAsync] = AuthSession.useAuthRequest(
{
redirectUri,
clientId: authorizerClientID,
// id_token will return a JWT token
responseType: 'code',
// use offline access to get a refresh token and perform silent refresh in background
scopes: ['openid', 'profile', 'email', 'offline_access'],
extraParams: {
// ideally, this will be a random value
nonce: 'nonce',
},
usePKCE: true,
},
{ authorizationEndpoint }
);
console.log({ result });
console.log({ request });
// on init silently refresh token if it exists
useEffect(() => {
async function silentRefresh() {
try {
const refreshToken = await SecureStore.getItemAsync(
authorizerRefreshTokenKey
);
console.log({ existingRefreshToken: refreshToken });
if (refreshToken) {
try {
const { data, errors } = await authorizerRef.getToken({
grant_type: 'refresh_token',
refresh_token: refreshToken,
});
console.log({ data, errors });
await SecureStore.setItemAsync(
'authorizer_refresh_token',
data?.refresh_token || ``
);
// get profile
const { data: profileData, errors: profileErr } =
await authorizerRef.getProfile({
Authorization: `Bearer ${data?.access_token}`,
});
console.log({ profileData, profileErr });
setEmail(profileData?.email ?? undefined);
} catch (err) {
console.error(JSON.stringify(err));
await SecureStore.deleteItemAsync(authorizerRefreshTokenKey);
}
}
} catch (error) {
setEmail(undefined);
await SecureStore.deleteItemAsync(authorizerRefreshTokenKey);
} finally {
setLoading(false);
}
}
silentRefresh();
}, []);
useEffect(() => {
async function setResult() {
try {
if (result && result.type === 'success') {
if (result?.params.refresh_token) {
await SecureStore.setItemAsync(
authorizerRefreshTokenKey,
result.params.refresh_token
);
}
if (result.error) {
Alert.alert(
'Authentication error',
result.params.error_description || 'something went wrong'
);
return;
}
console.log({ params: result.params });
const codeRes = await AuthSession.exchangeCodeAsync(
{
code: result.params.code,
redirectUri,
clientId: authorizerClientID,
extraParams: {
code_verifier: request?.codeVerifier || '',
},
},
{ tokenEndpoint }
);
console.log({ codeRes });
const { data, errors } = await authorizerRef.getToken({
grant_type: 'refresh_token',
refresh_token: codeRes?.refreshToken,
});
console.log({ data2: data, errors2: errors });
await SecureStore.setItemAsync(
'authorizer_refresh_token',
data?.refresh_token || ``
);
// get profile
const { data: profileData, errors: profileErr } =
await authorizerRef.getProfile({
Authorization: `Bearer ${codeRes?.accessToken}`,
});
console.log({ profileData2: profileData, profileErr2: profileErr });
setEmail(profileData?.email ?? undefined);
}
} catch (err) {
console.log(err);
}
}
setResult();
}, [result]);
const handleLogout = async () => {
setLoading(true);
setEmail(undefined);
try {
const refreshToken = await SecureStore.getItemAsync(
authorizerRefreshTokenKey
);
await authorizerRef.revokeToken({
refresh_token: refreshToken || '',
});
await SecureStore.deleteItemAsync(authorizerRefreshTokenKey);
await WebBrowser.openAuthSessionAsync(
`${authorizerURL}/logout?redirect_uri=${redirectUri}`,
'redirectUrl'
);
} catch (err) {
console.log(err);
} finally {
setLoading(false);
}
};
return (
<View style={styles.container}>
{loading ? (
<Text>Loading...</Text>
) : (
<View>
{email ? (
<>
<Text style={styles.title}>You are logged in, {email}!</Text>
<Button title="Log out" onPress={handleLogout} />
</>
) : (
<Button
disabled={!request}
title="Log in with Authorizer"
onPress={() => promptAsync()}
/>
)}
</View>
)}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
title: {
fontSize: 20,
textAlign: 'center',
marginTop: 40,
},
});