53 lines
1.1 KiB
TypeScript
53 lines
1.1 KiB
TypeScript
import { headers } from 'next/headers';
|
|
import { auth } from '@/lib/auth';
|
|
import { asErrorMessage, jsonError } from '@/lib/server/http';
|
|
|
|
export type AuthenticatedSession = NonNullable<
|
|
Awaited<ReturnType<typeof auth.api.getSession>>
|
|
>;
|
|
|
|
type RequiredSessionResult = (
|
|
| {
|
|
session: AuthenticatedSession;
|
|
response: null;
|
|
}
|
|
| {
|
|
session: null;
|
|
response: Response;
|
|
}
|
|
);
|
|
|
|
export async function getAuthenticatedSession() {
|
|
const session = await auth.api.getSession({
|
|
headers: await headers()
|
|
});
|
|
|
|
if (!session?.user?.id) {
|
|
return null;
|
|
}
|
|
|
|
return session;
|
|
}
|
|
|
|
export async function requireAuthenticatedSession(): Promise<RequiredSessionResult> {
|
|
try {
|
|
const session = await getAuthenticatedSession();
|
|
if (!session) {
|
|
return {
|
|
session: null,
|
|
response: jsonError('Unauthorized', 401)
|
|
};
|
|
}
|
|
|
|
return {
|
|
session,
|
|
response: null
|
|
};
|
|
} catch (error) {
|
|
return {
|
|
session: null,
|
|
response: jsonError(asErrorMessage(error, 'Authentication subsystem is unavailable.'), 500)
|
|
};
|
|
}
|
|
}
|