less database requests

This commit is contained in:
Alexander Bocken 2023-07-20 14:48:50 +02:00
parent 59ab194b08
commit af2b513677
Signed by: Alexander
GPG Key ID: 1D237BE83F9B05E8
5 changed files with 43 additions and 31 deletions

View File

@ -0,0 +1,33 @@
import type { RequestEvent } from "@sveltejs/kit";
import { COOKIE_SECRET } from "$env/static/private";
import pkg from 'jsonwebtoken';
const { verify } = pkg;
import { error } from "@sveltejs/kit";
import { dbConnect, dbDisconnect } from "../../utils/db";
import { User } from "../../models/User";;
export async function get_username(cookies){
// Set your master secret key (replace with your own secret)
const masterSecret = COOKIE_SECRET;
const secretKey = masterSecret
let decoded
try{
const cookie : string = cookies.get("UserSession")
if(cookie){
decoded = await verify(cookie, secretKey);
}
}
catch(e){
return null
}
if(decoded){
return {
username: decoded.username,
}
}
else{
return null
}
}

View File

@ -1,9 +1,5 @@
import type {LayoutServerLoad} from './$types'; import { get_username } from '$lib/js/get_username';;
import { authenticateUser } from '$lib/js/authenticate';;
export const load = (async ({cookies}) => { export const load = (async ({cookies}) => {
const user = await authenticateUser(cookies) return { user: await get_username(cookies) }
return { });
user
}
}) satisfies LayoutServerLoad;

View File

@ -1,16 +0,0 @@
<script lang="ts">
import Header from "$lib/components/Header.svelte";
import Calendar from "$lib/components/Calendar.svelte";
</script>
<Header>
<ul class=site_header slot=links>
<li><a href="/">Home</a></li>
</ul>
<Calendar>
</Calendar>
</Header>

View File

@ -1,8 +1,5 @@
import { authenticateUser } from '$lib/js/authenticate';; import { get_username } from '$lib/js/get_username';;
export const load = (async ({cookies}) => { export const load = (async ({cookies}) => {
const user = await authenticateUser(cookies) return { user: await get_username(cookies) }
return {
user
}
}); });

View File

@ -3,7 +3,9 @@ import Header from '$lib/components/Header.svelte'
import UserHeader from '$lib/components/UserHeader.svelte'; import UserHeader from '$lib/components/UserHeader.svelte';
export let data export let data
let username = "" let username = ""
if(data.user) username = data.user.username if(data.user){
username = data.user.username
}
</script> </script>
<Header> <Header>
@ -14,6 +16,6 @@ if(data.user) username = data.user.username
<li><a href="/rezepte/icon">Icon</a></li> <li><a href="/rezepte/icon">Icon</a></li>
<li><a href="/rezepte/tag">Stichwörter</a></li> <li><a href="/rezepte/tag">Stichwörter</a></li>
</ul> </ul>
<UserHeader {username} slot=right_side></UserHeader> <UserHeader slot=right_side {username}></UserHeader>
<slot></slot> <slot></slot>
</Header> </Header>