Skip to content

Commit 6182ed0

Browse files
committed
improvements
1 parent 4c9240c commit 6182ed0

4 files changed

Lines changed: 72 additions & 74 deletions

File tree

README.md

Lines changed: 26 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -9,22 +9,23 @@ A wrapper on auth0's react native library with common case features already impl
99
```sh
1010
$ npm i @cobuildlab/react-native-auth0
1111
```
12+
1213
## Usage
1314

1415
#### Auth0 Client Setup:
1516

1617
Create a new client instance using Auth0Native:
1718

18-
```tsx
19+
```ts
1920
import { Auth0Native } from '@cobuildlab/react-native-auth0';
2021

2122
// AUTH0 options
2223
const AUTH0_OPTIONS = {
2324
clientId: AUTH_CLIENT_ID,
2425
domain: AUTH_CLIENT_DOMAIN,
25-
}
26+
};
2627

27-
// You can handle the credentials obtained in auth0
28+
// You can handle the credentials obtained in auth0
2829
// and store them in the async store or another store of your choice
2930
const CREDENTIALS_HANDLER = {
3031
save: async (credentials): Promise<void> => {
@@ -39,7 +40,15 @@ const CREDENTIALS_HANDLER = {
3940
await AsyncStorage.removeItem('credentials_store');
4041
apolloClient.resetStore();
4142
},
42-
}
43+
validateToken: (credentials) => {
44+
const { exp } = jwtDecode(credentials.idToken) as { exp: number };
45+
46+
// Current time unix (in seconds)
47+
const currentTime = Math.floor(new Date().getTime() / 1000);
48+
49+
return exp > currentTime;
50+
},
51+
};
4352

4453
export const client = new Auth0Native(AUTH0_OPTIONS, CREDENTIALS_HANDLER);
4554
```
@@ -50,13 +59,10 @@ Then import the client and pass through props to the provider:
5059
import { AuthProvider } from '@cobuildlab/react-native-auth0';
5160
import { client } from './config';
5261

53-
5462
const AUTH0_SCOPE = 'offline_access email openid profile';
5563

5664
export const App = () => (
57-
<AuthProvider
58-
client={auth0NativeClient}
59-
scope={client}>
65+
<AuthProvider client={auth0NativeClient} scope={client}>
6066
<App />
6167
</AuthProvider>
6268
);
@@ -105,26 +111,26 @@ App Component:
105111
import { useAuth } from '@cobuildlab/react-native-auth0';
106112
import { LoginView } from './LoginView';
107113
import { LogOutView } from './LogOutView';
108-
import { MainView, Loading } from './others'
109-
114+
import { MainView, Loading } from './others';
110115

111116
export function App() {
112117
const { isLoading, isAuthenticated, clearSession } = useAuth();
113118

114-
if(isLoading){
115-
return <Loading />
119+
if (isLoading) {
120+
return <Loading />;
116121
}
117122

118-
if(!isAuthenticated){
119-
return < LoginView />
123+
if (!isAuthenticated) {
124+
return <LoginView />;
120125
}
121126

122-
return <MainView />
127+
return <MainView />;
123128
}
124-
125129
```
126130

127-
### TODO
128-
129-
- Documentation
130-
- Test Code
131+
### TODO
132+
133+
- Documentation
134+
- Test Code
135+
- Hanlde error cases
136+
- hook for subscribe to error cases

src/client.ts

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,34 +4,38 @@ import Auth0, {
44
Options,
55
} from 'react-native-auth0';
66
import { Credentials, CredentialsHandlersInput, ErrorCases } from './types';
7-
import { ErrorPublisher, getTimestamp } from './utils';
7+
import { ErrorPublisher } from './utils';
88

99
export class Auth0Native extends Auth0 {
1010
private credentials: Credentials | null = null;
1111

1212
private saveCredentials: CredentialsHandlersInput['save'];
13-
1413
private getCredentials: CredentialsHandlersInput['get'];
15-
1614
private clearCredentials: CredentialsHandlersInput['clear'];
15+
private validateToken: CredentialsHandlersInput['validateToken'];
1716

1817
private errors: Record<ErrorCases, ErrorPublisher> = {
1918
AUTHORIZATION: new ErrorPublisher(),
2019
CLEAR_SESSION: new ErrorPublisher(),
2120
REFRESH_TOKEN: new ErrorPublisher(),
21+
SAVE_CREDENTIALS: new ErrorPublisher(),
2222
};
2323

2424
constructor(options: Options, credentialsHandlers: CredentialsHandlersInput) {
2525
super(options);
2626
this.saveCredentials = credentialsHandlers.save;
2727
this.getCredentials = credentialsHandlers.get;
2828
this.clearCredentials = credentialsHandlers.clear;
29+
this.validateToken = credentialsHandlers.validateToken;
2930
}
3031

3132
async handleCredentials(data: Auth0Credentials): Promise<Credentials> {
32-
const credentials: Credentials = { ...data, issuedAt: getTimestamp() };
33-
34-
await this.saveCredentials(credentials);
33+
const credentials: Credentials = { ...data };
34+
try {
35+
await this.saveCredentials(credentials);
36+
} catch (error) {
37+
this.errors.SAVE_CREDENTIALS.notify(error as Error);
38+
}
3539

3640
this.credentials = credentials;
3741

@@ -63,7 +67,8 @@ export class Auth0Native extends Auth0 {
6367
return this.handleCredentials(result);
6468
} catch (error) {
6569
this.errors.AUTHORIZATION.notify(error as Error);
66-
return;
70+
71+
throw error;
6772
}
6873
}
6974

@@ -86,11 +91,7 @@ export class Auth0Native extends Auth0 {
8691
return false;
8792
}
8893

89-
const tokenTimestamp = credentials.expiresIn + credentials.issuedAt;
90-
91-
const validToken = tokenTimestamp > getTimestamp();
92-
93-
if (validToken) {
94+
if (this.validateToken(credentials)) {
9495
this.credentials = credentials;
9596
return true;
9697
}

src/provider.tsx

Lines changed: 30 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -16,61 +16,50 @@ export const AuthProvider: React.FC<{
1616
});
1717

1818
useEffect(() => {
19-
(async () => {
20-
try {
21-
const isAuth = await client.isAuthenticated();
22-
23-
setState((prev) => ({
24-
...prev,
25-
isLoading: false,
26-
isAuthenticated: isAuth,
27-
}));
28-
} catch (error) {
29-
console.log(error);
30-
}
31-
})();
19+
client.isAuthenticated().then((isAuth) => {
20+
setState((prev) => ({
21+
...prev,
22+
isLoading: false,
23+
isAuthenticated: isAuth,
24+
}));
25+
});
3226
}, [client]);
3327

3428
const authorize: AuthClientContextType['authorize'] = async ({
3529
scope: newScope,
3630
options,
3731
}) => {
3832
setState((prev) => ({ ...prev, isLoading: true }));
39-
40-
try {
41-
await client.authorize(newScope || scope, options);
42-
43-
setState((prev) => ({
44-
...prev,
45-
isLoading: false,
46-
isAuthenticated: true,
47-
}));
48-
} catch {
49-
setState((prev) => ({
50-
...prev,
51-
isLoading: false,
52-
isAuthenticated: false,
53-
}));
54-
}
33+
client
34+
.authorize(newScope || scope, options)
35+
.then(() => {
36+
setState((prev) => ({
37+
...prev,
38+
isLoading: false,
39+
isAuthenticated: true,
40+
}));
41+
})
42+
.catch(() => {
43+
setState((prev) => ({
44+
...prev,
45+
isLoading: false,
46+
isAuthenticated: false,
47+
}));
48+
});
5549
};
5650

5751
const clearSession: AuthClientContextType['clearSession'] = async () => {
5852
setState((prev) => ({
5953
...prev,
6054
isLoading: true,
6155
}));
62-
console.log('logging out...');
63-
64-
try {
65-
await client.clearSession();
66-
} catch (error) {
67-
console.log(error);
68-
}
69-
setState((prev) => ({
70-
...prev,
71-
isLoading: false,
72-
isAuthenticated: false,
73-
}));
56+
client.clearSession().then(() => {
57+
setState((prev) => ({
58+
...prev,
59+
isLoading: false,
60+
isAuthenticated: false,
61+
}));
62+
});
7463
};
7564

7665
return (

src/types.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,14 @@ import {
44
} from 'react-native-auth0';
55

66
export interface Credentials extends Auth0Credentials {
7-
issuedAt: number;
7+
issuedAt?: number;
88
}
99

1010
export type CredentialsHandlersInput = {
1111
save: (data: Credentials) => void | Promise<void>;
1212
clear: () => void | Promise<void>;
1313
get: () => (Credentials | null) | Promise<Credentials | null>;
14+
validateToken: (data: Credentials) => boolean;
1415
};
1516

1617
export interface AuthClientContextType {
@@ -29,4 +30,5 @@ export enum ErrorCases {
2930
AUTHORIZATION = 'AUTHORIZATION',
3031
CLEAR_SESSION = 'CLEAR_SESSION',
3132
REFRESH_TOKEN = 'REFRESH_TOKEN',
33+
SAVE_CREDENTIALS = 'SAVE_CREDENTIALS',
3234
}

0 commit comments

Comments
 (0)