49 lines
1.4 KiB
TypeScript
49 lines
1.4 KiB
TypeScript
import { readAuthConfig, type AuthConfig } from "../../shared/auth-config";
|
|
import { createLoggedInAuthState, createLoggedOutAuthState } from "./state";
|
|
import type { AuthClientLike } from "./types";
|
|
|
|
export interface AuthController {
|
|
getAccessToken(): Promise<string>;
|
|
getAuthState(): Promise<ReturnType<typeof createLoggedOutAuthState>>;
|
|
signIn(): Promise<void>;
|
|
signOut(): Promise<void>;
|
|
}
|
|
|
|
export function createAuthController(options: {
|
|
authClient: AuthClientLike;
|
|
config?: AuthConfig;
|
|
}): AuthController {
|
|
const config = options.config ?? readAuthConfig();
|
|
|
|
return {
|
|
async getAccessToken() {
|
|
return options.authClient.getAccessToken(config.apiResource);
|
|
},
|
|
async getAuthState() {
|
|
const isAuthenticated = await options.authClient.isAuthenticated();
|
|
|
|
if (!isAuthenticated) {
|
|
return createLoggedOutAuthState(config);
|
|
}
|
|
|
|
try {
|
|
await options.authClient.getAccessToken(config.apiResource);
|
|
} catch (error) {
|
|
return createLoggedOutAuthState(
|
|
config,
|
|
error instanceof Error ? error.message : String(error)
|
|
);
|
|
}
|
|
|
|
const claims = await options.authClient.getIdTokenClaims();
|
|
return createLoggedInAuthState(claims, config);
|
|
},
|
|
async signIn() {
|
|
await options.authClient.signIn();
|
|
},
|
|
async signOut() {
|
|
await options.authClient.signOut();
|
|
}
|
|
};
|
|
}
|