auth validation
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
|
||||
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
|
||||
import axios from '../../axios';
|
||||
|
||||
type Status = 'idle' | 'loading' | 'successful' | 'failed';
|
||||
|
||||
// 🔹 Декодирование JWT
|
||||
function decodeJwt(token: string) {
|
||||
const [, payload] = token.split('.');
|
||||
@@ -15,8 +17,12 @@ interface AuthState {
|
||||
username: string | null;
|
||||
email: string | null;
|
||||
id: string | null;
|
||||
status: 'idle' | 'loading' | 'successful' | 'failed';
|
||||
status: Status;
|
||||
error: string | null;
|
||||
register: {
|
||||
errors?: Record<string, string[]>;
|
||||
status: Status;
|
||||
};
|
||||
}
|
||||
|
||||
// 🔹 Инициализация состояния с синхронной загрузкой из localStorage
|
||||
@@ -31,6 +37,9 @@ const initialState: AuthState = {
|
||||
id: null,
|
||||
status: 'idle',
|
||||
error: null,
|
||||
register: {
|
||||
status: 'idle',
|
||||
},
|
||||
};
|
||||
|
||||
// Если токен есть, подставляем в axios и декодируем
|
||||
@@ -76,9 +85,7 @@ export const registerUser = createAsyncThunk(
|
||||
});
|
||||
return response.data;
|
||||
} catch (err: any) {
|
||||
return rejectWithValue(
|
||||
err.response?.data?.message || 'Registration failed',
|
||||
);
|
||||
return rejectWithValue(err.response?.data?.errors);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -165,6 +172,15 @@ const authSlice = createSlice({
|
||||
localStorage.removeItem('refreshToken');
|
||||
delete axios.defaults.headers.common['Authorization'];
|
||||
},
|
||||
setAuthStatus: (
|
||||
state,
|
||||
action: PayloadAction<{ key: keyof AuthState; status: Status }>,
|
||||
) => {
|
||||
const { key, status } = action.payload;
|
||||
if (state[key]) {
|
||||
(state[key] as any).status = status;
|
||||
}
|
||||
},
|
||||
},
|
||||
extraReducers: (builder) => {
|
||||
// ----------------- Register -----------------
|
||||
@@ -199,7 +215,7 @@ const authSlice = createSlice({
|
||||
});
|
||||
builder.addCase(registerUser.rejected, (state, action) => {
|
||||
state.status = 'failed';
|
||||
state.error = action.payload as string;
|
||||
state.register.errors = action.payload as Record<string, string[]>;
|
||||
});
|
||||
|
||||
// ----------------- Login -----------------
|
||||
@@ -304,5 +320,5 @@ const authSlice = createSlice({
|
||||
},
|
||||
});
|
||||
|
||||
export const { logout } = authSlice.actions;
|
||||
export const { logout, setAuthStatus } = authSlice.actions;
|
||||
export const authReducer = authSlice.reducer;
|
||||
|
||||
Reference in New Issue
Block a user