Auth Package Extraction And Auth Flow Refactor (#2)
Reviewed-on: #2 Co-authored-by: Vishesh 'ironeagle' Bangotra <aetoskia@gmail.com> Co-committed-by: Vishesh 'ironeagle' Bangotra <aetoskia@gmail.com>
This commit is contained in:
@@ -1,70 +1,50 @@
|
||||
import React, { createContext, useState, useEffect, useContext } from 'react';
|
||||
import { api, auth } from '../utils/api';
|
||||
import { AuthorModel } from '../types/models';
|
||||
import { AuthContextModel } from '../types/contexts';
|
||||
import React, { createContext, useState, useEffect, useContext } from "react";
|
||||
import { api } from "../utils/api";
|
||||
import { AuthorModel } from "../types/models";
|
||||
import { AuthContextModel } from "../types/contexts";
|
||||
import { useAuth as useBaseAuth } from "../../../auth/src";
|
||||
|
||||
const AuthContext = createContext<AuthContextModel | undefined>(undefined);
|
||||
|
||||
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||
const { currentUser: authUser, logout } = useBaseAuth();
|
||||
const [currentUser, setCurrentUser] = useState<AuthorModel | null>(null);
|
||||
const [authors, setAuthors] = useState<AuthorModel[]>([]);
|
||||
const [token, setToken] = useState<string | null>(localStorage.getItem('token'));
|
||||
const [loading, setLoading] = useState<boolean>(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
/** 🔹 Register new user */
|
||||
const register = async (username: string, password: string) => {
|
||||
/**
|
||||
* Hydrate application-level currentUser
|
||||
*/
|
||||
const hydrateCurrentUser = async () => {
|
||||
if (!authUser) return;
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const res = await auth.post('/register', { username, password });
|
||||
const res = await api.get<AuthorModel>("/authors/me");
|
||||
|
||||
// auto-login
|
||||
// await login(username, password);
|
||||
/**
|
||||
* Explicit precedence:
|
||||
* Auth service is source of truth for inherited fields
|
||||
*/
|
||||
const fullUser: AuthorModel = {
|
||||
...res.data,
|
||||
username: authUser.username,
|
||||
email: authUser.email,
|
||||
is_active: authUser.is_active,
|
||||
};
|
||||
|
||||
// now create author
|
||||
await api.post('/authors', { name: null, avatar: null });
|
||||
|
||||
return res.data;
|
||||
} catch (err: any) {
|
||||
console.error('Registration failed:', err);
|
||||
setError(err.response?.data?.detail || 'Registration failed');
|
||||
setCurrentUser(fullUser);
|
||||
} catch (err) {
|
||||
console.error("Failed to hydrate current user:", err);
|
||||
logout();
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
/** 🔹 Login and store JWT token */
|
||||
const login = async (username: string, password: string) => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const res = await auth.post('/login', { username, password });
|
||||
const { access_token, user } = res.data;
|
||||
|
||||
if (access_token) {
|
||||
localStorage.setItem('token', access_token);
|
||||
setToken(access_token);
|
||||
setCurrentUser(user);
|
||||
}
|
||||
} catch (err: any) {
|
||||
console.error('Login failed:', err);
|
||||
setError(err.response?.data?.detail || 'Invalid credentials');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
/** 🔹 Logout and clear everything */
|
||||
const logout = () => {
|
||||
localStorage.removeItem('token');
|
||||
setToken(null);
|
||||
setCurrentUser(null);
|
||||
setAuthors([]);
|
||||
};
|
||||
|
||||
/** 🔹 Fetch all authors (JWT handled by api interceptor) */
|
||||
const refreshAuthors = async () => {
|
||||
try {
|
||||
@@ -102,39 +82,27 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
|
||||
}
|
||||
};
|
||||
|
||||
/** 🔹 Auto-load current user if token exists */
|
||||
const fetchCurrentUser = async () => {
|
||||
if (!token) return;
|
||||
try {
|
||||
const me = await auth.get('/me');
|
||||
|
||||
const author = await api.get<AuthorModel>(`/authors/me`);
|
||||
|
||||
const fullUser = { ...me.data, ...author.data };
|
||||
|
||||
setCurrentUser(fullUser);
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch current user:', err);
|
||||
logout();
|
||||
}
|
||||
};
|
||||
|
||||
/** 🔹 On mount, try to fetch user if token exists */
|
||||
/**
|
||||
* React strictly to auth lifecycle
|
||||
*/
|
||||
useEffect(() => {
|
||||
if (token) fetchCurrentUser();
|
||||
}, [token]);
|
||||
if (authUser) {
|
||||
hydrateCurrentUser();
|
||||
} else {
|
||||
setCurrentUser(null);
|
||||
setAuthors([]);
|
||||
setError(null);
|
||||
}
|
||||
}, [authUser]);
|
||||
|
||||
return (
|
||||
<AuthContext.Provider
|
||||
value={{
|
||||
currentUser,
|
||||
authors,
|
||||
token,
|
||||
loading,
|
||||
error,
|
||||
login,
|
||||
logout,
|
||||
register,
|
||||
|
||||
refreshAuthors,
|
||||
updateProfile,
|
||||
}}
|
||||
|
||||
Reference in New Issue
Block a user