-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathAppContextProvider.tsx
154 lines (134 loc) · 4.51 KB
/
AppContextProvider.tsx
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
"use client";
import 'react-toastify/dist/ReactToastify.css';
import { useTranslations } from 'next-intl';
import {
createContext,
useState,
SetStateAction,
ReactNode,
useEffect
} from 'react';
import axiosClient, {setAuthToken} from '@/config/client';
import { onIncompletePaymentFound } from '@/utils/auth';
import { AuthResult } from '@/constants/pi';
import { IUser } from '@/constants/types';
import logger from '../logger.config.mjs';
interface IAppContextProps {
currentUser: IUser | null;
setCurrentUser: React.Dispatch<SetStateAction<IUser | null>>;
registerUser: () => void;
autoLoginUser: ()=> void;
isSigningInUser: boolean;
reload: boolean;
alertMessage: string | null;
setAlertMessage: React.Dispatch<SetStateAction<string | null>>;
showAlert: (message: string) => void;
setReload: React.Dispatch<SetStateAction<boolean>>;
isSaveLoading: boolean;
setIsSaveLoading: React.Dispatch<SetStateAction<boolean>>;
}
const initialState: IAppContextProps = {
currentUser: null,
setCurrentUser: () => {},
registerUser: () => { },
autoLoginUser: ()=> {},
isSigningInUser: false,
reload: false,
alertMessage: null,
setAlertMessage: () => {},
showAlert: () => {},
setReload: () => {},
isSaveLoading: false,
setIsSaveLoading: () => {}
};
export const AppContext = createContext<IAppContextProps>(initialState);
interface AppContextProviderProps {
children: ReactNode;
}
const AppContextProvider = ({ children }: AppContextProviderProps) => {
const t = useTranslations();
const [currentUser, setCurrentUser] = useState<IUser | null>(null);
const [isSigningInUser,setIsSigningInUser] = useState(false);
const [reload, setReload] = useState(false);
const [isSaveLoading, setIsSaveLoading] = useState(false);
const [alertMessage, setAlertMessage] = useState<string | null>(null);
const showAlert = (message: string) => {
setAlertMessage(message);
setTimeout(() => {
setAlertMessage(null); // Clear alert after 5 seconds
}, 5000);
};
const registerUser = async () => {
logger.info('Initializing Pi SDK for user registration.');
await Pi.init({ version: '2.0', sandbox: process.env.NODE_ENV === 'development' });
let isInitiated = Pi.initialized;
logger.info(`Pi SDK initialized: ${isInitiated}`);
if (isInitiated) {
try {
setIsSigningInUser(true)
const pioneerAuth: AuthResult = await window.Pi.authenticate(['username', 'payments'], onIncompletePaymentFound);
const res = await axiosClient.post(
"/users/authenticate",
{}, // empty body
{
headers: {
Authorization: `Bearer ${pioneerAuth.accessToken}`,
},
}
);
if (res.status === 200) {
setAuthToken(res.data?.token)
setCurrentUser(res.data.user);
logger.info('User authenticated successfully.');
setTimeout(() => {
setIsSigningInUser(false); // hide the splash screen after the delay
}, 2500);
} else if (res.status === 500) {
setCurrentUser(null);
logger.error('User authentication failed.');
setIsSigningInUser(false)
}
} catch (error) {
logger.error('Error during user registration:', error);
setIsSigningInUser(false)
}
} else {
logger.error('PI SDK failed to initialize.');
}
};
const autoLoginUser = async () => {
logger.info('Attempting to auto-login user.');
try {
setIsSigningInUser(true)
const res = await axiosClient.get('/users/me');
if (res.status === 200) {
logger.info('Auto-login successful.');
setCurrentUser(res.data);
setTimeout(() => {
setIsSigningInUser(false); // hide the splash screen after the delay
}, 2500);
} else {
setCurrentUser(null);
logger.warn('Auto-login failed.');
setIsSigningInUser(false)
}
} catch (error) {
logger.error('Auto login unresolved; attempting Pi SDK authentication:', error);
await registerUser();
}
}
useEffect(() => {
logger.info('AppContextProvider mounted.');
if (!currentUser) {
registerUser();
} else {
autoLoginUser();
}
}, []);
return (
<AppContext.Provider value={{ currentUser, setCurrentUser, registerUser, autoLoginUser, isSigningInUser, reload, setReload, showAlert, alertMessage, setAlertMessage, isSaveLoading, setIsSaveLoading }}>
{children}
</AppContext.Provider>
);
};
export default AppContextProvider;