Skip to content

Commit

Permalink
fix(earth-map): refactor service layer, support refresh token interce…
Browse files Browse the repository at this point in the history
…ptors
  • Loading branch information
iacoshoria committed Oct 14, 2020
1 parent 52dd26b commit fb7a875
Show file tree
Hide file tree
Showing 47 changed files with 411 additions and 731 deletions.
8 changes: 1 addition & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,15 @@
"@natgeosociety/marapp-uikit": "^1.0.11",
"assert": "^2.0.0",
"axios": "^0.18.0",
"axios-cache-adapter": "^2.3.0",
"basic-auth": "^2.0.1",
"classnames": "^2.2.6",
"d3-ease": "^1.0.5",
"d3-geo": "^1.11.3",
"deck.gl": "7.3.6",
"delay": "^4.1.0",
"iframe-resizer": "^3.6.6",
"jsona": "^1.4.0",
"flat": "^5.0.2",
"json2csv": "^5.0.3",
"layer-manager": "^3.0.6",
"localforage": "^1.7.3",
"localforage-memoryStorageDriver": "^0.9.2",
"lodash": "^4.17.11",
"luma.gl": "7.3.2",
"moment": "^2.24.0",
Expand Down Expand Up @@ -75,8 +70,7 @@
"vega-lib": "^4.4.0",
"viewport-mercator-project": "6.1.1",
"vizzuality-components": "^3.0.1",
"vizzuality-redux-tools": "^4.0.2",
"wri-json-api-serializer": "^1.0.1"
"vizzuality-redux-tools": "^4.0.2"
},
"devDependencies": {
"@babel/cli": "^7.2.3",
Expand Down
2 changes: 1 addition & 1 deletion packages/earth-admin/gatsby-browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export const wrapRootElement = ({ element }) => (
onSuccessHook={onSuccessHook}
onFailureHook={onFailureHook}
useRefreshTokens={true}
cacheLocation={'localstorage'}
cacheLocation={'memory'}
>
{element}
</Auth0Provider>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ import React, { useState } from 'react';
import { AuthzGuards, ErrorMessages } from '@marapp/earth-shared';

import { useAuth0 } from '@app/auth/auth0';
import { normalizeGroupName } from '@app/utils';
import { LinkWithOrg } from '@app/components/link-with-org';
import { DeleteConfirmation } from '@app/components/modals/delete-confirmation';
import { normalizeGroupName } from '@app/utils';

import { UserProps } from '../model';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ import renderHTML from 'react-render-html';
import useSWR from 'swr';

import {
alphaNumericDashesRule,
AsyncSelect,
AuthzGuards,
ErrorMessages,
InlineEditCard,
Input,
alphaNumericDashesRule,
setupErrors,
} from '@marapp/earth-shared';

Expand Down
4 changes: 2 additions & 2 deletions packages/earth-admin/src/pages-client/dashboards/new.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,12 @@ import React, { useState } from 'react';
import { Controller, useForm } from 'react-hook-form';

import {
alphaNumericDashesRule,
AsyncSelect,
ErrorMessages,
Spinner,
Input,
alphaNumericDashesRule,
setupErrors,
Spinner,
} from '@marapp/earth-shared';

import { useAuth0 } from '@app/auth/auth0';
Expand Down
2 changes: 1 addition & 1 deletion packages/earth-admin/src/pages-client/layers/details.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,12 @@ import Select from 'react-select';
import useSWR from 'swr';

import {
alphaNumericDashesRule,
AsyncSelect,
AuthzGuards,
ErrorMessages,
InlineEditCard,
Input,
alphaNumericDashesRule,
setupErrors,
} from '@marapp/earth-shared';

Expand Down
4 changes: 2 additions & 2 deletions packages/earth-admin/src/pages-client/layers/new.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,12 @@ import { Controller, useForm } from 'react-hook-form';
import Select from 'react-select';

import {
alphaNumericDashesRule,
AsyncSelect,
ErrorMessages,
Spinner,
Input,
alphaNumericDashesRule,
setupErrors,
Spinner,
} from '@marapp/earth-shared';

import { useAuth0 } from '@app/auth/auth0';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ import { useForm } from 'react-hook-form';

import {
ErrorMessages,
Spinner,
Input,
setupErrors,
Spinner,
upperNumericDashesRule,
validEmailRule,
} from '@marapp/earth-shared';
Expand Down
2 changes: 1 addition & 1 deletion packages/earth-admin/src/pages-client/places/details.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ import { calculateAllForPlace, getPlace, handlePlaceForm } from '@app/services';
import { encodeQueryToURL, formatArrayToParentheses, formatDate, km2toHa } from '@app/utils';
import { MapComponentContext } from '@app/utils/contexts';

import { PLACE_DETAIL_QUERY, PlaceIntersection, IPlace } from './model';
import { IPlace, PLACE_DETAIL_QUERY, PlaceIntersection } from './model';

interface IProps {
path: string;
Expand Down
2 changes: 1 addition & 1 deletion packages/earth-admin/src/pages-client/places/new.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { noop } from 'lodash';
import React, { useState } from 'react';
import { useForm } from 'react-hook-form';

import { ErrorMessages, Spinner, Input, setupErrors } from '@marapp/earth-shared';
import { ErrorMessages, Input, setupErrors, Spinner } from '@marapp/earth-shared';

import { useAuth0 } from '@app/auth/auth0';
import { Card } from '@app/components/card';
Expand Down
2 changes: 1 addition & 1 deletion packages/earth-admin/src/pages-client/widgets/details.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,12 @@ import Select from 'react-select';
import useSWR from 'swr';

import {
alphaNumericDashesRule,
AsyncSelect,
AuthzGuards,
ErrorMessages,
InlineEditCard,
Input,
alphaNumericDashesRule,
setupErrors,
} from '@marapp/earth-shared';

Expand Down
4 changes: 2 additions & 2 deletions packages/earth-admin/src/pages-client/widgets/new.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,12 @@ import { Controller, useForm } from 'react-hook-form';
import Select from 'react-select';

import {
alphaNumericDashesRule,
AsyncSelect,
ErrorMessages,
Spinner,
Input,
alphaNumericDashesRule,
setupErrors,
Spinner,
} from '@marapp/earth-shared';

import { useAuth0 } from '@app/auth/auth0';
Expand Down
2 changes: 1 addition & 1 deletion packages/earth-admin/src/utils/hooks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@
specific language governing permissions and limitations under the License.
*/

import { groupBy } from 'lodash';
import { noop } from 'lodash/fp';
import { useSWRInfinite } from 'swr';
import { groupBy } from 'lodash';

/**
* Custom hook that integrates useSWRInfinite with <DataListing /> component
Expand Down
2 changes: 1 addition & 1 deletion packages/earth-admin/src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@
*/

import { navigate } from 'gatsby';
import { capitalize } from 'lodash';
import moment from 'moment';
import queryStringEncode from 'query-string-encode';
import { RefObject } from 'react';
import { capitalize } from 'lodash';

import { ADMIN_PAGES } from '@app/components/sidebar-select/model';
import { BASE_URL } from '@app/config';
Expand Down
1 change: 1 addition & 0 deletions packages/earth-map/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"react-intersection-observer": "^8.26.2",
"three": "^0.103.0",
"three-css2drender": "^1.0.0",
"ts-jsonapi": "^2.1.3",
"url-join": "^4.0.1",
"viewport-mercator-project": "^6.1.1",
"yn": "^4.0.0"
Expand Down
6 changes: 3 additions & 3 deletions packages/earth-map/src/auth/auth0.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ export const Auth0Provider = ({
setIsAuthenticated(isAuthenticated);

const accessToken = isAuthenticated ? await auth0FromHook.getTokenSilently() : null;
onSuccessHook({ token: accessToken });
onSuccessHook({ accessToken, authClient: auth0FromHook });

const idToken = accessToken ? await auth0FromHook.getUser() : {};

Expand Down Expand Up @@ -163,7 +163,7 @@ export const Auth0Provider = ({
* grant and the refresh token from the cache.
* @param options
*/
const getToken = (options = {}) => {
const getAccessToken = (options = {}): Promise<string> => {
return client.getTokenSilently(options);
};

Expand All @@ -187,7 +187,7 @@ export const Auth0Provider = ({
login,
logout,
getUser,
getToken,
getAccessToken,
setupUserOrg: setSelectedGroup,
}}
>
Expand Down
16 changes: 12 additions & 4 deletions packages/earth-map/src/auth/hooks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,13 @@
specific language governing permissions and limitations under the License.
*/

import { Auth0Client } from '@auth0/auth0-spa-js';
import axios from 'axios';
import { errorHandler, successHandler } from 'services/interceptors/response';
import { routeToPage } from 'utils';

import { noopInterceptor } from '../services/interceptors/request';

/**
* Routes the user to the right place after login.
* @param params
Expand All @@ -35,11 +39,15 @@ export const onRedirectCallback = (params: { targetUrl?: string } = {}) => {
* Configure behaviour in case of successful login.
* @param params
*/
export const onSuccessHook = (params: { token?: string } = {}) => {
const { token } = params;
if (token) {
axios.defaults.headers.common.Authorization = `Bearer ${token}`;
export const onSuccessHook = (params: { accessToken?: string; authClient?: Auth0Client } = {}) => {
if (params.accessToken) {
axios.defaults.headers.common.Authorization = `Bearer ${params.accessToken}`;
}
axios.interceptors.request.use(noopInterceptor());
axios.interceptors.response.use(
successHandler(),
errorHandler({ authClient: params.authClient })
);
};

/**
Expand Down
2 changes: 1 addition & 1 deletion packages/earth-map/src/auth/model.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export interface Auth0 {
logout?(o?: LogoutOptions): void;
login?(o?: BaseLoginOptions): void;
getUser?(o?: GetUserOptions): void;
getToken?(o?: GetTokenWithPopupOptions): void;
getAccessToken?(o?: GetTokenWithPopupOptions): Promise<string>;
setupUserOrg?(org: string): void;
}

Expand Down
4 changes: 2 additions & 2 deletions packages/earth-map/src/components/header/component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import { remove } from 'lodash';
import { EPanels } from 'modules/sidebar/model';
import React, { useContext, useEffect, useState } from 'react';
import Link from 'redux-first-router-link';
import { fetchStats } from 'services/stats';
import OrganizationService from 'services/OrganizationService';
import { APP_LOGO } from 'theme';

import { AppContextSwitcher, checkRole } from '@marapp/earth-shared';
Expand Down Expand Up @@ -77,7 +77,7 @@ const Header = (props: IProps) => {
useEffect(() => {
(async () => {
try {
const response: any = await fetchStats({ group: groups.join(',') });
const response = await OrganizationService.fetchStats({ group: groups.join(',') });
setAvailableGroups(response.data);
} catch (err) {
console.error(err);
Expand Down
2 changes: 1 addition & 1 deletion packages/earth-map/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ ReactDOM.render(
onSuccessHook={onSuccessHook}
onFailureHook={onFailureHook}
useRefreshTokens={true}
cacheLocation={'localstorage'}
cacheLocation={'memory'}
>
<App />
</Auth0Provider>,
Expand Down
4 changes: 2 additions & 2 deletions packages/earth-map/src/pages/change-email/component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
import { useAuth0 } from 'auth/auth0';
import React, { useEffect } from 'react';
import { replace } from 'redux-first-router';
import { changeEmailConfirmation } from 'services/users';
import ProfileService from 'services/ProfileService';

import { Spinner } from '@marapp/earth-shared';

Expand All @@ -39,7 +39,7 @@ export default function ChangeEmailComponent() {
const error_description = params.get('error_description');

if (accessToken) {
const response: any = await changeEmailConfirmation({ accessToken });
const response = await ProfileService.changeEmailConfirmation({ accessToken });
if (response && response?.success) {
alert('Email change successful. Please login using the new credentials.');
// Auth0 sessions are reset when a user’s email or password changes;
Expand Down
22 changes: 11 additions & 11 deletions packages/earth-map/src/pages/profile/component.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import { Auth0Context } from 'auth/auth0';
import { REACT_APP_EXTERNAL_IDP_URL } from 'config';
import React, { useContext, useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import Link from 'redux-first-router-link';
import { fetchProfile, updateProfile } from 'services/users';
import ProfileService from 'services/ProfileService';
import { APP_LOGO } from 'theme';
import { REACT_APP_EXTERNAL_IDP_URL } from 'config';

import { useForm } from 'react-hook-form';
import {
InlineEditCard,
Spinner,
UserMenu,
Input,
setupErrors,
Spinner,
UserMenu,
validEmailRule,
} from '@marapp/earth-shared';

Expand Down Expand Up @@ -42,9 +42,9 @@ export function ProfileComponent(props: IProps) {

useEffect(() => {
(async () => {
const profile: any = await fetchProfile();
setUserProfile(profile.data);
processUserName(profile.data);
const response = await ProfileService.fetchProfile();
setUserProfile(response.data);
processUserName(response.data);

setIsLoading(false);
})();
Expand All @@ -54,12 +54,12 @@ export function ProfileComponent(props: IProps) {
e.preventDefault();

const formData = getValues();

try {
setIsLoading && setIsLoading(true);

const result: any = await updateProfile(formData);
processUserName(result.data);
const response = await ProfileService.updateProfile(formData);
setUserProfile(response.data);
processUserName(response.data);

setIsEditing && setIsEditing(false);
setIsLoading && setIsLoading(false);
Expand Down
4 changes: 2 additions & 2 deletions packages/earth-map/src/sagas/earth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import { loadDataIndexes } from 'sagas/layers';
import { LOCATION_QUERY } from 'sagas/model';
import { nextPage } from 'sagas/places';
import { getGroup, ignoreRedirectsTo } from 'sagas/saga-utils';
import { fetchPlaces } from 'services/places';
import PlacesService from 'services/PlacesService';

const ignoreRedirectsToEarth = ignoreRedirectsTo('EARTH');

Expand Down Expand Up @@ -58,7 +58,7 @@ function* loadPlaces() {

// PLACES
const places: IPlace[] = yield all({
featured: call(fetchPlaces, {
featured: call(PlacesService.fetchPlaces, {
select: 'slug,name,id,organization,type',
page: { size: 100 },
filter: 'featured==true',
Expand Down
Loading

0 comments on commit fb7a875

Please sign in to comment.