another step

This commit is contained in:
hamid
2026-06-23 23:36:19 +03:30
parent 3fd147cf80
commit be07c703ec
27 changed files with 3682 additions and 194 deletions
+24
View File
@@ -0,0 +1,24 @@
'use client';
import { createContext, useContext, useReducer } from 'react';
import type { Dispatch, FunctionComponent, PropsWithChildren } from 'react';
import { authReducer } from './authReducer';
import { INITIAL_AUTH_STATE } from './types';
import type { AuthAction, AuthState } from './types';
export type AuthContextValue = [AuthState, Dispatch<AuthAction>];
const AuthContext = createContext<AuthContextValue>([INITIAL_AUTH_STATE, () => null]);
interface AuthProviderProps extends PropsWithChildren {
// Auth state resolved on the server from the request's access-token cookie.
// Seeding the reducer with it means the first client render already reflects
// the real session — no logged-out flash, no post-mount cookie read.
initialState?: AuthState;
}
export const AuthProvider: FunctionComponent<AuthProviderProps> = ({ initialState, children }) => {
const value = useReducer(authReducer, initialState ?? INITIAL_AUTH_STATE);
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};
export const useAuth = (): AuthContextValue => useContext(AuthContext);
+13
View File
@@ -0,0 +1,13 @@
import type { Reducer } from 'react';
import type { AuthAction, AuthState } from './types';
export const authReducer: Reducer<AuthState, AuthAction> = (state, action) => {
switch (action.type) {
case 'LOG_IN':
return { isAuthenticated: true, currentUser: action.user ?? state.currentUser };
case 'LOG_OUT':
return { isAuthenticated: false };
default:
return state;
}
};
+4
View File
@@ -0,0 +1,4 @@
export { AuthProvider, useAuth } from './AuthContext';
export type { AuthContextValue } from './AuthContext';
export { INITIAL_AUTH_STATE } from './types';
export type { AuthAction, AuthState } from './types';
+12
View File
@@ -0,0 +1,12 @@
import type { User } from '@/services/auth/types';
export interface AuthState {
isAuthenticated: boolean;
currentUser?: User;
}
export type AuthAction = { type: 'LOG_IN'; user?: User } | { type: 'LOG_OUT' };
export const INITIAL_AUTH_STATE: AuthState = {
isAuthenticated: false,
};