This repository has been archived on 2024-10-29. You can view files and clone it, but cannot push or open issues or pull requests.
website/tools/authentication/AuthenticationContext.tsx

43 lines
1.3 KiB
TypeScript
Raw Normal View History

import { createContext, useState, useEffect, useMemo, useContext } from 'react'
2021-10-26 16:38:55 +02:00
import { useTheme } from 'next-themes'
import setLanguage from 'next-translate/setLanguage'
import { Authentication, PagePropsWithAuthentication } from '.'
2021-10-26 16:38:55 +02:00
import { UserCurrent } from '../../models/User'
export interface AuthenticationValue {
authentication: Authentication
user: UserCurrent
}
const defaultAnthenticationContext: AuthenticationValue = {} as any
const AuthenticationContext = createContext<AuthenticationValue>(
defaultAnthenticationContext
)
export const AuthenticationProvider: React.FC<PagePropsWithAuthentication> = (
props
) => {
const { setTheme } = useTheme()
const [user] = useState<UserCurrent>(props.authentication.user)
const authentication = useMemo(() => {
return new Authentication(props.authentication.tokens)
}, [props.authentication.tokens])
useEffect(() => {
setLanguage(user.settings.language).catch(() => {})
setTheme(user.settings.theme)
}, [setTheme, user.settings.language, user.settings.theme])
return (
<AuthenticationContext.Provider value={{ authentication, user }}>
{props.children}
</AuthenticationContext.Provider>
)
}
export const useAuthentication = (): AuthenticationValue => {
return useContext(AuthenticationContext)
}