Skip to content

Instantly share code, notes, and snippets.

@jrolo-ris
Created September 14, 2023 17:22
Show Gist options
  • Save jrolo-ris/17884f5041d3a28e674ac07da7fcde36 to your computer and use it in GitHub Desktop.
Save jrolo-ris/17884f5041d3a28e674ac07da7fcde36 to your computer and use it in GitHub Desktop.
AuthProvider
import { useCallback, useEffect, useReducer, useContext } from 'react';
import PropTypes from 'prop-types';
import { Auth0Client } from '@auth0/auth0-spa-js';
import { auth0Config } from 'src/config';
import { paths } from 'src/paths';
import { Issuer } from 'src/utils/auth';
import { AuthContext, initialState } from './auth-context';
import { CampaignIDContext } from '../campaignID';
import { setUserData } from '../userData';
const auth0Client = new Auth0Client({
domain: auth0Config.issuer_base_url,
clientId: auth0Config.client_id,
cacheLocation: 'localstorage',
audience: 'https://api.tailor.video/api/v1', //API that I created in the Auth0 Dashboard
scope: "openid profile",
authorizationParams: {
redirect_uri: auth0Config.base_url + paths.auth.auth0.callback,
},
});
var ActionType;
(function (ActionType) {
ActionType['INITIALIZE'] = 'INITIALIZE';
ActionType['LOGIN'] = 'LOGIN';
ActionType['LOGOUT'] = 'LOGOUT';
})(ActionType || (ActionType = {}));
const handlers = {
INITIALIZE: (state, action) => {
const { isAuthenticated, user } = action.payload;
return {
...state,
isAuthenticated,
isInitialized: true,
user,
};
},
LOGIN: (state, action) => {
const { user } = action.payload;
return {
...state,
isAuthenticated: true,
user,
};
},
LOGOUT: (state) => ({
...state,
isAuthenticated: false,
user: null,
}),
};
const reducer = (state, action) =>
handlers[action.type] ? handlers[action.type](state, action) : state;
const getHardCodedApiResponse = () => {
return {
eventData: [
{
"_id": "6435bba43d4022329943c0ec",
"eventName": "Play",
"pagePath": "/test-embed",
"campaignID": "364057669",
"eventCount": 13
}
],
pageInfo: [
{
"_id": "6435bba93d4022329943cd2b",
"infoType": "totalPageViews",
"campaignID": "364057669",
"value": 0
}
],
};
};
export const AuthProvider = (props) => {
const { children } = props;
const [state, dispatch] = useReducer(reducer, initialState);
const { campaignID } = useContext(CampaignIDContext); // Moved useContext here
const getToken = useCallback(async () => {
try {
const token = await auth0Client.getTokenSilently({
audience: 'https://api.tailor.video/api/v1',
scope: "openid profile",
});
console.log("Retrieved token:", token);
return token;
} catch (err) {
console.error('Failed to retrieve access token:', err);
return null;
}
}, []);
const initialize = useCallback(async () => {
try {
await auth0Client.checkSession();
const isAuthenticated = await auth0Client.isAuthenticated();
if (isAuthenticated) {
const user = await auth0Client.getUser();
const hardCodedApiResponse = getHardCodedApiResponse();
const userObject = {
id: user.sub,
avatar: user.picture,
email: user.email,
name: user.name,
plan: 'Premium',
campaignID: campaignID, // use the campaignID value from the context
eventData: hardCodedApiResponse.eventData,
pageInfo: hardCodedApiResponse.pageInfo,
campaigns: [ // add this
{
name: 'Project 1',
campaignID: '364057669'
},
{
name: 'Project 2',
campaignID: 'property2'
}
]
}
setUserData(userObject); // call setUserData here
dispatch({
type: ActionType.INITIALIZE,
payload: {
isAuthenticated,
user: userObject,
},
});
} else {
dispatch({
type: ActionType.INITIALIZE,
payload: {
isAuthenticated,
user: null,
},
});
}
} catch (err) {
console.error(err);
dispatch({
type: ActionType.INITIALIZE,
payload: {
isAuthenticated: false,
user: null,
},
});
}
}, [dispatch, campaignID]); // include campaignID in the dependency array
useEffect(
() => {
initialize();
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[initialize]
);
const loginWithRedirect = useCallback(async (appState) => {
await auth0Client.loginWithRedirect({
appState,
});
}, []);
const handleRedirectCallback = useCallback(async () => {
const result = await auth0Client.handleRedirectCallback();
const user = await auth0Client.getUser();
dispatch({
type: ActionType.LOGIN,
payload: {
user: {
id: user.sub,
avatar: user.picture,
email: user.email,
},
},
});
return result.appState;
}, []);
const logout = useCallback(async () => {
await auth0Client.logout();
dispatch({
type: ActionType.LOGOUT,
});
}, []);
return (
<AuthContext.Provider
value={{
...state,
issuer: Issuer.Auth0,
loginWithRedirect,
handleRedirectCallback,
logout,
getToken,
}}
>
{children}
</AuthContext.Provider>
);
};
AuthProvider.propTypes = {
children: PropTypes.node.isRequired,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment