diff options
| author | l3wdfut4pwr <l3wdfut4pwr@gmail.com> | 2026-04-02 08:36:51 +0300 |
|---|---|---|
| committer | l3wdfut4pwr <l3wdfut4pwr@gmail.com> | 2026-04-02 08:36:51 +0300 |
| commit | 1d20080db8a26e4b7dd4071daac1166142592afa (patch) | |
| tree | b4c1bbb3725f00515b4d9a3d1cd18584cba36c81 /src/lib/contexts | |
| parent | 37f51ee88710868a77b4645294cf32862f55e7c4 (diff) | |
minor improvements
Diffstat (limited to 'src/lib/contexts')
| -rw-r--r-- | src/lib/contexts/Auth.context.tsx | 42 | ||||
| -rw-r--r-- | src/lib/contexts/Global.context.tsx | 2 |
2 files changed, 26 insertions, 18 deletions
diff --git a/src/lib/contexts/Auth.context.tsx b/src/lib/contexts/Auth.context.tsx index 29e2005..fbf2e24 100644 --- a/src/lib/contexts/Auth.context.tsx +++ b/src/lib/contexts/Auth.context.tsx @@ -1,39 +1,49 @@ 'use client'; import React, { createContext, useState, useContext, useEffect } from 'react'; -type User = { +export type User = { id: number; username: string; + avatar?: string; + banner_file?: string; + premium?: boolean; + is_banned?: boolean; + is_moderator?: boolean; }; - interface AuthContextType { user: User | null; setUser: (user: User | null) => void; logout: () => void; } - const AuthContext = createContext<AuthContextType | null>(null); +const API_URL = process.env.NEXT_PUBLIC_API_URL; export const AuthContextProvider = ({ children }: React.PropsWithChildren) => { const [user, setUser] = useState<User | null>(null); useEffect(() => { - const token = localStorage.getItem('token'); - if (!token) return; + const fetchUser = async () => { + const hasCookies = document.cookie.includes('access_token'); + if (!hasCookies) return; + + try { + const res = await fetch(`${API_URL}/api/me`, { + credentials: 'include', + }); + if (!res.ok) return; + const userData = await res.json(); + setUser(userData); + } catch {} + }; - fetch('http://localhost:8000/api/me', { - headers: { Authorization: `Bearer ${token}` }, - }) - .then((res) => { - if (!res.ok) throw new Error('Not authenticated'); - return res.json(); - }) - .then((userData) => setUser(userData)) - .catch(() => setUser(null)); + fetchUser(); }, []); - const logout = () => { - localStorage.removeItem('token'); + const logout = async () => { + await fetch(`${API_URL}/api/auth/logout`, { + method: 'POST', + credentials: 'include', + }); setUser(null); }; diff --git a/src/lib/contexts/Global.context.tsx b/src/lib/contexts/Global.context.tsx index c903456..3f8b61b 100644 --- a/src/lib/contexts/Global.context.tsx +++ b/src/lib/contexts/Global.context.tsx @@ -1,5 +1,3 @@ -import react from 'react'; -import { authcontextprovider } from './auth.context'; import React from 'react'; import { AuthContextProvider } from './Auth.context'; |
