Auth / Author Flow Hardening and Client Separation #1

Merged
aetos merged 4 commits from jwt into main 2025-12-13 13:15:21 +00:00
3 changed files with 53 additions and 25 deletions
Showing only changes of commit c23145f338 - Show all commits

View File

@@ -1,5 +1,5 @@
import React, { createContext, useState, useEffect, useContext } from 'react';
import { api } from '../utils/api';
import { api, auth } from '../utils/api';
import { AuthorModel } from '../types/models';
import { AuthContextModel } from '../types/contexts';
@@ -18,7 +18,14 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
setLoading(true);
setError(null);
const res = await api.post('/auth/register', { username, password });
const res = await auth.post('/register', { username, password });
// auto-login
// await login(username, password);
// now create author
await api.post('/authors', { name: null, avatar: null });
return res.data;
} catch (err: any) {
console.error('Registration failed:', err);
@@ -34,7 +41,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
setLoading(true);
setError(null);
const res = await api.post('/auth/login', { username, password });
const res = await auth.post('/login', { username, password });
const { access_token, user } = res.data;
if (access_token) {
@@ -99,9 +106,9 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
const fetchCurrentUser = async () => {
if (!token) return;
try {
const me = await api.get<{ _id: string; username: string; email: string }>('/auth/me');
const me = await auth.get('/me');
const author = await api.get<AuthorModel>(`/authors/${me.data._id}`);
const author = await api.get<AuthorModel>(`/authors/me`);
const fullUser = { ...me.data, ...author.data };

View File

@@ -1,8 +1,42 @@
// src/utils/api.ts
import axios from 'axios';
const AUTH_BASE = import.meta.env.VITE_AUTH_BASE_URL;
const API_BASE = import.meta.env.VITE_API_BASE_URL;
//------------------------------------------------------
// COMMON TOKEN ATTACHMENT LOGIC
//------------------------------------------------------
const attachToken = (config: any) => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
};
const handleAuthError = (error: any) => {
if (error.response?.status === 401) {
console.warn('Token expired or invalid. Logging out...');
localStorage.removeItem('token');
// Optional: eventBus, redirect, logout callback
}
return Promise.reject(error);
};
//------------------------------------------------------
// AUTH SERVICE CLIENT
//------------------------------------------------------
export const auth = axios.create({
baseURL: AUTH_BASE,
headers: {
'Content-Type': 'application/json',
},
});
//------------------------------------------------------
// BLOG SERVICE CLIENT
//------------------------------------------------------
export const api = axios.create({
baseURL: API_BASE,
headers: {
@@ -10,24 +44,10 @@ export const api = axios.create({
},
});
// 🔹 Attach token from localStorage before each request
api.interceptors.request.use((config) => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
// Attach token + 401 handling
api.interceptors.request.use(attachToken);
api.interceptors.response.use((res) => res, handleAuthError);
// 🔹 Handle expired or invalid tokens globally
api.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
console.warn('Token expired or invalid. Logging out...');
localStorage.removeItem('token');
// Optionally: trigger a redirect or event
}
return Promise.reject(error);
}
);
// Auth service ALSO needs token for /me, /logout, /introspect
auth.interceptors.request.use(attachToken);
auth.interceptors.response.use((res) => res, handleAuthError);

1
src/vite-env.d.ts vendored
View File

@@ -2,6 +2,7 @@
interface ImportMetaEnv {
readonly VITE_API_BASE_URL: string;
readonly VITE_AUTH_BASE_URL: string;
}
interface ImportMeta {