From 3b30f11d0f88f4d1bb815e5ff3f7210c6c02b6c0 Mon Sep 17 00:00:00 2001 From: Araozu Date: Thu, 16 May 2024 17:16:42 -0500 Subject: [PATCH] After login, modify global axios helper to include this token in all future requests --- src/pages/Index.tsx | 3 ++- src/utils.ts | 14 +++++++++++++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index abe884b..b81e831 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -1,6 +1,6 @@ import { A, useNavigate } from "@solidjs/router"; import { createSignal, onMount, Show } from "solid-js"; -import { backend, UserInfo } from "../utils"; +import { backend, set_auth_token, UserInfo } from "../utils"; import { Card } from "../components/Card"; import { AxiosError } from "axios"; @@ -119,6 +119,7 @@ function UserRegistration(props: {setUserInfo: (u: UserInfo) => void}) { props.setUserInfo(response.data); localStorage.setItem(userIdKey, response.data.UserId); localStorage.setItem(usernameKey, response.data.Username); + set_auth_token(response.data.UserId); } catch (_e) { const e = _e as AxiosError<{error: string}>; diff --git a/src/utils.ts b/src/utils.ts index d201e50..083f03f 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,9 +1,21 @@ import axios from "axios"; -export const backend = axios.create({ +export let backend = axios.create({ baseURL: `${import.meta.env.VITE_BACKEND_URL}/api`, + headers: { + "Authorization": `Bearer ${localStorage.getItem("UserId") ?? ""}`, + }, }); +export function set_auth_token(token: string) { + backend = axios.create({ + baseURL: `${import.meta.env.VITE_BACKEND_URL}/api`, + headers: { + "Authorization": `Bearer ${token}`, + }, + }); +} + export type UserInfo = { UserId: string, Username: string,