feat: restructure routing and authentication for hidden layout and user login
This commit is contained in:
+26
-24
@@ -1,29 +1,33 @@
|
||||
import { API_BASE } from "../config/api.config";
|
||||
import Cookies from "js-cookie";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { TFunction } from "i18next";
|
||||
import { toast } from "react-toastify";
|
||||
import { redirect } from "@tanstack/react-router";
|
||||
|
||||
const { t } = useTranslation();
|
||||
|
||||
export async function isAuthenticated() {
|
||||
const result = await fetch(`${API_BASE}/users/verify-token`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${Cookies.get("token") || ""}`,
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
},
|
||||
});
|
||||
if (Cookies.get("token")) {
|
||||
const result = await fetch(`${API_BASE}/users/verify-token`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${Cookies.get("token") || ""}`,
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
if (result.status === 200) {
|
||||
return true;
|
||||
if (result.status === 200) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
Cookies.remove("token");
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function signInUser(username: string, password: string) {
|
||||
export async function signInUser(
|
||||
username: string,
|
||||
password: string,
|
||||
t: TFunction,
|
||||
) {
|
||||
const result = await fetch(`${API_BASE}/users/login`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
@@ -35,21 +39,19 @@ export async function signInUser(username: string, password: string) {
|
||||
});
|
||||
|
||||
const response = await result.json();
|
||||
console.log(response);
|
||||
|
||||
if (result.status === 202) {
|
||||
Cookies.set("token", response.token);
|
||||
return true;
|
||||
Cookies.set("token", response.data.token);
|
||||
return { ok: true as const };
|
||||
}
|
||||
|
||||
if (result.status !== 202) {
|
||||
Cookies.remove("token");
|
||||
toast.error(t(response.code));
|
||||
}
|
||||
Cookies.remove("token");
|
||||
toast.error(t(response.code));
|
||||
return { ok: false as const };
|
||||
}
|
||||
|
||||
export function signOutUser() {
|
||||
Cookies.remove("token");
|
||||
throw redirect({
|
||||
to: "/login",
|
||||
});
|
||||
return { ok: true as const };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"username": "Benutzername",
|
||||
"password": "Passwort",
|
||||
"eu001": "Falscher Benutzername oder Passwort!",
|
||||
"login": "Login"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"username": "Username",
|
||||
"password": "Password",
|
||||
"eu001": "Wrong username or password!",
|
||||
"login": "Login"
|
||||
}
|
||||
Reference in New Issue
Block a user