File size: 14,692 Bytes
25f22bf baaf93b 25f22bf baaf93b 25f22bf baaf93b 25f22bf baaf93b 25f22bf baaf93b 25f22bf baaf93b 25f22bf baaf93b 25f22bf baaf93b 25f22bf baaf93b 25f22bf baaf93b 25f22bf baaf93b 25f22bf baaf93b 25f22bf baaf93b 25f22bf baaf93b 25f22bf baaf93b 25f22bf |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 |
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import authService from '../../services/authService';
import cacheService from '../../services/cacheService';
import cookieService from '../../services/cookieService';
// Initial state
const initialState = {
user: null,
isAuthenticated: false,
loading: 'idle', // 'idle' | 'pending' | 'succeeded' | 'failed'
error: null,
security: {
isLocked: false,
failedAttempts: 0,
securityScore: 1.0,
lastSecurityCheck: null
},
cache: {
isRemembered: false,
expiresAt: null,
deviceFingerprint: null
}
};
// Async thunks for cache operations
export const checkCachedAuth = createAsyncThunk(
'auth/checkCachedAuth',
async (_, { rejectWithValue }) => {
try {
const isDevelopment = import.meta.env.VITE_NODE_ENV === 'development';
if (isDevelopment) {
console.log('π [Auth] Starting cached authentication check');
}
// First check cache
const cachedAuth = await cacheService.getAuthCache();
if (cachedAuth) {
if (isDevelopment) {
console.log('ποΈ [Cache] Found cached authentication data');
}
// Validate that the cached token is still valid by checking expiry
if (cachedAuth.expiresAt && Date.now() < cachedAuth.expiresAt) {
return {
success: true,
user: cachedAuth.user,
token: cachedAuth.token,
rememberMe: cachedAuth.rememberMe,
expiresAt: cachedAuth.expiresAt,
deviceFingerprint: cachedAuth.deviceFingerprint
};
} else {
if (isDevelopment) {
console.log('β° [Cache] Cached authentication has expired');
}
// Cache expired, clear it
await cacheService.clearAuthCache();
}
}
// If not in cache or expired, check cookies
if (isDevelopment) {
console.log('πͺ [Cookie] Checking for authentication cookies');
}
const cookieAuth = await cookieService.getAuthTokens();
if (cookieAuth?.accessToken) {
if (isDevelopment) {
console.log('πͺ [Cookie] Found authentication cookies, validating with API');
}
// Validate token and get user data
try {
const response = await authService.getCurrentUser();
if (response.data.success) {
// Store in cache for next time
await cacheService.setAuthCache({
token: cookieAuth.accessToken,
user: response.data.user
}, cookieAuth.rememberMe);
const expiresAt = cookieAuth.rememberMe ?
Date.now() + (7 * 24 * 60 * 60 * 1000) :
Date.now() + (60 * 60 * 1000);
if (isDevelopment) {
console.log('β
[Auth] Cookie authentication validated successfully');
}
return {
success: true,
user: response.data.user,
token: cookieAuth.accessToken,
rememberMe: cookieAuth.rememberMe,
expiresAt: expiresAt,
deviceFingerprint: cookieAuth.deviceFingerprint
};
} else {
if (isDevelopment) {
console.log('β [Auth] Cookie authentication returned unsuccessful response');
}
}
} catch (error) {
if (isDevelopment) {
console.error('π¨ [API] Cookie validation failed:', error);
}
// Token invalid, clear cookies
await cookieService.clearAuthTokens();
}
} else {
if (isDevelopment) {
console.log('πͺ [Cookie] No authentication cookies found');
}
}
if (isDevelopment) {
console.log('π [Auth] No valid cached or cookie authentication found');
}
return { success: false };
} catch (error) {
if (import.meta.env.VITE_NODE_ENV === 'development') {
console.error('π [Auth] Cached authentication check failed:', error);
}
return rejectWithValue('Authentication check failed');
}
}
);
export const autoLogin = createAsyncThunk(
'auth/autoLogin',
async (_, { rejectWithValue }) => {
try {
// Enhanced logging for debugging
const isDevelopment = import.meta.env.VITE_NODE_ENV === 'development';
if (isDevelopment) {
console.log('π [Auth] Starting auto login process');
}
// Try to get token from cookies first, then fallback to localStorage
let token = null;
let rememberMe = false;
try {
const cookieAuth = await cookieService.getAuthTokens();
token = cookieAuth?.accessToken;
rememberMe = cookieAuth?.rememberMe || false;
if (isDevelopment) {
console.log('πͺ [Cookie] Got tokens from cookie service:', { token: !!token, rememberMe });
}
} catch (cookieError) {
if (isDevelopment) {
console.warn('πͺ [Cookie] Error getting cookie tokens, trying localStorage:', cookieError.message);
}
}
// If no cookie token, try localStorage
if (!token) {
token = localStorage.getItem('token');
if (isDevelopment) {
console.log('πΎ [Storage] Got token from localStorage:', !!token);
}
}
if (token) {
try {
// Try to validate token and get user data
if (isDevelopment) {
console.log('π [Token] Validating token with API');
}
const response = await authService.getCurrentUser();
if (response.data.success) {
// Update cache and cookies
await cacheService.setAuthCache({
token: token,
user: response.data.user
}, rememberMe);
// Ensure cookies are set
await cookieService.setAuthTokens(token, rememberMe);
if (isDevelopment) {
console.log('β
[Auth] Auto login successful');
}
return {
success: true,
user: response.data.user,
token: token,
rememberMe
};
} else {
if (isDevelopment) {
console.log('β [Auth] API returned unsuccessful response');
}
}
} catch (apiError) {
if (isDevelopment) {
console.error('π¨ [API] Auto login API call failed:', apiError);
}
}
}
if (isDevelopment) {
console.log('π [Auth] Auto login failed - no valid token found');
}
return { success: false };
} catch (error) {
// Clear tokens on error
localStorage.removeItem('token');
await cookieService.clearAuthTokens();
if (import.meta.env.VITE_NODE_ENV === 'development') {
console.error('π [Auth] Auto login error:', error);
}
return rejectWithValue('Auto login failed');
}
}
);
// Async thunks
export const registerUser = createAsyncThunk(
'auth/register',
async (userData, { rejectWithValue }) => {
try {
const response = await authService.register(userData);
return response.data;
} catch (error) {
return rejectWithValue(error.response.data);
}
}
);
export const loginUser = createAsyncThunk(
'auth/login',
async (credentials, { rejectWithValue }) => {
try {
const response = await authService.login(credentials);
const result = response.data;
if (result.success) {
// Store auth data in cache
const rememberMe = credentials.rememberMe || false;
await cacheService.setAuthCache({
token: result.token,
user: result.user
}, rememberMe);
// Store tokens in secure cookies
await cookieService.setAuthTokens(result.token, rememberMe);
return {
...result,
rememberMe,
expiresAt: rememberMe ? Date.now() + (7 * 24 * 60 * 60 * 1000) : Date.now() + (60 * 60 * 1000)
};
}
return result;
} catch (error) {
return rejectWithValue(error.response?.data || { success: false, message: 'Login failed' });
}
}
);
export const logoutUser = createAsyncThunk(
'auth/logout',
async (_, { rejectWithValue }) => {
try {
// Clear cache first
await cacheService.clearAuthCache();
// Clear cookies
await cookieService.clearAuthTokens();
// Then call logout API
const response = await authService.logout();
return response.data;
} catch (error) {
// Even if API fails, clear cache and cookies
await cacheService.clearAuthCache();
await cookieService.clearAuthTokens();
return { success: true, message: 'Logged out successfully' };
}
}
);
export const getCurrentUser = createAsyncThunk(
'auth/getCurrentUser',
async (_, { rejectWithValue }) => {
try {
const response = await authService.getCurrentUser();
return response.data;
} catch (error) {
return rejectWithValue(error.response.data);
}
}
);
// Auth slice
const authSlice = createSlice({
name: 'auth',
initialState,
reducers: {
clearError: (state) => {
state.error = null;
state.loading = 'idle';
},
setUser: (state, action) => {
state.user = action.payload.user;
state.isAuthenticated = true;
state.loading = 'succeeded';
state.error = null;
},
clearAuth: (state) => {
state.user = null;
state.isAuthenticated = false;
state.loading = 'idle';
state.error = null;
state.security = {
isLocked: false,
failedAttempts: 0,
securityScore: 1.0,
lastSecurityCheck: null
};
state.cache = {
isRemembered: false,
expiresAt: null,
deviceFingerprint: null
};
},
updateSecurityStatus: (state, action) => {
state.security = { ...state.security, ...action.payload };
},
updateCacheInfo: (state, action) => {
state.cache = { ...state.cache, ...action.payload };
},
setRememberMe: (state, action) => {
state.cache.isRemembered = action.payload;
}
},
extraReducers: (builder) => {
// Check cached authentication
builder
.addCase(checkCachedAuth.pending, (state) => {
state.loading = 'pending';
state.error = null;
})
.addCase(checkCachedAuth.fulfilled, (state, action) => {
state.loading = 'succeeded';
if (action.payload.success) {
state.user = action.payload.user;
state.isAuthenticated = true;
state.cache.isRemembered = action.payload.rememberMe || false;
state.cache.expiresAt = action.payload.expiresAt;
state.cache.deviceFingerprint = action.payload.deviceFingerprint;
} else {
state.isAuthenticated = false;
}
})
.addCase(checkCachedAuth.rejected, (state, action) => {
state.loading = 'failed';
state.error = action.payload;
state.isAuthenticated = false;
})
// Auto login
.addCase(autoLogin.pending, (state) => {
state.loading = 'pending';
state.error = null;
})
.addCase(autoLogin.fulfilled, (state, action) => {
state.loading = 'succeeded';
if (action.payload.success) {
state.user = action.payload.user;
state.isAuthenticated = true;
} else {
state.isAuthenticated = false;
}
})
.addCase(autoLogin.rejected, (state, action) => {
state.loading = 'failed';
state.error = action.payload;
state.isAuthenticated = false;
})
// Register user (existing)
.addCase(registerUser.pending, (state) => {
state.loading = 'pending';
state.error = null;
})
.addCase(registerUser.fulfilled, (state, action) => {
state.loading = 'succeeded';
state.user = action.payload.user;
state.isAuthenticated = true;
})
.addCase(registerUser.rejected, (state, action) => {
state.loading = 'failed';
state.error = action.payload?.message || 'Registration failed';
})
// Login user (enhanced)
.addCase(loginUser.pending, (state) => {
state.loading = 'pending';
state.error = null;
})
.addCase(loginUser.fulfilled, (state, action) => {
state.loading = 'succeeded';
state.user = action.payload.user;
state.isAuthenticated = true;
state.cache.isRemembered = action.payload.rememberMe || false;
state.cache.expiresAt = action.payload.expiresAt;
// Store token securely
localStorage.setItem('token', action.payload.token);
})
.addCase(loginUser.rejected, (state, action) => {
state.loading = 'failed';
state.error = action.payload?.message || 'Login failed';
state.security.failedAttempts += 1;
})
// Logout user (enhanced)
.addCase(logoutUser.fulfilled, (state) => {
state.user = null;
state.isAuthenticated = false;
state.loading = 'idle';
state.cache.isRemembered = false;
state.cache.expiresAt = null;
state.cache.deviceFingerprint = null;
// Clear all cached data (already done in the thunk)
localStorage.removeItem('token');
})
.addCase(logoutUser.rejected, (state) => {
state.user = null;
state.isAuthenticated = false;
state.loading = 'idle';
state.cache.isRemembered = false;
state.cache.expiresAt = null;
state.cache.deviceFingerprint = null;
localStorage.removeItem('token');
})
// Get current user (existing)
.addCase(getCurrentUser.pending, (state) => {
state.loading = 'pending';
})
.addCase(getCurrentUser.fulfilled, (state, action) => {
state.loading = 'succeeded';
state.user = action.payload.user;
state.isAuthenticated = true;
})
.addCase(getCurrentUser.rejected, (state) => {
state.loading = 'failed';
state.user = null;
state.isAuthenticated = false;
});
}
});
export const {
clearError,
setUser,
clearAuth,
updateSecurityStatus,
updateCacheInfo,
setRememberMe
} = authSlice.actions;
export default authSlice.reducer; |