From 203e7c4b27394a4ea1b6a7a200727a4f98842c00 Mon Sep 17 00:00:00 2001 From: wilson Date: Mon, 9 Mar 2026 22:16:56 +0000 Subject: [PATCH] feat: build the CookieAuthentication class --- src/lib/blog/auth/CookieAuthentication.ts | 38 +++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/lib/blog/auth/CookieAuthentication.ts diff --git a/src/lib/blog/auth/CookieAuthentication.ts b/src/lib/blog/auth/CookieAuthentication.ts new file mode 100644 index 0000000..ff477f7 --- /dev/null +++ b/src/lib/blog/auth/CookieAuthentication.ts @@ -0,0 +1,38 @@ +import type { Cookies } from "@sveltejs/kit"; + +export class CookieAuthentication { + + private readonly cookieValue: string; + private readonly cookieValueArray: string[]; + public static cookieName = 'auth' + public static adminAuthRole = 'admin' + + constructor( + private readonly cookies: Cookies, + ){ + this.cookieValue = this.cookies.get(CookieAuthentication.cookieName) ?? '' + this.cookieValueArray = this.cookieValue.split(',') + } + + public get isAuthdAsAdmin(): boolean { + let isAuthdAsAdmin = false; + + if (this.cookieValueArray.includes(CookieAuthentication.adminAuthRole)) { + isAuthdAsAdmin = true + } + + return isAuthdAsAdmin + } + + public setAdminAuthentication(isAuthd: boolean) { + let value = this.cookieValue + + if (isAuthd) { + value = Array.from(new Set([...this.cookieValueArray, CookieAuthentication.adminAuthRole])).join(',') + } else { + value = this.cookieValueArray.filter((i) => i !== CookieAuthentication.adminAuthRole).join(',') + } + + this.cookies.set(CookieAuthentication.cookieName, value, { path: '/'}) + } +}