Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(api): migrate login and logout to API routes #1703

Merged
merged 4 commits into from
Mar 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 19 additions & 14 deletions src/lib/components/DisclaimerModal.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -55,20 +55,25 @@
{/if}
</button>
{#if page.data.loginEnabled}
<form action="{base}/login" target="_parent" method="POST" class="w-full">
<button
type="submit"
class="flex w-full flex-wrap items-center justify-center whitespace-nowrap rounded-full border-2 border-black bg-black px-5 py-2 text-lg font-semibold text-gray-100 transition-colors hover:bg-gray-900"
>
Sign in
{#if envPublic.PUBLIC_APP_NAME === "HuggingChat"}
<span class="flex items-center">
&nbsp;with <LogoHuggingFaceBorderless classNames="text-xl mr-1 ml-1.5 flex-none" /> Hugging
Face
</span>
{/if}
</button>
</form>
<button
onclick={async () => {
const response = await fetch(`${base}/login`, {
method: "POST",
});
if (response.ok) {
window.location.href = await response.text();
}
}}
class="flex w-full flex-wrap items-center justify-center whitespace-nowrap rounded-full border-2 border-black bg-black px-5 py-2 text-lg font-semibold text-gray-100 transition-colors hover:bg-gray-900"
>
Sign in
{#if envPublic.PUBLIC_APP_NAME === "HuggingChat"}
<span class="flex items-center">
&nbsp;with <LogoHuggingFaceBorderless classNames="text-xl mr-1 ml-1.5 flex-none" /> Hugging
Face
</span>
{/if}
</button>
{/if}
</div>
</div>
Expand Down
11 changes: 8 additions & 3 deletions src/lib/components/LoginModal.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,15 @@
</p>

<form
action="{base}/{page.data.loginRequired ? 'login' : 'settings'}"
target="_parent"
method="POST"
class="flex w-full flex-col items-center gap-2"
onsubmit={async () => {
const response = await fetch(`${base}/login`, {
method: "POST",
});
if (response.ok) {
window.location.href = await response.text();
}
}}
>
{#if page.data.loginRequired}
<button
Expand Down
40 changes: 25 additions & 15 deletions src/lib/components/NavMenu.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import InfiniteScroll from "./InfiniteScroll.svelte";
import type { Conversation } from "$lib/types/Conversation";
import { CONV_NUM_PER_PAGE } from "$lib/constants/pagination";
import { goto } from "$app/navigation";

interface Props {
conversations: ConvSidebar[];
Expand Down Expand Up @@ -139,34 +140,43 @@
class="mt-0.5 flex flex-col gap-1 rounded-r-xl p-3 text-sm md:bg-gradient-to-l md:from-gray-50 md:dark:from-gray-800/30"
>
{#if user?.username || user?.email}
<form
action="{base}/logout"
method="post"
<button
onclick={async () => {
await fetch(`${base}/logout`, {
method: "POST",
});
await goto(base + "/", { invalidateAll: true });
}}
class="group flex items-center gap-1.5 rounded-lg pl-2.5 pr-2 hover:bg-gray-100 dark:hover:bg-gray-700"
>
<span
class="flex h-9 flex-none shrink items-center gap-1.5 truncate pr-2 text-gray-500 dark:text-gray-400"
>{user?.username || user?.email}</span
>
{#if !user.logoutDisabled}
<button
type="submit"
<span
class="ml-auto h-6 flex-none items-center gap-1.5 rounded-md border bg-white px-2 text-gray-700 shadow-sm group-hover:flex hover:shadow-none dark:border-gray-600 dark:bg-gray-600 dark:text-gray-400 dark:hover:text-gray-300 md:hidden"
>
Sign Out
</button>
</span>
{/if}
</form>
</button>
{/if}
{#if canLogin}
<form action="{base}/login" method="POST" target="_parent">
<button
type="submit"
class="flex h-9 w-full flex-none items-center gap-1.5 rounded-lg pl-2.5 pr-2 text-gray-500 hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-700"
>
Login
</button>
</form>
<button
onclick={async () => {
const response = await fetch(`${base}/login`, {
method: "POST",
credentials: "include",
});
if (response.ok) {
window.location.href = await response.text();
}
}}
class="flex h-9 w-full flex-none items-center gap-1.5 rounded-lg pl-2.5 pr-2 text-gray-500 hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-700"
>
Login
</button>
{/if}
<button
onclick={switchTheme}
Expand Down
27 changes: 0 additions & 27 deletions src/routes/login/+page.server.ts

This file was deleted.

28 changes: 28 additions & 0 deletions src/routes/login/+server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { getOIDCAuthorizationUrl } from "$lib/server/auth";
import { base } from "$app/paths";
import { env } from "$env/dynamic/private";

export async function POST({ request, url, locals }) {
const referer = request.headers.get("referer");
let redirectURI = `${(referer ? new URL(referer) : url).origin}${base}/login/callback`;

// TODO: Handle errors if provider is not responding

if (url.searchParams.has("callback")) {
const callback = url.searchParams.get("callback") || redirectURI;
if (env.ALTERNATIVE_REDIRECT_URLS.includes(callback)) {
redirectURI = callback;
}
}

const authorizationUrl = await getOIDCAuthorizationUrl(
{ redirectURI },
{ sessionId: locals.sessionId }
);

return new Response(authorizationUrl, {
headers: {
"Content-Type": "text/html",
},
});
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { redirect, error } from "@sveltejs/kit";
import { error, redirect } from "@sveltejs/kit";
import { getOIDCUserData, validateAndParseCsrfToken } from "$lib/server/auth";
import { z } from "zod";
import { base } from "$app/paths";
import { updateUser } from "./updateUser";
import { env } from "$env/dynamic/private";
import JSON5 from "json5";
import { updateUser } from "./updateUser.js";

const allowedUserEmails = z
.array(z.string().email())
Expand All @@ -18,7 +18,7 @@ const allowedUserDomains = z
.default([])
.parse(JSON5.parse(env.ALLOWED_USER_DOMAINS));

export async function load({ url, locals, cookies, request, getClientAddress }) {
export async function GET({ url, locals, cookies, request, getClientAddress }) {
const { error: errorName, error_description: errorDescription } = z
.object({
error: z.string().optional(),
Expand All @@ -27,7 +27,7 @@ export async function load({ url, locals, cookies, request, getClientAddress })
.parse(Object.fromEntries(url.searchParams.entries()));

if (errorName) {
error(400, errorName + (errorDescription ? ": " + errorDescription : ""));
throw error(400, errorName + (errorDescription ? ": " + errorDescription : ""));
}

const { code, state, iss } = z
Expand All @@ -43,7 +43,7 @@ export async function load({ url, locals, cookies, request, getClientAddress })
const validatedToken = await validateAndParseCsrfToken(csrfToken, locals.sessionId);

if (!validatedToken) {
error(403, "Invalid or expired CSRF token");
throw error(403, "Invalid or expired CSRF token");
}

const { userData } = await getOIDCUserData(
Expand All @@ -55,19 +55,19 @@ export async function load({ url, locals, cookies, request, getClientAddress })
// Filter by allowed user emails or domains
if (allowedUserEmails.length > 0 || allowedUserDomains.length > 0) {
if (!userData.email) {
error(403, "User not allowed: email not returned");
throw error(403, "User not allowed: email not returned");
}
const emailVerified = userData.email_verified ?? true;
if (!emailVerified) {
error(403, "User not allowed: email not verified");
throw error(403, "User not allowed: email not verified");
}

const emailDomain = userData.email.split("@")[1];
const isEmailAllowed = allowedUserEmails.includes(userData.email);
const isDomainAllowed = allowedUserDomains.includes(emailDomain);

if (!isEmailAllowed && !isDomainAllowed) {
error(403, "User not allowed");
throw error(403, "User not allowed");
}
}

Expand All @@ -79,5 +79,5 @@ export async function load({ url, locals, cookies, request, getClientAddress })
ip: getClientAddress(),
});

redirect(302, `${base}/`);
return redirect(302, `${base}/`);
}
20 changes: 0 additions & 20 deletions src/routes/logout/+page.server.ts

This file was deleted.

18 changes: 18 additions & 0 deletions src/routes/logout/+server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { dev } from "$app/environment";
import { base } from "$app/paths";
import { env } from "$env/dynamic/private";
import { collections } from "$lib/server/database";
import { redirect } from "@sveltejs/kit";

export async function POST({ locals, cookies }) {
await collections.sessions.deleteOne({ sessionId: locals.sessionId });

cookies.delete(env.COOKIE_NAME, {
path: "/",
// So that it works inside the space's iframe
sameSite: dev || env.ALLOW_INSECURE_COOKIES === "true" ? "lax" : "none",
secure: !dev && !(env.ALLOW_INSECURE_COOKIES === "true"),
httpOnly: true,
});
return redirect(302, `${base}/`);
}