Files
Wisecolt-CI/frontend/src/providers/auth-provider.tsx
wisecolt 535b5cbdc2 fix(auth): kimlik doğrulama hatasında durumu temizle
Kullanıcı verisi getirme başarısız olduğunda artık tüm kimlik doğrulama
durumunu (token, kullanıcı bilgileri) temizler, böylece eski oturum
bilgileri kalıcı olmaz.
2026-01-26 15:34:12 +00:00

63 lines
1.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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);
setToken(null);
setUser(null);
})
.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;
}