feat(auth): separate auth and blog API clients and integrate author auto-creation

## Summary
Refactored the authentication flow to correctly separate traffic between the
Auth service and Blog service. Added post-registration author creation and
switched all `/auth/*` calls to the dedicated `auth` Axios client.

## Changes
### AuthProvider
- Replaced `api.post('/auth/register')` with `auth.post('/register')`
- Replaced `api.post('/auth/login')` with `auth.post('/login')`
- Added automatic author creation after user registration (`POST /authors`)
- Switched user identity lookup from `api.get('/auth/me')` to `auth.get('/me')`
- Replaced `/authors/{id}` lookup with `/authors/me`
- Updated imports to use `{ api, auth }`

### Axios Client Layer
- Introduced a new `auth` Axios instance using `VITE_AUTH_BASE_URL`
- Added shared token attachment and 401 handling logic
- Applied interceptors to both `auth` and `api` clients
- Removed inline auth logic from `api.ts`

### Types
- Added `VITE_AUTH_BASE_URL` to `vite-env.d.ts`

## Impact
- Correctly routes authentication traffic to the Auth microservice
- Ensures an Author document is created automatically after registration
- Simplifies identity loading via `/authors/me`
- Improves token handling consistency across both services
This commit is contained in:
2025-12-11 21:00:13 +05:30
parent a7987ab922
commit c23145f338
3 changed files with 53 additions and 25 deletions

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 };