first commit

This commit is contained in:
2025-11-26 18:57:18 +03:00
commit 16c21a4e49
41 changed files with 1075 additions and 0 deletions

View File

@@ -0,0 +1,58 @@
import React, { createContext, useContext, useEffect, useMemo, useState } from "react";
import { fetchMe, loginRequest, setAuthToken } from "../api/client";
interface AuthContextProps {
user: { username: string } | null;
token: string | null;
login: (username: string, password: string) => Promise<void>;
logout: () => void;
loading: boolean;
}
const AuthContext = createContext<AuthContextProps | undefined>(undefined);
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [user, setUser] = useState<{ username: string } | null>(null);
const [token, setToken] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const stored = localStorage.getItem("token");
if (stored) {
setAuthToken(stored);
setToken(stored);
fetchMe()
.then((data) => setUser({ username: data.username }))
.catch(() => setAuthToken(undefined))
.finally(() => setLoading(false));
} else {
setLoading(false);
}
}, []);
const login = async (username: string, password: string) => {
const { token: newToken, username: returnedUsername } = await loginRequest(username, password);
setAuthToken(newToken);
setToken(newToken);
setUser({ username: returnedUsername });
};
const logout = () => {
setAuthToken(undefined);
setToken(null);
setUser(null);
};
const value = useMemo(
() => ({ user, token, login, logout, loading }),
[user, token, loading]
);
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};
export function useAuth() {
const ctx = useContext(AuthContext);
if (!ctx) throw new Error("useAuth AuthProvider içinde kullanılmalı");
return ctx;
}