From 8e25ca5dd73a459287eb6b74c63ed29b65f32203 Mon Sep 17 00:00:00 2001 From: Filip Rojek Date: Wed, 8 May 2024 16:31:21 +0200 Subject: [PATCH] Moved from axios to Fetch API, Added user object to the AuthState --- api/src/routes/api_v1.ts | 1 - frontend/app/(app)/index.js | 8 +-- frontend/app/context/AuthContext.js | 82 +++++++++++++++++++++-------- 3 files changed, 64 insertions(+), 27 deletions(-) diff --git a/api/src/routes/api_v1.ts b/api/src/routes/api_v1.ts index 214e852..bedb87f 100644 --- a/api/src/routes/api_v1.ts +++ b/api/src/routes/api_v1.ts @@ -18,7 +18,6 @@ router.get('/', docsController.docs_get); router.post("/auth/signup",validate(AuthVal.signup) , authController.signup_post); router.post("/auth/signin",validate(AuthVal.signin) , authController.signin_post); -router.options("/auth/signin",validate(AuthVal.signin) , authController.signin_post); router.post("/auth/logout", requireAuth, authController.logout_post); router.get("/auth/status", requireAuth, authController.status_get); diff --git a/frontend/app/(app)/index.js b/frontend/app/(app)/index.js index 2520d95..98fe6cc 100644 --- a/frontend/app/(app)/index.js +++ b/frontend/app/(app)/index.js @@ -3,11 +3,13 @@ import { Text, View } from "react-native"; import { useAuth } from "../context/AuthContext"; export default function Index() { - const { onLogout } = useAuth(); - const user = "debil" + const { onLogout, authState } = useAuth(); + + const user = authState.user; + return ( - Welcome {user} + Welcome {user.username} { // The `app/(app)/_layout.tsx` will redirect to the sign-in screen. diff --git a/frontend/app/context/AuthContext.js b/frontend/app/context/AuthContext.js index 7adda2d..f5d202e 100644 --- a/frontend/app/context/AuthContext.js +++ b/frontend/app/context/AuthContext.js @@ -1,5 +1,4 @@ import { createContext, useContext, useEffect, useState } from "react"; -import axios from "axios"; import storageUtil from "./storage"; const TOKEN_KEY = "my-jwt"; @@ -26,12 +25,17 @@ export function AuthProvider({ children }) { const token = await storageUtil.getItem(TOKEN_KEY); console.log(`stored: ${token}`); - if (token) { - axios.defaults.headers.common["Authorization"] = `Bearer ${token}`; + const resUser = await fetch(`${API_URL}/auth/status`, { + credentials: "include", + }); + const userData = await resUser.json(); + + if (token && resUser.status == 200) { setAuthState({ token: token, authenticated: true, + user: userData.data, }); return; @@ -39,6 +43,7 @@ export function AuthProvider({ children }) { setAuthState({ authenticated: false, token: null, + user: null, }); } loadToken(); @@ -46,49 +51,80 @@ export function AuthProvider({ children }) { async function register(username, email, password) { try { - const res = await axios.post(`${API_URL}/auth/signup`, { - username, - email, - password, - }); - return res + const res = await fetch(`${API_URL}/auth/signup`, { + method: 'POST', + credentials: 'include', + headers: { + "Content-Type": "application/json" + }, + body: JSON.stringify({ + username, + email, + password + }) + }) + return res; } catch (err) { - return { error: true, msg: err.response.data}; + return { error: true, msg: err.response.data }; } } async function login(email, password) { try { - const res = await axios.post(`${API_URL}/auth/signin`, { - email, - password, + const resLogin = await fetch(`${API_URL}/auth/signin`, { + method: "POST", + credentials: "include", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + email, + password, + }), }); + const loginData = await resLogin.json(); + + const resUser = await fetch(`${API_URL}/auth/status`, { + credentials: "include", + }); + + if (resUser.status != 200) { + throw Error("user does not have user data"); + } + + const userData = await resUser.json(); + setAuthState({ - token: res.data.data.jwt, + token: loginData.data.jwt, authenticated: true, + user: userData.data, }); - //axios.defaults.headers.common[ - // "Authorization" - //] = `Bearer ${res.data.data.jwt}`; - - await storageUtil.setItem(TOKEN_KEY, res.data.data.jwt); - - return res + await storageUtil.setItem(TOKEN_KEY, loginData.data.jwt); } catch (err) { + console.error("Failed to log in", err) return { error: true, msg: err.res }; } } async function logout() { - await storageUtil.delItem(TOKEN_KEY); + let res = await fetch(`${API_URL}/auth/logout`, { + method: "POST", + credentials: "include", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({}), + }); + res = await res.json(); - axios.defaults.headers.common["Authorization"] = ""; + await storageUtil.delItem(TOKEN_KEY); setAuthState({ token: null, authenticated: false, + user: null, }); }