This commit is contained in:
wayanrivan
2026-07-02 15:20:41 +07:00
parent 8ca596af86
commit ea1a678a25
6 changed files with 171 additions and 101 deletions

View File

@ -8,6 +8,8 @@ const RequireAuth = () => {
const { auth, loading } = useAuthContext(); const { auth, loading } = useAuthContext();
const location = useLocation(); const location = useLocation();
// console.log('RequireAuth render: loading =', loading, ' auth =', auth);
if (loading) { if (loading) {
return <ScreenLoader />; return <ScreenLoader />;
} }

View File

@ -41,9 +41,9 @@ export function setupAxios(axios: any) {
(config: { headers: { Authorization: string }; params?: any; url?: any; httpsAgent: any }) => { (config: { headers: { Authorization: string }; params?: any; url?: any; httpsAgent: any }) => {
const auth = getAuth(); const auth = getAuth();
if (auth?.access_token) { // if (auth?.access_token) {
config.headers.Authorization = `Bearer ${auth.access_token}`; // config.headers.Authorization = `Bearer ${auth.access_token}`;
} // }
return config; return config;
}, },
async (err: any) => await Promise.reject(err) async (err: any) => await Promise.reject(err)

View File

@ -2,14 +2,21 @@ import { type TLanguageCode } from '@/i18n';
export interface AuthModel { export interface AuthModel {
id: string; id: string;
access_token: string; // access_token: string;
refresh_token: string; // refresh_token: string;
role_name: string; role_name: string;
roles_list: []; // roles_list: [];
company: any; // company: any;
user: any; // user: any;
// api_token: string; // // api_token: string;
statusbalance: string; // statusbalance: string;
username?: string;
password?: string;
user?: UserModel;
statusbalance?: string;
access_token?: string;
token_type?: string;
// language?: TLanguageCode;
} }
export interface UserModel { export interface UserModel {
@ -18,18 +25,21 @@ export interface UserModel {
name: string; name: string;
password: string | undefined; password: string | undefined;
email: string; email: string;
id_role: string; customer?: {
id: string;
};
// id_role: string;
role_name: string; role_name: string;
roles_list: []; // roles_list: [];
token: AuthModel; // token: AuthModel;
first_name: string; // first_name: string;
last_name: string; // last_name: string;
fullname?: string; // fullname?: string;
occupation?: string; // occupation?: string;
companyName?: string; // companyName?: string;
phone?: string; // phone?: string;
roles?: number[]; // roles?: number[];
pic?: string; // pic?: string;
language?: TLanguageCode; // language?: TLanguageCode;
} }

View File

@ -1,84 +1,81 @@
import { type MouseEvent, useState } from 'react'; import { type MouseEvent, useState } from 'react';
import { Link, useLocation, useNavigate } from 'react-router-dom'; import { useLocation, useNavigate } from 'react-router-dom';
import clsx from 'clsx'; import clsx from 'clsx';
import * as Yup from 'yup'; import * as Yup from 'yup';
import { useFormik } from 'formik'; import { useFormik } from 'formik';
import { KeenIcon } from '@/components'; import { KeenIcon } from '@/components';
import { toAbsoluteUrl } from '@/utils';
import { useAuthContext } from '@/auth';
import { useLayout } from '@/providers';
import { Alert } from '@/components'; import { Alert } from '@/components';
import { useAuthContext } from '@/auth';
import moment from 'moment'; import moment from 'moment';
import { Helmet } from 'react-helmet'; import { Helmet } from 'react-helmet';
// ---------------------------------------------------------------------------
// Hardcoded credentials (no API call). The actual session (auth/currentUser)
// is still set through AuthContext's login(), which — while its provider is
// in DUMMY_MODE — stores a local dummy session instead of hitting the API.
// ---------------------------------------------------------------------------
const HARDCODED_USERNAME = 'admin';
const HARDCODED_PASSWORD = 'admin';
const loginSchema = Yup.object().shape({ const loginSchema = Yup.object().shape({
username: Yup.string().required('Username is required'), username: Yup.string().required('Username is required'),
password: Yup.string() password: Yup.string()
.min(3, 'Minimum 3 symbols') .min(3, 'Minimum 3 symbols')
.max(50, 'Maximum 50 symbols') .max(50, 'Maximum 50 symbols')
.required('Password is required'), .required('Password is required')
token: Yup.string(),
// .max(3, 'Maximum 6 code'),
// .required('Token is required'),
remember: Yup.boolean()
}); });
// const initialValues = { const initialValues = {
// username: '', username: '',
// password: '', password: ''
// token: '', };
// remember: false
// };
const Login = () => { const Login = () => {
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const { login } = useAuthContext(); const { login } = useAuthContext();
const navigate = useNavigate(); const navigate = useNavigate();
const location = useLocation(); const location = useLocation();
const from = location.state?.from?.pathname || '/'; const from = (location.state as any)?.from?.pathname || '/';
const [showPassword, setShowPassword] = useState(false); const [showPassword, setShowPassword] = useState(false);
const { currentLayout } = useLayout();
// const formik = useFormik({ const formik = useFormik({
// initialValues, initialValues,
// validationSchema: loginSchema, validationSchema: loginSchema,
// onSubmit: async (values, { setStatus, setSubmitting }) => { onSubmit: async (values, { setStatus, setSubmitting }) => {
// setLoading(true); setLoading(true);
setStatus(undefined);
// try { if (values.username !== HARDCODED_USERNAME || values.password !== HARDCODED_PASSWORD) {
// if (!login) throw new Error('JWTProvider is required for this form.'); setStatus('Incorrect username or password. Please try again.');
// await login(values.username, values.password, values.token); setSubmitting(false);
setLoading(false);
return;
}
// if (values.remember) { try {
// localStorage.setItem('username', values.username); if (!login) throw new Error('AuthProvider is required for this form.');
// } else { await login(values.username, values.password);
// localStorage.removeItem('username'); navigate(from, { replace: true });
// } } catch (error) {
console.error('Login error:', error);
setStatus('Something went wrong while signing in. Please try again.');
setSubmitting(false);
}
// navigate(from, { replace: true }); setLoading(false);
// } catch (error: any) { }
// if (error.response && error.response.data) { });
// setStatus(error.response.data.message);
// } else {
// setStatus('The login details are incorrect');
// }
// setSubmitting(false); const togglePassword = (event: MouseEvent<HTMLButtonElement>) => {
// } event.preventDefault();
// setLoading(false); setShowPassword(!showPassword);
// } };
// });
// const togglePassword = (event: MouseEvent<HTMLButtonElement>) => { const handleKeyPress = (e: { key: string }) => {
// event.preventDefault(); if (e.key === 'Enter') {
// setShowPassword(!showPassword); formik.handleSubmit();
// }; }
};
// const handleKeyPress = (e: { key: string }) => {
// if (e.key === 'Enter') {
// formik.handleSubmit();
// }
// };
return ( return (
<> <>
@ -86,33 +83,29 @@ const Login = () => {
<title>REVENUE | Sign In</title> <title>REVENUE | Sign In</title>
</Helmet> </Helmet>
<div className="card max-w-[390px] w-full"> <div className="card max-w-[390px] w-full">
<form <form className="card-body flex flex-col gap-5 p-10" onSubmit={formik.handleSubmit} noValidate>
className="card-body flex flex-col gap-5 p-10"
// onSubmit={formik.handleSubmit}
noValidate
>
<div className="text-center"> <div className="text-center">
<h3 className="text-lg font-semibold text-gray-900 leading-none ">Sign in</h3> <h3 className="text-lg font-semibold text-gray-900 leading-none ">Sign in</h3>
</div> </div>
{/* {formik.status && <Alert variant="danger">{formik.status}</Alert>} */} {formik.status && <Alert variant="danger">{formik.status}</Alert>}
<div className="flex flex-col gap-1"> <div className="flex flex-col gap-1">
<label className="form-label text-gray-900 ps-2.5">Login</label> <label className="form-label text-gray-900 ps-2.5">Login</label>
<label className="input"> <label className="input">
<input <input
placeholder="Enter username" placeholder="Enter username"
autoComplete="off" autoComplete="off"
// {...formik.getFieldProps('username')} {...formik.getFieldProps('username')}
className={clsx('form-control', { className={clsx('form-control', {
// 'is-invalid': formik.touched.username && formik.errors.username 'is-invalid': formik.touched.username && formik.errors.username
})} })}
// onKeyPress={handleKeyPress} onKeyPress={handleKeyPress}
/> />
</label> </label>
{/* {formik.touched.username && formik.errors.username && ( {formik.touched.username && formik.errors.username && (
<span role="alert" className="text-danger text-xs mt-1"> <span role="alert" className="text-danger text-xs mt-1">
{formik.errors.username} {formik.errors.username}
</span> </span>
)} */} )}
</div> </div>
<div className="flex flex-col gap-1"> <div className="flex flex-col gap-1">
@ -124,15 +117,13 @@ const Login = () => {
type={showPassword ? 'text' : 'password'} type={showPassword ? 'text' : 'password'}
placeholder="Enter Password" placeholder="Enter Password"
autoComplete="off" autoComplete="off"
// {...formik.getFieldProps('password')} {...formik.getFieldProps('password')}
// className={clsx('form-control', { className={clsx('form-control', {
// 'is-invalid': formik.touched.password && formik.errors.password 'is-invalid': formik.touched.password && formik.errors.password
// })} })}
// onKeyPress={handleKeyPress} onKeyPress={handleKeyPress}
/> />
<button className="btn btn-icon" <button className="btn btn-icon" onClick={togglePassword} type="button">
// onClick={togglePassword}
type="button">
<KeenIcon icon="eye" className={clsx('text-gray-500', { hidden: showPassword })} /> <KeenIcon icon="eye" className={clsx('text-gray-500', { hidden: showPassword })} />
<KeenIcon <KeenIcon
icon="eye-slash" icon="eye-slash"
@ -140,16 +131,16 @@ const Login = () => {
/> />
</button> </button>
</label> </label>
{/* {formik.touched.password && formik.errors.password && ( {formik.touched.password && formik.errors.password && (
<span role="alert" className="text-danger text-xs mt-1"> <span role="alert" className="text-danger text-xs mt-1">
{formik.errors.password} {formik.errors.password}
</span> </span>
)} */} )}
</div> </div>
<button <button
type="submit" type="submit"
className="btn btn-primary flex justify-center grow" className="btn btn-primary flex justify-center grow"
// disabled={loading || formik.isSubmitting} disabled={loading || formik.isSubmitting}
> >
{loading ? 'Please wait...' : 'Sign In'} {loading ? 'Please wait...' : 'Sign In'}
</button> </button>

View File

@ -21,6 +21,34 @@ export const FORGOT_PASSWORD_URL = `${API_URL}/reset_password`;
export const RESET_PASSWORD_URL = `${API_URL}/update_password`; export const RESET_PASSWORD_URL = `${API_URL}/update_password`;
export const GET_USER_URL = `${API_URL}/user/detail`; export const GET_USER_URL = `${API_URL}/user/detail`;
// ---------------------------------------------------------------------------
// DUMMY MODE — set to `false` to restore the real API-backed auth flow.
// While `true`, every method below skips its axios call and works off a
// local, hardcoded session instead. This keeps the rest of the app (route
// guards, `getAuth()`, etc.) working without a live backend.
// ---------------------------------------------------------------------------
const DUMMY_MODE = true;
const DUMMY_USER: UserModel = {
id: 1,
name: 'Administrator',
username: 'admin',
email: 'admin@example.com',
password: undefined,
customer: { id: 'dummy-customer-id' },
role_name: 'Admin'
};
const DUMMY_AUTH: AuthModel = {
id: 'dummy-user-id',
username: 'admin',
role_name: 'Admin',
user: DUMMY_USER,
statusbalance: 'Y',
access_token: 'dummy-token',
token_type: 'Bearer'
};
interface AuthContextProps { interface AuthContextProps {
loading: boolean; loading: boolean;
setLoading: Dispatch<SetStateAction<boolean>>; setLoading: Dispatch<SetStateAction<boolean>>;
@ -53,6 +81,13 @@ const AuthProvider = ({ children }: PropsWithChildren) => {
}; };
const login = async (username: string, password: string, token?: string) => { const login = async (username: string, password: string, token?: string) => {
if (DUMMY_MODE) {
// No API call — just persist a local dummy session.
saveAuth(DUMMY_AUTH);
setCurrentUser(DUMMY_USER);
return;
}
try { try {
const { data: auth } = await axios const { data: auth } = await axios
.post(LOGIN_URL, { username, password, token }) .post(LOGIN_URL, { username, password, token })
@ -82,10 +117,18 @@ const AuthProvider = ({ children }: PropsWithChildren) => {
}; };
const requestPasswordResetLink = async (email: string) => { const requestPasswordResetLink = async (email: string) => {
if (DUMMY_MODE) {
console.warn('[AuthProvider] DUMMY_MODE: requestPasswordResetLink skipped (no API call).');
return;
}
await axios.put(FORGOT_PASSWORD_URL + '/' + email); await axios.put(FORGOT_PASSWORD_URL + '/' + email);
}; };
const changePassword = async (token: string, password: string, retype_password: string) => { const changePassword = async (token: string, password: string, retype_password: string) => {
if (DUMMY_MODE) {
console.warn('[AuthProvider] DUMMY_MODE: changePassword skipped (no API call).');
return;
}
await axios.put(`${RESET_PASSWORD_URL}/${token}`, { await axios.put(`${RESET_PASSWORD_URL}/${token}`, {
password, password,
retype_password retype_password
@ -93,6 +136,10 @@ const AuthProvider = ({ children }: PropsWithChildren) => {
}; };
const getUser = async () => { const getUser = async () => {
if (DUMMY_MODE) {
return { data: DUMMY_USER };
}
let _axios = await axios let _axios = await axios
.get(`${GET_USER_URL}/${authHelper.getAuth()?.id}`) .get(`${GET_USER_URL}/${authHelper.getAuth()?.id}`)
.then((response) => response.data.data); .then((response) => response.data.data);
@ -101,6 +148,13 @@ const AuthProvider = ({ children }: PropsWithChildren) => {
}; };
const verify = async () => { const verify = async () => {
if (DUMMY_MODE) {
// Keep whatever session is already in memory/local storage as-is;
// no API round-trip to re-validate it.
setLoading(false);
return;
}
if (auth) { if (auth) {
try { try {
const { data: user } = await getUser(); const { data: user } = await getUser();
@ -127,7 +181,20 @@ const AuthProvider = ({ children }: PropsWithChildren) => {
} }
}; };
// Ensures `loading` always resolves, even if no external wrapper calls
// verify() on app start. Safe to call twice if such a wrapper does exist.
useEffect(() => {
verify();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const logout = async () => { const logout = async () => {
if (DUMMY_MODE) {
saveAuth(undefined);
setCurrentUser(undefined);
return;
}
const createActivity = { const createActivity = {
module: 'Logout', module: 'Logout',
description: `Logout`, description: `Logout`,

View File

@ -59,7 +59,7 @@ import ComingSoonPage from '@/pages/ComingSoonPage';
const AppRoutingSetup = (): ReactElement => { const AppRoutingSetup = (): ReactElement => {
return ( return (
<Routes> <Routes>
{/* <Route element={<RequireAuth />}> */} <Route element={<RequireAuth />}>
<Route element={<Demo2Layout />}> <Route element={<Demo2Layout />}>
<Route path="/" element={<DashboardHomePage />} /> <Route path="/" element={<DashboardHomePage />} />
<Route path="/account/home/user-profile" element={<AccountUserProfilePage />} /> <Route path="/account/home/user-profile" element={<AccountUserProfilePage />} />
@ -142,7 +142,7 @@ const AppRoutingSetup = (): ReactElement => {
/> */} /> */}
{/* DISBURSEMENT */} {/* DISBURSEMENT */}
</Route> </Route>
{/* </Route> */} </Route>
<Route path="error/*" element={<ErrorsRouting />} /> <Route path="error/*" element={<ErrorsRouting />} />
<Route path="auth/*" element={<AuthPage />} /> <Route path="auth/*" element={<AuthPage />} />
<Route path="*" element={<Navigate to="/error/404" />} /> <Route path="*" element={<Navigate to="/error/404" />} />