Newer
Older
import { AuthServiceLoginApiArg, AuthServiceLoginApiResponse, useAuthServiceLoginMutation } from "@api/api";
import { getCookieValue } from "@helper/coookie";
import { useAppDispatch, useAppSelector } from "@hooks";
import { setToken } from "@reducer/user.reducer";
import { DEVICE_URL, LOGIN_URL } from "@routes";
import { jwtDecode } from "jwt-decode";
import { createContext, useContext, useEffect, useMemo } from "react";
import { useNavigate } from "react-router-dom";
interface AuthProviderType {
login: (username: string, password: string) => void,
logout: () => void,
// todo figure out the type of loginProperties
loginProperties: {
isLoading: boolean,
isSuccess: boolean,
isError: boolean,
error: object,
data: object,
reset: () => void
} | undefined,
isAuthenticated: () => boolean
}
const AuthContext = createContext<AuthProviderType>({
login: () => { throw new Error("login function not implemented"); },
logout: () => { throw new Error("logout function not implemented"); },
loginProperties: undefined,
isAuthenticated: () => { throw new Error("login function not implemented"); },
});
export const AuthProvider = ({ children }) => {
const navigate = useNavigate();
const { username } = useAppSelector(state => state.user);
const token = getCookieValue('token');
if (token) {
}, [username]);
const [
sendLogin,
loginProperties,
] = useAuthServiceLoginMutation()
/**
* Returns the /login payload
*/
const getAuthPayload = (username: string, password: string): AuthServiceLoginApiArg => {
const payload: AuthServiceLoginApiArg = {
rbacLoginRequest: {
username,
pwd: password,
timestamp: new Date().getTime().toString(),
},
}
return payload;
}
const executeLogin = (username: string, password: string) => {
const authPayload = getAuthPayload(username, password);
sendLogin(authPayload).unwrap().then((response: AuthServiceLoginApiResponse) => {
if (!response.token) {
// reset the action by calling the reset hook
throw Error("Response is successful but no token was provided. Expected response {token: '<jwt-token>'}");
}
dispatch(setToken({ token: response.token, username }));
}).catch((error) => {
// determine whether 500 or 401 err
});
}
const token = getCookieValue('token');
const { exp } = jwtDecode(token);
const currentTime = new Date().getTime() / 1000;
// TODO this is currently a workaround for the never expiring token
if (process.env.NODE_ENV === 'development') {
return !!token;
return !!token && exp! > currentTime;
}
}
const logout = () => {
dispatch(setToken(null));
}
const value = useMemo(
() => ({
loginProperties
}),
[]
);
return (
<AuthContext.Provider value={value}>
{children}
</AuthContext.Provider>
)
}
export const useAuth = () => {
return useContext(AuthContext);
}