|
1 | | -import { createContext, use, useState, useEffect } from "react" |
| 1 | +import { AuthProvider as AuraAuthProvider, type AuthProviderProps } from "@aura-stack/react" |
2 | 2 | import { authClient } from "@/lib/client" |
3 | | -import type { Session, LiteralUnion, BuiltInOAuthProvider, SignInOptions, SignOutOptions } from "@aura-stack/auth" |
4 | | -import type { AuthProviderProps } from "@/@types/props" |
5 | | -import type { AuthContextValue } from "@/@types/types" |
6 | 3 |
|
7 | | -export const AuthContext = createContext<AuthContextValue | undefined>(undefined) |
8 | | - |
9 | | -export const AuthProvider = ({ children, session: defaultSession }: AuthProviderProps) => { |
10 | | - const [isLoading, setIsLoading] = useState(defaultSession === undefined) |
11 | | - const [session, setSession] = useState<Session | null>(defaultSession ?? null) |
12 | | - const isAuthenticated = Boolean(session?.user) |
13 | | - |
14 | | - const signIn = async (provider: LiteralUnion<BuiltInOAuthProvider>, options?: SignInOptions) => { |
15 | | - setIsLoading(true) |
16 | | - try { |
17 | | - return await authClient.signIn(provider, options) |
18 | | - } finally { |
19 | | - setIsLoading(false) |
20 | | - } |
21 | | - } |
22 | | - |
23 | | - const signOut = async (options?: SignOutOptions) => { |
24 | | - setIsLoading(true) |
25 | | - try { |
26 | | - const value = await authClient.signOut(options) |
27 | | - setSession(null) |
28 | | - return value |
29 | | - } finally { |
30 | | - setIsLoading(false) |
31 | | - } |
32 | | - } |
33 | | - |
34 | | - useEffect(() => { |
35 | | - if (defaultSession !== undefined) { |
36 | | - setSession(defaultSession) |
37 | | - setIsLoading(false) |
38 | | - return |
39 | | - } |
40 | | - const fetchSession = async () => { |
41 | | - try { |
42 | | - const session = await authClient.getSession() |
43 | | - setSession(session) |
44 | | - } catch { |
45 | | - setSession(null) |
46 | | - } finally { |
47 | | - setIsLoading(false) |
48 | | - } |
49 | | - } |
50 | | - fetchSession() |
51 | | - }, [defaultSession]) |
52 | | - |
53 | | - return <AuthContext value={{ session, isAuthenticated, isLoading, signIn, signOut }}>{children}</AuthContext> |
54 | | -} |
55 | | - |
56 | | -export const useAuth = () => { |
57 | | - const ctx = use(AuthContext) |
58 | | - if (!ctx) { |
59 | | - throw new Error("useAuth must be used within an AuthProvider") |
60 | | - } |
61 | | - return ctx |
| 4 | +export const AuthProvider = ({ children, initialSession }: Omit<AuthProviderProps, "client">) => { |
| 5 | + return ( |
| 6 | + <AuraAuthProvider client={authClient} initialSession={initialSession}> |
| 7 | + {children} |
| 8 | + </AuraAuthProvider> |
| 9 | + ) |
62 | 10 | } |
0 commit comments