UNPKG

@vaadin/hilla-react-auth

Version:

Hilla auth utils for React

60 lines (59 loc) 1.87 kB
import { type LoginOptions, type LoginResult } from "@vaadin/hilla-frontend"; import { type Context } from "react"; type LoginFunction = (username: string, password: string, options?: LoginOptions) => Promise<LoginResult>; type LogoutFunction = () => Promise<void>; /** * The type of the function that is used to get the authenticated user. */ export type GetUserFn<TUser> = () => Promise<TUser | undefined>; type AuthState<TUser> = Readonly<{ initializing: boolean loading: boolean user?: TUser error?: string getAuthenticatedUser?: GetUserFn<TUser> }>; /** * The properties that can be used to control access to a route. * They can be added to the route type handler as properties. */ export type AccessProps = Readonly<{ /** * If true, the user must be logged in to access the route. */ loginRequired?: boolean /** * If true, the user must be logged in to access the route. * * @deprecated Use `loginRequired` instead. */ requiresLogin?: boolean /** * The list of roles that are allowed to access the route. */ rolesAllowed?: readonly [string, ...string[]] }>; /** * The type of the authentication hook. */ export type Authentication<TUser> = Readonly<{ state: AuthState<TUser> login: LoginFunction logout: LogoutFunction hasAccess(accessProps: AccessProps): boolean }>; /** * The hook that can be used to get the authentication state. * It returns the state of the authentication. */ export declare const AuthContext: Context<Authentication<unknown>>; interface AuthConfig<TUser> { getRoles?(user: TUser): readonly string[]; } export type AuthHook<TUser> = () => Authentication<TUser>; interface AuthModule<TUser> { AuthProvider: React.FC<React.PropsWithChildren>; useAuth: AuthHook<TUser>; } export declare function configureAuth<TUser>(getAuthenticatedUser: GetUserFn<TUser>, config?: AuthConfig<TUser>): AuthModule<TUser>; export {};