@companyio/auth-react 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +21 -0
- package/src/index.tsx +42 -0
- package/tsconfig.json +12 -0
package/package.json
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@companyio/auth-react",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "React provider and hooks for the shared authentication platform",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"dependencies": {
|
|
9
|
+
"react": "^18.2.0",
|
|
10
|
+
"@companyio/auth-client": "0.1.0",
|
|
11
|
+
"@companyio/auth-contracts": "0.1.0"
|
|
12
|
+
},
|
|
13
|
+
"devDependencies": {
|
|
14
|
+
"@types/react": "^18.2.0",
|
|
15
|
+
"typescript": "^5.3.3"
|
|
16
|
+
},
|
|
17
|
+
"scripts": {
|
|
18
|
+
"build": "tsc",
|
|
19
|
+
"test": "exit 0"
|
|
20
|
+
}
|
|
21
|
+
}
|
package/src/index.tsx
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { createContext, PropsWithChildren, useContext, useEffect, useState } from 'react';
|
|
2
|
+
import { AuthClient } from '@companyio/auth-client';
|
|
3
|
+
import { AuthSession, User } from '@companyio/auth-contracts';
|
|
4
|
+
|
|
5
|
+
type AuthContextValue = {
|
|
6
|
+
client: AuthClient;
|
|
7
|
+
session: AuthSession | null;
|
|
8
|
+
user: User | null;
|
|
9
|
+
isLoading: boolean;
|
|
10
|
+
signIn: (provider?: string) => Promise<void>;
|
|
11
|
+
signOut: () => Promise<void>;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
const AuthContext = createContext<AuthContextValue | null>(null);
|
|
15
|
+
|
|
16
|
+
export const AuthProvider = ({ client, children }: PropsWithChildren<{ client: AuthClient }>) => {
|
|
17
|
+
const [session, setSession] = useState<AuthSession | null>(client.session);
|
|
18
|
+
const [isLoading, setIsLoading] = useState(true);
|
|
19
|
+
|
|
20
|
+
useEffect(() => {
|
|
21
|
+
const unsubscribe = client.subscribe(setSession);
|
|
22
|
+
void client.restore().finally(() => setIsLoading(false));
|
|
23
|
+
return unsubscribe;
|
|
24
|
+
}, [client]);
|
|
25
|
+
|
|
26
|
+
const value: AuthContextValue = {
|
|
27
|
+
client,
|
|
28
|
+
session,
|
|
29
|
+
user: session?.user ?? null,
|
|
30
|
+
isLoading,
|
|
31
|
+
signIn: (provider) => client.signIn(provider),
|
|
32
|
+
signOut: () => client.signOut(),
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
export const useAuth = (): AuthContextValue => {
|
|
39
|
+
const context = useContext(AuthContext);
|
|
40
|
+
if (!context) throw new Error('useAuth must be used inside an AuthProvider.');
|
|
41
|
+
return context;
|
|
42
|
+
};
|
package/tsconfig.json
ADDED