103 lines
2.6 KiB
TypeScript
103 lines
2.6 KiB
TypeScript
/*
|
|
* File: authSlice.ts
|
|
* Description: Redux slice for Auth state management
|
|
* Design & Developed by Tech4Biz Solutions
|
|
* Copyright (c) Spurrin Innovations. All rights reserved.
|
|
*/
|
|
|
|
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
|
|
import { User, NotificationPreferences, DashboardSettings } from '../../../shared/types/auth';
|
|
import { login } from './authActions';
|
|
|
|
// Use User type from shared types as UserProfile
|
|
type UserProfile = User;
|
|
|
|
// Auth state type
|
|
interface AuthState {
|
|
user: UserProfile | null;
|
|
loading: boolean;
|
|
error: string | null;
|
|
isAuthenticated: boolean;
|
|
}
|
|
|
|
const initialState: AuthState = {
|
|
user: null,
|
|
loading: false,
|
|
error: null,
|
|
isAuthenticated: false,
|
|
};
|
|
|
|
/**
|
|
* Auth slice for managing authentication state
|
|
*/
|
|
const authSlice = createSlice({
|
|
name: 'auth',
|
|
initialState,
|
|
reducers: {
|
|
logout(state) {
|
|
state.user = null;
|
|
state.isAuthenticated = false;
|
|
state.loading = false;
|
|
state.error = null;
|
|
},
|
|
updateOnboarded(state, action: PayloadAction<boolean>) {
|
|
if (state.user) {
|
|
state.user.onboarded = action.payload;
|
|
}
|
|
},
|
|
updateUserProfile(state, action: PayloadAction<Partial<UserProfile>>) {
|
|
if (state.user) {
|
|
state.user = { ...state.user, ...action.payload };
|
|
}
|
|
},
|
|
updateNotificationPreferences(state, action: PayloadAction<NotificationPreferences>) {
|
|
if (state.user) {
|
|
state.user.notification_preferences = action.payload;
|
|
}
|
|
},
|
|
updateDashboardSettings(state, action: PayloadAction<DashboardSettings>) {
|
|
if (state.user) {
|
|
state.user.dashboard_settings = action.payload;
|
|
}
|
|
},
|
|
clearError(state) {
|
|
state.error = null;
|
|
}
|
|
},
|
|
extraReducers: (builder) => {
|
|
// Login thunk cases
|
|
builder
|
|
.addCase(login.pending, (state) => {
|
|
state.loading = true;
|
|
state.error = null;
|
|
})
|
|
.addCase(login.fulfilled, (state, action) => {
|
|
state.loading = false;
|
|
state.user = action.payload as UserProfile;
|
|
state.isAuthenticated = true;
|
|
state.error = null;
|
|
})
|
|
.addCase(login.rejected, (state, action) => {
|
|
state.loading = false;
|
|
state.error = action.payload as string || 'Login failed';
|
|
state.isAuthenticated = false;
|
|
});
|
|
},
|
|
});
|
|
|
|
export const {
|
|
logout,
|
|
updateOnboarded,
|
|
updateUserProfile,
|
|
updateNotificationPreferences,
|
|
updateDashboardSettings,
|
|
clearError
|
|
} = authSlice.actions;
|
|
|
|
export default authSlice.reducer;
|
|
|
|
/*
|
|
* End of File: authSlice.ts
|
|
* Design & Developed by Tech4Biz Solutions
|
|
* Copyright (c) Spurrin Innovations. All rights reserved.
|
|
*/
|