break session user lookup into a util function

This commit is contained in:
Erin 2023-11-12 15:45:36 -05:00
parent ec49a67418
commit 1e57731b08
2 changed files with 23 additions and 19 deletions

View file

@ -0,0 +1,19 @@
import {getDataSource} from './db';
import {AuthSession} from './entity/AuthSession';
/** Returns the user authorized by a given session. */
export async function getUserFromSessionID (sessionID: string | undefined) {
const dataSource = await getDataSource();
const sessionsRepo = dataSource.getRepository(AuthSession);
const session = sessionID
? await sessionsRepo.findOne({
where: {id: sessionID},
relations: {
authMethod: {
user: true,
},
},
})
: null;
return session?.authMethod.user;
}

View file

@ -1,5 +1,6 @@
import {getDataSource} from '$lib/server/db'; import {getDataSource} from '$lib/server/db';
import {AuthSession} from '$lib/server/entity/AuthSession'; import {AuthSession} from '$lib/server/entity/AuthSession';
import {getUserFromSessionID} from '$lib/server/sessionutil';
import type {LayoutServerLoad} from './$types'; import type {LayoutServerLoad} from './$types';
@ -12,23 +13,7 @@ async function findSession (sessionID?: string) {
} }
export const load: LayoutServerLoad = async ({cookies}) => { export const load: LayoutServerLoad = async ({cookies}) => {
const sessionID = cookies.get('sessionid'); return JSON.parse(JSON.stringify({
const dataSource = await getDataSource(); user: await getUserFromSessionID(cookies.get('sessionid')),
const sessionsRepo = dataSource.getRepository(AuthSession); }));
const session = sessionID
? await sessionsRepo.findOne({
where: {id: sessionID},
relations: {
authMethod: {
user: true,
},
},
})
: null;
return {
user: session
? JSON.parse(JSON.stringify(session.authMethod.user))
: null,
};
}; };