diff --git a/auth.tsx b/auth.tsx new file mode 100644 index 0000000..6d34e2a --- /dev/null +++ b/auth.tsx @@ -0,0 +1,147 @@ +/* eslint-disable no-unused-vars */ +import axios, { AxiosResponse } from 'axios'; +import { + createContext, + type Dispatch, + type PropsWithChildren, + type SetStateAction, + useEffect, + useState +} from 'react'; + +import * as authHelper from '../_helpers'; +import { type AuthModel, type UserModel } from '@/auth'; +import { apiConfig } from '@/config/api.config'; +import { doSaveLogActivity } from '@/actions/GlobalActions'; + +const API_URL = apiConfig.service_dashboard; + +export const LOGIN_URL = `${API_URL}/login`; +export const FORGOT_PASSWORD_URL = `${API_URL}/reset_password`; +export const RESET_PASSWORD_URL = `${API_URL}/update_password`; +export const GET_USER_URL = `${API_URL}/user/detail`; + +interface AuthContextProps { + loading: boolean; + setLoading: Dispatch>; + auth: AuthModel | undefined; + saveAuth: (auth: AuthModel | undefined) => void; + currentUser: UserModel | undefined; + setCurrentUser: Dispatch>; + login: (email: string, password: string) => Promise; + requestPasswordResetLink: (email: string) => Promise; + changePassword: (token: string, password: string, password_confirmation: string) => Promise; + getUser: () => Promise | {}>; + logout: () => void; + verify: () => Promise; +} + +const AuthContext = createContext(null); + +const AuthProvider = ({ children }: PropsWithChildren) => { + const [loading, setLoading] = useState(true); + const [auth, setAuth] = useState(authHelper.getAuth()); + const [currentUser, setCurrentUser] = useState(); + + const verify = async () => { + if (auth) { + try { + const { data: user } = await getUser(); + const createCacheUser = { + name: user.name, + email: user.email, + username: user.username, + role_name: auth.role_name, + statusbalance: user.role.status_balance, + }; + localStorage.setItem('user', JSON.stringify(createCacheUser)); + } catch { + saveAuth(undefined); + setCurrentUser(undefined); + } + } + }; + + const saveAuth = (auth: AuthModel | undefined) => { + setAuth(auth); + if (auth) { + authHelper.setAuth(auth); + } else { + authHelper.removeAuth(); + } + }; + + const login = async (username: string, password: string) => { + try { + const { data: auth } = await axios + .post(LOGIN_URL, { username, password }) // , { headers: { 'Access-Control-Allow-Origin': "*" }} + .then((response) => response.data); + + saveAuth({ ...auth.token, id: auth.user.id, role_name: auth.role_name, user: auth.user }); + setCurrentUser(auth.user); + const createActivity = { + module: 'Login', + description: `Login`, + action: 'l' + }; + doSaveLogActivity(createActivity); + } catch (error: any) { + throw error; + } + }; + + const requestPasswordResetLink = async (email: string) => { + await axios.put(FORGOT_PASSWORD_URL + '/' + email); + }; + + const changePassword = async (token: string, password: string, retype_password: string) => { + await axios.put(`${RESET_PASSWORD_URL}/${token}`, { + password, + retype_password + }); + }; + + const getUser = async () => { + let _axios = await axios + .get(`${GET_USER_URL}/${authHelper.getAuth()?.id}`) + .then((response) => response.data.data); + + return { data: _axios }; + }; + + const logout = async () => { + const createActivity = { + module: 'Logout', + description: `Logout`, + action: 'O' + }; + await doSaveLogActivity(createActivity); + + saveAuth(undefined); + setCurrentUser(undefined); + }; + + return ( + + {children} + + ); +}; + +export { AuthContext, AuthProvider }; diff --git a/src/auth/providers/JWTProvider.tsx b/src/auth/providers/JWTProvider.tsx index ec33b0d..8cba25e 100644 --- a/src/auth/providers/JWTProvider.tsx +++ b/src/auth/providers/JWTProvider.tsx @@ -63,7 +63,7 @@ const AuthProvider = ({ children }: PropsWithChildren) => { id: auth.user.id, role_name: auth.role_name, user: auth.user, - statusbalance: auth.role.status_balance + statusbalance: auth.role?.status_balance ?? null // SAFE ACCESS }; saveAuth(enhancedAuth); @@ -76,6 +76,7 @@ const AuthProvider = ({ children }: PropsWithChildren) => { }; doSaveLogActivity(createActivity); } catch (error: any) { + console.error('Login error:', error); throw error; } }; @@ -160,4 +161,4 @@ const AuthProvider = ({ children }: PropsWithChildren) => { ); }; -export { AuthContext, AuthProvider }; +export { AuthContext, AuthProvider }; \ No newline at end of file