update login dan password

This commit is contained in:
2024-06-27 14:43:01 +07:00
parent 32a45814b8
commit 4ceaf41a7d
5 changed files with 189 additions and 74 deletions

View File

@@ -1,11 +1,12 @@
import { createContext, ReactNode, useEffect, useReducer } from 'react';
// utils
import axios from '../utils/axios';
import { setSession, getSession } from '../utils/token';
import { setSession, getSession, setUser, getUser, getCookie } from '../utils/token';
// @types
import { ActionMap, AuthState, AuthUser, JWTContextType } from '../@types/auth';
// ----------------------------------------------------------------------
import { Navigate, useLocation } from 'react-router-dom';
enum Types {
Initial = 'INITIALIZE',
@@ -19,7 +20,9 @@ type JWTAuthPayload = {
isAuthenticated: boolean;
user: AuthUser;
};
[Types.Login]: undefined;
[Types.Login]: {
user: AuthUser;
};
[Types.ValidateOtp]: {
user: AuthUser;
};
@@ -45,8 +48,8 @@ const JWTReducer = (state: AuthState, action: JWTActions) => {
case 'LOGIN':
return {
...state,
isAuthenticated: false,
user: null,
isAuthenticated: true,
user: action.payload.user,
};
case 'VALIDATE-OTP':
return {
@@ -75,7 +78,46 @@ type AuthProviderProps = {
function AuthProvider({ children }: AuthProviderProps) {
const [state, dispatch] = useReducer(JWTReducer, initialState);
let location = useLocation();
const accessToken = getSession();
// useEffect(() => {
// (async () => {
// try {
// // const accessToken = getSession();
// if (accessToken) {
// setSession(accessToken);
// const response = await axios.get('/user');
// const user = response.data;
// dispatch({
// type: Types.Initial,
// payload: {
// isAuthenticated: true,
// user,
// },
// });
// } else {
// dispatch({
// type: Types.Initial,
// payload: {
// isAuthenticated: false,
// user: null,
// },
// });
// }
// } catch (err) {
// dispatch({
// type: Types.Initial,
// payload: {
// isAuthenticated: false,
// user: null,
// },
// });
// }
// })();
// }, [accessToken]);
useEffect(() => {
(async () => {
@@ -116,12 +158,28 @@ function AuthProvider({ children }: AuthProviderProps) {
})();
}, [accessToken]);
const login = async (phoneOrEmail: string) =>
const headers = {
headers: {
'Accept': 'application/json',
'Content-Type' : 'application/json',
'Accept-Language': localStorage.getItem('currentLocale') ?? 'id-ID',
},
};
const login = async (phoneOrEmail: string, password: string, remember:boolean) =>
axios
.post('/login', { phoneOrEmail })
.then(() => {
.post('/login', { phoneOrEmail, password }, headers)
.then((response) => {
const { user, token } = response.data.data;
setSession(token);
setUser(user);
dispatch({
type: Types.Login,
payload: {
user,
}
});
})
.catch((error) => {