(options?: UseSessionOptions<R>)
| 160 | * |
| 161 | */ |
| 162 | export function useSession<R extends boolean>(options?: UseSessionOptions<R>) { |
| 163 | if (!SessionContext) { |
| 164 | throw new Error('React Context is unavailable in Server Components'); |
| 165 | } |
| 166 | |
| 167 | // @ts-expect-error Satisfy TS if branch on line below |
| 168 | const value: SessionContextValue<R> = React.useContext(SessionContext); |
| 169 | if (!value && process.env.NODE_ENV !== 'production') { |
| 170 | throw new Error('`useSession` must be wrapped in a <SessionProvider />'); |
| 171 | } |
| 172 | |
| 173 | const { required, onUnauthenticated } = options || {}; |
| 174 | |
| 175 | const requiredAndNotLoading = required && value.status === 'unauthenticated'; |
| 176 | |
| 177 | React.useEffect(() => { |
| 178 | if (requiredAndNotLoading) { |
| 179 | const url = `${__LINEN_AUTH.basePath}/signin?${new URLSearchParams({ |
| 180 | error: 'SessionRequired', |
| 181 | callbackUrl: window.location.href, |
| 182 | })}`; |
| 183 | if (onUnauthenticated) onUnauthenticated(); |
| 184 | else window.location.href = url; |
| 185 | } |
| 186 | }, [requiredAndNotLoading, onUnauthenticated]); |
| 187 | |
| 188 | if (requiredAndNotLoading) { |
| 189 | return { data: value.data, status: 'loading' } as const; |
| 190 | } |
| 191 | |
| 192 | return value; |
| 193 | } |
| 194 | |
| 195 | export async function getSession(params?: GetSessionParams) { |
| 196 | const session = await fetchData<Session>( |
no outgoing calls
no test coverage detected