Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import React, { createContext, useContext, useEffect, useState } from 'react';
import api from 'services/api';
import interceptResponse from 'services/interceptResponse';
const AuthContext = createContext({});
export const AuthProvider = ({ children }) => {
const [auth, setAuth] = useState({
isAuth: false,
data: {},
});
const saveAuth = (props) => {
localStorage.setItem('@e-construcao/auth', JSON.stringify(props));
return setAuth(props);
};
useEffect(() => {
const auth_local = localStorage.getItem('@e-construcao/auth');
if (auth_local !== null) setAuth(JSON.parse(auth_local));
}, []);
const RefreshToken = async () => {
try {
const { refresh_token } = auth.data;
await api.setHeader('Authorization', `Bearer ${refresh_token}`);
const response = await api.post('/oauth/refresh');
if (response.status !== 200) {
throw response;
}
api.setHeader('Authorization', `Bearer ${response.data.access_token}`);
return saveAuth({
...auth,
data: response.data,
isAuth: true,
});
} catch (e) {
return e;
}
};
const prepareRequest = async (request, url, params = null) => {
const { access_token } = auth.data;
api.setHeader('Authorization', `Bearer ${access_token}`);
const response = await request(url, params);
const isValid = interceptResponse(response, false);
if (response.status === 401) {
await RefreshToken();
const responseTakeTwo = await request(url, params);
return responseTakeTwo;
}
if (isValid) {
return response;
}
return false;
};
const getLogout = async () => {
saveAuth({
isAuth: false,
data: {},
});
};
return (
<AuthContext.Provider
value={{
auth,
getLogout,
prepareRequest,
saveAuth,
}}>
{children}
</AuthContext.Provider>
);
};
export function useAuth() {
const context = useContext(AuthContext);
if (!context) {
throw new Error('The context The Perfil must be within a valid provider');
}
return context;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment