Refactor authentication and implement password reset.
All checks were successful
SteamWarCI Build successful

This commit is contained in:
2025-02-17 18:29:17 +01:00
parent 23f35a35c4
commit 75f1a6528b
13 changed files with 360 additions and 95 deletions

View File

@ -21,6 +21,7 @@ export default defineAstroI18nConfig({
statistiken: "stats",
ankuendigungen: "announcements",
datenschutzerklaerung: "privacy-policy",
"passwort-zuruecksetzen": "reset-password",
"passwort-setzen": "set-password",
},
},

View File

@ -31,8 +31,7 @@
let error: string = $state("");
async function login() {
let {tokenStore} = await import("./repo/repo.ts");
let {authRepo} = await import("./repo/auth.ts");
let {authV2Repo} = await import("./repo/authv2.ts");
if (username === "" || pw === "") {
pw = "";
error = t("login.error");
@ -40,15 +39,14 @@
}
try {
let auth = await get(authRepo).login(username, pw);
if (auth == undefined) {
let auth = await get(authV2Repo).login(username, pw);
if (!auth) {
pw = "";
error = t("login.error");
return;
}
tokenStore.set(auth);
navigate(l("/dashboard"));
await navigate(l("/dashboard"));
} catch (e: any) {
pw = "";
error = t("login.error");

View File

@ -23,24 +23,35 @@
import {t} from "astro-i18n";
import {l} from "../util/util";
import {onMount} from "svelte";
import {loggedIn} from "@repo/authv2.ts";
interface Props {
logo?: import('svelte').Snippet;
}
let { logo }: Props = $props();
let navbar: HTMLDivElement = $state();
let navbar = $state<HTMLDivElement>();
let searchOpen = $state(false);
let accountBtn = $state<HTMLAnchorElement>();
$effect(() => {
if ($loggedIn) {
accountBtn!.href = l("/dashboard");
} else {
accountBtn!.href = l("/login");
}
})
onMount(() => {
handleScroll();
})
function handleScroll() {
if (window.scrollY > 0) {
navbar.classList.add("before:scale-y-100");
navbar!.classList.add("before:scale-y-100");
} else {
navbar.classList.remove("before:scale-y-100");
navbar!.classList.remove("before:scale-y-100");
}
}
</script>
@ -106,7 +117,7 @@
</div>
</div>
-->
<a class="btn" href={l("/login")}>
<a class="btn" href={l("/login")} bind:this={accountBtn}>
<span class="btn__text">{t("navbar.links.account")}</span>
</a>
<!--

View File

@ -0,0 +1,83 @@
<!--
- This file is a part of the SteamWar software.
-
- Copyright (C) 2025 SteamWar.de-Serverteam
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU Affero General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU Affero General Public License for more details.
-
- You should have received a copy of the GNU Affero General Public License
- along with this program. If not, see <https://www.gnu.org/licenses/>.
-->
<script lang="ts">
import { preventDefault } from 'svelte/legacy';
import {l} from "@utils/util.ts";
import {t} from "astro-i18n";
import {get} from "svelte/store";
import {navigate} from "astro:transitions/client";
let username: string = $state("");
let pw: string = $state("");
let pw2: string = $state("");
let error: string = $state("");
async function resetPW() {
let {authV2Repo} = await import("./repo/authv2.ts");
if (username === "" || pw === "" || pw2 === "" || pw !== pw2) {
pw = "";
pw2 = "";
error = t("login.error");
return;
}
try {
const token = decodeURI(new URLSearchParams(window.location.search).get("token") ?? "");
await get(authV2Repo).resetPassword(username, pw, token);
await navigate(l("/login"));
} catch (e: any) {
pw = "";
error = t("login.error");
}
}
</script>
<form class="bg-gray-100 dark:bg-neutral-900 p-12 rounded-2xl shadow-2xl border-2 border-gray-600 flex flex-col" onsubmit={preventDefault(resetPW)}>
<h1 class="text-4xl text-white text-center">{t("login.title")}</h1>
<div class="ml-2 flex flex-col">
<label for="username">{t("login.label.username")}</label>
<input type="text" id="username" name="username" placeholder={t("login.placeholder.username")} bind:value={username} />
<label for="password">{t("login.label.password")}</label>
<input type="password" id="password" name="password" placeholder={t("login.placeholder.password")} bind:value={pw} />
<label for="password-repeat">{t("login.label.password")}</label>
<input type="password" id="password-repeat" name="password-repeat" placeholder={t("login.placeholder.password")} bind:value={pw2} />
</div>
<p class="mt-2">
<a class="text-neutral-500 hover:underline" href={l("/set-password")}>{t("login.setPassword")}</a></p>
{#if error}
<p class="mt-2 text-red-500">{error}</p>
{/if}
<button class="btn mt-4 !mx-0 justify-center" type="submit" onclick={preventDefault(resetPW)}>{t("login.submit")}</button>
</form>
<style lang="postcss">
input {
@apply border-2 rounded-md p-2 shadow-2xl w-80 dark:bg-neutral-800 focus:outline-none focus:ring-2 focus:ring-neutral-500 focus:border-transparent text-black;
}
label {
@apply text-neutral-300;
}
</style>

View File

@ -22,38 +22,40 @@
import wrap from "svelte-spa-router/wrap";
import Router, {replace} from "svelte-spa-router";
import {get} from "svelte/store";
import {tokenStore} from "@repo/repo";
import {loggedIn} from "@repo/authv2.ts";
const routes: RouteDefinition = {
"/": wrap({asyncComponent: () => import("./pages/Home.svelte"), conditions: detail => get(tokenStore) != ""}),
"/": wrap({asyncComponent: () => import("./pages/Home.svelte"), conditions: detail => get(loggedIn)}),
"/perms": wrap({
asyncComponent: () => import("./pages/Perms.svelte"),
conditions: detail => get(tokenStore) != ""
conditions: detail => get(loggedIn)
}),
"/login": wrap({
asyncComponent: () => import("./pages/Login.svelte"),
conditions: detail => get(tokenStore) == ""
conditions: detail => !get(loggedIn)
}),
"/event/:id": wrap({
asyncComponent: () => import("./pages/Event.svelte"),
conditions: detail => get(tokenStore) != ""
conditions: detail => get(loggedIn)
}),
"/event/:id/generate": wrap({
asyncComponent: () => import("./pages/Generate.svelte"),
conditions: detail => get(tokenStore) != ""
conditions: detail => get(loggedIn)
}),
"/edit": wrap({
asyncComponent: () => import("./pages/Edit.svelte"),
conditions: detail => get(tokenStore) != ""
conditions: detail => get(loggedIn)
}),
"/display/:event": wrap({
asyncComponent: () => import("./pages/Display.svelte"),
conditions: detail => get(tokenStore) != ""
conditions: detail => get(loggedIn)
}),
"*": wrap({asyncComponent: () => import("./pages/NotFound.svelte")})
};
function conditionsFailed(event: ConditionsFailedEvent) {
console.log(event)
if (event.detail.location === "/login") {
replace("/");
} else {

View File

@ -22,9 +22,9 @@
import type {Player} from "@type/data.ts";
import {l} from "@utils/util.ts";
import Statistics from "./Statistics.svelte";
import {authRepo} from "@repo/auth.ts";
import {tokenStore} from "@repo/repo.ts";
import {authV2Repo} from "@repo/authv2.ts";
import Card from "@components/Card.svelte";
import {navigate} from "astro:transitions/client";
interface Props {
user: Player;
@ -33,9 +33,8 @@
let { user }: Props = $props();
async function logout() {
await $authRepo.logout()
tokenStore.set("")
window.location.href = l("/login")
await $authV2Repo.logout();
await navigate(l("/login"));
}
</script>

View File

@ -1,44 +0,0 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2023 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {fetchWithToken, tokenStore} from "./repo.ts";
import {derived} from "svelte/store";
export class AuthRepo {
constructor(private token: string) {
}
public async login(username: string, password: string): Promise<string> {
return await fetchWithToken(this.token, "/auth/login", {
body: JSON.stringify({
username,
password,
}),
method: "POST",
}).then(value => value.json()).then(value => value.token);
}
public async logout(): Promise<void> {
await fetchWithToken(this.token, "/auth/tokens/logout", {
method: "POST",
});
}
}
export const authRepo = derived(tokenStore, ($token) => new AuthRepo($token));

View File

@ -0,0 +1,183 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2025 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {readable, writable} from "svelte/store";
import {tokenStore} from "@repo/repo.ts";
import dayjs, {type Dayjs} from "dayjs";
import {type AuthToken, AuthTokenSchema} from "@type/auth.ts";
export class AuthV2Repo {
private accessToken: string | undefined;
private accessTokenExpires: Dayjs | undefined;
private refreshToken: string | undefined;
private refreshTokenExpires: Dayjs | undefined;
constructor() {
if (typeof localStorage === "undefined") {
return;
}
this.accessToken = localStorage.getItem("sw-access-token") ?? undefined;
if (this.accessToken) {
this.accessTokenExpires = dayjs(localStorage.getItem("sw-access-token-expires") ?? "");
}
this.refreshToken = localStorage.getItem("sw-refresh-token") ?? undefined;
if (this.refreshToken) {
loggedIn.set(true);
this.refreshTokenExpires = dayjs(localStorage.getItem("sw-refresh-token-expires") ?? "");
}
}
async login(name: string, password: string) {
if (this.accessToken !== undefined || this.refreshToken !== undefined) {
throw new Error("Already logged in");
}
try {
const login = await this.request("/v2/auth/state", {
method: "POST",
body: JSON.stringify({
name,
password,
keepLoggedIn: true,
}),
}).then(value => value.json()).then(value => AuthTokenSchema.parse(value));
this.setLoginState(login);
return true;
} catch (e) {
return false;
}
}
async resetPassword(name: string, password: string, token: string) {
return await this.requestWithToken(token, "/v2/auth/register", {
method: "POST",
body: JSON.stringify({
name,
password,
}),
});
}
async logout() {
if (this.accessToken === undefined) {
return;
}
await this.request("/v2/auth/state", {
method: "DELETE",
});
this.resetAccessToken();
this.resetRefreshToken();
}
private setLoginState(tokens: AuthToken) {
this.setAccessToken(tokens.accessToken.token, dayjs(tokens.accessToken.expires));
this.setRefreshToken(tokens.refreshToken.token, dayjs(tokens.refreshToken.expires));
loggedIn.set(true);
}
private setAccessToken(token: string, expires: Dayjs) {
this.accessToken = token;
this.accessTokenExpires = expires;
localStorage.setItem("sw-access-token", token);
localStorage.setItem("sw-access-token-expires", expires.toString());
}
private resetAccessToken() {
if (this.accessToken === undefined) {
return;
}
this.accessToken = undefined;
this.accessTokenExpires = undefined;
localStorage.removeItem("sw-access-token");
localStorage.removeItem("sw-access-token-expires");
}
private setRefreshToken(token: string, expires: Dayjs) {
this.refreshToken = token;
this.refreshTokenExpires = expires;
localStorage.setItem("sw-refresh-token", token);
localStorage.setItem("sw-refresh-token-expires", expires.toString());
}
private resetRefreshToken() {
if (this.refreshToken === undefined) {
return;
}
this.refreshToken = undefined;
this.refreshTokenExpires = undefined;
localStorage.removeItem("sw-refresh-token");
localStorage.removeItem("sw-refresh-token-expires");
loggedIn.set(false);
}
private async refresh() {
if (this.refreshToken === undefined || this.refreshTokenExpires === undefined || this.refreshTokenExpires.isBefore(dayjs().add(10, "seconds"))) {
this.resetRefreshToken();
this.resetAccessToken();
return;
}
try {
const response = await this.requestWithToken(this.refreshToken!, "/v2/auth/state", {
method: "PUT",
}).then(value => value.json()).then(value => AuthTokenSchema.parse(value));
this.setLoginState(response);
} catch (e) {
this.resetRefreshToken();
this.resetAccessToken();
return;
}
}
async request(url: string, params: RequestInit = {}) {
if (this.accessToken !== undefined && this.accessTokenExpires !== undefined && this.accessTokenExpires.isBefore(dayjs())) {
await this.refresh();
}
return this.requestWithToken(this.accessToken ?? "", url, params);
}
private async requestWithToken(token: string, url: string, params: RequestInit = {}) {
return fetch(`${import.meta.env.PUBLIC_API_SERVER}${url}`, {...params,
headers: {
...(token !== "" ? {"Authorization": "Bearer " + (token)} : {}),
"Content-Type": "application/json", ...params.headers,
},
})
.then(value => {
if (value.status === 401) {
tokenStore.set("");
}
return value;
});
}
}
export const loggedIn = writable(false);
export const authV2Repo = readable(new AuthV2Repo());

View File

@ -17,31 +17,9 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {writable} from "svelte/store";
import {get, writable} from "svelte/store";
import {authV2Repo} from "@repo/authv2.ts";
export const fetchWithToken = (token: string, url: string, params: RequestInit = {}) =>
fetch(`${import.meta.env.PUBLIC_API_SERVER}${url}`, {...params,
headers: {
...(token !== "" ? {"Authorization": "Bearer " + (token)} : {}),
"Content-Type": "application/json", ...params.headers,
},
})
.then(value => {
if (value.status === 401) {
tokenStore.set("");
}
return value;
});
export const fetchWithToken = (token: string, url: string, params: RequestInit = {}) => get(authV2Repo).request(url, params);
export function getLocalStorage() {
if (typeof localStorage === "undefined") {
return {
getItem: () => "",
setItem: () => {},
};
}
return localStorage;
}
export const tokenStore = writable((getLocalStorage().getItem("sw-session") ?? ""));
tokenStore.subscribe((value) => getLocalStorage().setItem("sw-session", value));
export const tokenStore = writable("");

View File

@ -0,0 +1,34 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2025 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {z} from "zod";
export const TokenSchema = z.object({
token: z.string(),
expires: z.string(),
});
export type Token = z.infer<typeof TokenSchema>;
export const AuthTokenSchema = z.object({
accessToken: TokenSchema,
refreshToken: TokenSchema,
});
export type AuthToken = z.infer<typeof AuthTokenSchema>;

View File

@ -8,9 +8,11 @@ import {t} from "astro-i18n";
<script>
import {l} from "../util/util";
import {navigate} from "astro:transitions/client";
import {get} from "svelte/store";
import {loggedIn} from "../components/repo/authv2";
document.addEventListener("astro:page-load", () => {
if (window.location.href.endsWith("/dashboard") || window.location.href.endsWith("/dashboard/")) {
if ((localStorage.getItem("sw-session") ?? "") === "") {
if (!get(loggedIn)) {
navigate(l("/login"), {});
}
}

View File

@ -9,10 +9,12 @@ import BackgroundImage from "../components/BackgroundImage.astro";
<script>
import {l} from "../util/util";
import {navigate} from "astro:transitions/client";
import {loggedIn} from "../components/repo/authv2";
import {get} from "svelte/store";
document.addEventListener("astro:page-load", () => {
if (window.location.href.endsWith("/login") || window.location.href.endsWith("/login/")) {
if ((localStorage.getItem("sw-session") ?? "") !== "") {
if (get(loggedIn)) {
navigate(l("/dashboard"), {history: "replace"});
}
}

View File

@ -0,0 +1,16 @@
---
import {t} from "astro-i18n";
import BackgroundImage from "../components/BackgroundImage.astro";
import ResetPasswordComponent from "../components/ResetPasswordComponent.svelte";
import NavbarLayout from "../layouts/NavbarLayout.astro";
---
<NavbarLayout title={t("login.page")}>
<div class="h-screen w-screen fixed -z-10">
<BackgroundImage />
</div>
<div class="h-screen mx-auto p-8 rounded-b-md pt-40 sm:pt-28 md:pt-14 flex flex-col justify-center items-center
dark:text-white " style="width: min(100vw, 75em);">
<ResetPasswordComponent client:load/>
</div>
</NavbarLayout>