refactor(auth): separate auth and author responsibilities and centralize auth client creation
- Replace manual axios auth client with createApiClient in auth context - Decouple domain author logic from auth provider - Make AuthorModel extend AuthUser explicitly - Route login/register/logout exclusively through auth package - Derive application-level currentUser from auth identity - Fix provider hierarchy and hook usage across Blog and Profile - Align main.jsx to use base AuthProvider + AuthorProvider layering
This commit is contained in:
@@ -1,7 +1,6 @@
|
||||
import React, { createContext, useContext, useEffect, useState } from "react";
|
||||
import axios from "axios";
|
||||
import { tokenStore } from "./token";
|
||||
import { attachAuthInterceptors } from "./axios";
|
||||
import { createApiClient } from "./axios";
|
||||
import { AuthUser } from "./models";
|
||||
|
||||
interface AuthContextModel {
|
||||
@@ -19,23 +18,16 @@ const AuthContext = createContext<AuthContextModel | undefined>(undefined);
|
||||
export function AuthProvider({
|
||||
children,
|
||||
authBaseUrl,
|
||||
apiClient,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
authBaseUrl: string;
|
||||
apiClient: any; // your domain api client
|
||||
}) {
|
||||
const [currentUser, setCurrentUser] = useState<AuthUser | null>(null);
|
||||
const [token, setToken] = useState<string | null>(tokenStore.get());
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const auth = axios.create({
|
||||
baseURL: authBaseUrl,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
|
||||
attachAuthInterceptors(auth);
|
||||
const auth = createApiClient(authBaseUrl);
|
||||
|
||||
const login = async (username: string, password: string) => {
|
||||
try {
|
||||
@@ -61,7 +53,6 @@ export function AuthProvider({
|
||||
setError(null);
|
||||
|
||||
await auth.post("/register", { username, password });
|
||||
await apiClient.post("/authors", { name: null, avatar: null });
|
||||
} catch (e: any) {
|
||||
setError(e.response?.data?.detail ?? "Registration failed");
|
||||
} finally {
|
||||
@@ -79,8 +70,7 @@ export function AuthProvider({
|
||||
if (!token) return;
|
||||
try {
|
||||
const me = await auth.get("/me");
|
||||
const author = await apiClient.get("/authors/me");
|
||||
setCurrentUser({ ...me.data, ...author.data });
|
||||
setCurrentUser({ ...me.data });
|
||||
} catch {
|
||||
logout();
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
export { AuthProvider, useAuth } from "./context";
|
||||
export { AuthProvider, useAuth } from "./contexts";
|
||||
export { createApiClient } from "./axios";
|
||||
export { AuthPage } from "./AuthPage";
|
||||
export type { AuthUser } from "./models";
|
||||
export type { AuthMode } from "./AuthPage";
|
||||
export { tokenStore } from "./token"
|
||||
|
||||
Reference in New Issue
Block a user