From 6ec41bac23d941b81b93883d00602c8ccec9ff35 Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Sun, 29 Dec 2024 11:59:02 -0800 Subject: nostr login --- src/routes/(app)/[username]/(profile)/+page.svelte | 9 +++ src/routes/(static)/login/+page.server.ts | 44 ++++++++++++- src/routes/(static)/login/+page.svelte | 73 +++++++++++++++++++--- 3 files changed, 114 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/src/routes/(app)/[username]/(profile)/+page.svelte b/src/routes/(app)/[username]/(profile)/+page.svelte index 05273bc5..53a994ad 100644 --- a/src/routes/(app)/[username]/(profile)/+page.svelte +++ b/src/routes/(app)/[username]/(profile)/+page.svelte @@ -1,4 +1,6 @@
diff --git a/src/routes/(static)/login/+page.server.ts b/src/routes/(static)/login/+page.server.ts index 6e268c92..740f02d8 100644 --- a/src/routes/(static)/login/+page.server.ts +++ b/src/routes/(static)/login/+page.server.ts @@ -1,13 +1,15 @@ -import { fd, login } from "$lib/utils"; +import { fd, get, login } from "$lib/utils"; import { fail, redirect } from "@sveltejs/kit"; export const load = async ({ parent }) => { const { user } = await parent(); if (user?.pubkey) redirect(307, `/${user.username}`); + const { id } = await get("/challenge"); + return { id }; }; export const actions = { - default: async ({ cookies, request }) => { + login: async ({ cookies, request }) => { const form = await fd(request); let { username, password, token, loginRedirect } = form; const user = { username, password, token }; @@ -23,4 +25,42 @@ export const actions = { redirect(307, loginRedirect || `/${user.username}`); }, + + nostr: async ({ cookies, fetch, request }) => { + const form = await fd(request); + let { id, event, loginRedirect } = form; + if (loginRedirect === "null") loginRedirect = undefined; + event = JSON.parse(event); + + const maxAge = 380 * 24 * 60 * 60; + + const res = await fetch("/api/nostrLogin", { + method: "POST", + body: JSON.stringify({ id, event }), + headers: { + "content-type": "application/json", + accept: "application/json", + "cf-connecting-ip": request.headers.get("cf-connecting-ip"), + }, + }); + + if (res.status === 401) { + const text = await res.text(); + if (text.startsWith("2fa")) throw new Error("2fa"); + } + + const { user, token } = await res.json(); + if (!token) throw new Error("Login failed"); + const { username, language } = user; + + const expires = new Date(); + expires.setSeconds(expires.getSeconds() + maxAge); + + const opts = { path: "/", expires }; + if (language) cookies.set("lang", language, opts); + cookies.set("username", username, opts); + cookies.set("token", token, opts); + + redirect(307, loginRedirect || `/${username}`); + }, }; diff --git a/src/routes/(static)/login/+page.svelte b/src/routes/(static)/login/+page.svelte index 5caf48fb..b49ba036 100644 --- a/src/routes/(static)/login/+page.svelte +++ b/src/routes/(static)/login/+page.svelte @@ -1,5 +1,5 @@
{/if} -
- + + + {#if nostr} + + {/if} +

{$t("login.noAccount")}