Skip to content

Commit

Permalink
Merge pull request #1271 from ral-facilities/feature/use-ga4-#1219
Browse files Browse the repository at this point in the history
Feature/use ga4 #1219
  • Loading branch information
jounaidr authored Mar 29, 2023
2 parents 48dbb13 + cfc1696 commit 6e68bdc
Show file tree
Hide file tree
Showing 12 changed files with 37 additions and 230 deletions.
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@
"react": "17.0.2",
"react-app-polyfill": "3.0.0",
"react-dom": "17.0.2",
"react-ga": "3.3.0",
"react-i18next": "12.1.1",
"react-joyride": "2.5.0",
"react-redux": "8.0.4",
Expand Down
20 changes: 0 additions & 20 deletions src/authentication/githubAuthProvider.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import mockAxios from 'axios';
import GithubAuthProvider from './githubAuthProvider';
import ReactGA from 'react-ga';

describe('github auth provider', () => {
let authProvider: GithubAuthProvider;
Expand All @@ -18,11 +17,6 @@ describe('github auth provider', () => {
window.localStorage.__proto__.setItem = jest.fn();

authProvider = new GithubAuthProvider('http://localhost:8000');
ReactGA.initialize('test id', { testMode: true, titleCase: false });
});

afterEach(() => {
ReactGA.testModeAPI.resetCalls();
});

it('should load the token when built', () => {
Expand Down Expand Up @@ -59,13 +53,6 @@ describe('github auth provider', () => {
expect(authProvider.user).not.toBeNull();
expect(authProvider.user?.username).toBe('user');
expect(authProvider.user?.avatarUrl).toBe('gravitar.com/fiowmefoimwe');

expect(ReactGA.testModeAPI.calls[1][0]).toEqual('send');
expect(ReactGA.testModeAPI.calls[1][1]).toEqual({
eventAction: 'Sucessfully logged in via Github',
eventCategory: 'Login',
hitType: 'event',
});
});

it('should log the user out if there is no verification code', async () => {
Expand All @@ -90,13 +77,6 @@ describe('github auth provider', () => {

expect(localStorage.removeItem).toBeCalledWith('scigateway:token');
expect(authProvider.isLoggedIn()).toBeFalsy();

expect(ReactGA.testModeAPI.calls[1][0]).toEqual('send');
expect(ReactGA.testModeAPI.calls[1][1]).toEqual({
eventAction: 'Failed to log in via Github',
eventCategory: 'Login',
hitType: 'event',
});
});

it('should log the user out if the token has expired', async () => {
Expand Down
9 changes: 0 additions & 9 deletions src/authentication/githubAuthProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import qs from 'query-string';
import Axios from 'axios';
import BaseAuthProvider from './baseAuthProvider';
import ReactGA from 'react-ga';

export default class GithubAuthProvider extends BaseAuthProvider {
public constructor(authUrl: string | undefined) {
Expand All @@ -23,19 +22,11 @@ export default class GithubAuthProvider extends BaseAuthProvider {
code: params.code,
})
.then((res) => {
ReactGA.event({
category: 'Login',
action: 'Sucessfully logged in via Github',
});
this.storeToken(res.data.token);
this.storeUser(res.data.username, undefined, res.data.avatar);
return;
})
.catch((err) => {
ReactGA.event({
category: 'Login',
action: 'Failed to log in via Github',
});
this.handleAuthError(err);
});
}
Expand Down
34 changes: 0 additions & 34 deletions src/authentication/icatAuthProvider.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import mockAxios from 'axios';
import ICATAuthProvider from './icatAuthProvider';
import ReactGA from 'react-ga';
import parseJwt from './parseJwt';
import { BroadcastSignOutType } from '../state/scigateway.types';

Expand Down Expand Up @@ -31,7 +30,6 @@ describe('ICAT auth provider', () => {
'http://localhost:8000',
true
);
ReactGA.initialize('test id', { testMode: true, titleCase: false });
(parseJwt as jest.Mock).mockImplementation(
(token) =>
`{"sessionId": "${token}", "username": "${token} username", "userIsAdmin": true}`
Expand All @@ -40,10 +38,6 @@ describe('ICAT auth provider', () => {
document.dispatchEvent = jest.fn();
});

afterEach(() => {
ReactGA.testModeAPI.resetCalls();
});

it('should set the mnemonic to empty string if none is provided (after autologin)', async () => {
icatAuthProvider = new ICATAuthProvider(
undefined,
Expand Down Expand Up @@ -136,13 +130,6 @@ describe('ICAT auth provider', () => {
expect(icatAuthProvider.isLoggedIn()).toBeTruthy();
expect(icatAuthProvider.user).not.toBeNull();
expect(icatAuthProvider.user?.username).toBe(testToken + ' username');

expect(ReactGA.testModeAPI.calls[1][0]).toEqual('send');
expect(ReactGA.testModeAPI.calls[1][1]).toEqual({
eventAction: 'Successfully logged in via JWT',
eventCategory: 'Login',
hitType: 'event',
});
});

it('should log the user out for an invalid login attempt', async () => {
Expand All @@ -163,13 +150,6 @@ describe('ICAT auth provider', () => {

expect(localStorage.removeItem).toBeCalledWith('scigateway:token');
expect(icatAuthProvider.isLoggedIn()).toBeFalsy();

expect(ReactGA.testModeAPI.calls[1][0]).toEqual('send');
expect(ReactGA.testModeAPI.calls[1][1]).toEqual({
eventAction: 'Failed to log in via JWT',
eventCategory: 'Login',
hitType: 'event',
});
});

it('should attempt to autologin via anon authenticator when initialised', async () => {
Expand Down Expand Up @@ -203,13 +183,6 @@ describe('ICAT auth provider', () => {
expect(icatAuthProvider.user?.username).toBe(testToken + ' username');
expect(icatAuthProvider.isAdmin()).toBeTruthy();

expect(ReactGA.testModeAPI.calls[1][0]).toEqual('send');
expect(ReactGA.testModeAPI.calls[1][1]).toEqual({
eventAction: 'Successfully logged in via JWT',
eventCategory: 'Login',
hitType: 'event',
});

expect(icatAuthProvider.mnemonic).toBe('');
});

Expand Down Expand Up @@ -244,13 +217,6 @@ describe('ICAT auth provider', () => {
expect(icatAuthProvider.isLoggedIn()).toBeFalsy();
expect(localStorage.setItem).toBeCalledWith('autoLogin', 'false');

expect(ReactGA.testModeAPI.calls[1][0]).toEqual('send');
expect(ReactGA.testModeAPI.calls[1][1]).toEqual({
eventAction: 'Failed to log in via JWT',
eventCategory: 'Login',
hitType: 'event',
});

expect(icatAuthProvider.mnemonic).toBe('');
});

Expand Down
9 changes: 0 additions & 9 deletions src/authentication/icatAuthProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import Axios from 'axios';
import BaseAuthProvider from './baseAuthProvider';
import ReactGA from 'react-ga';
import parseJwt from './parseJwt';
import { ScheduledMaintenanceState } from '../state/scigateway.types';
import { MaintenanceState } from '../state/scigateway.types';
Expand Down Expand Up @@ -43,10 +42,6 @@ export default class ICATAuthProvider extends BaseAuthProvider {
},
})
.then((res) => {
ReactGA.event({
category: 'Login',
action: 'Successfully logged in via JWT',
});
if (this.isLoggedIn() && localStorage.getItem('autoLogin') === 'true') {
this.logOut();
}
Expand All @@ -61,10 +56,6 @@ export default class ICATAuthProvider extends BaseAuthProvider {
return;
})
.catch((err) => {
ReactGA.event({
category: 'Login',
action: 'Failed to log in via JWT',
});
this.handleAuthError(err);
});
}
Expand Down
17 changes: 0 additions & 17 deletions src/authentication/jwtAuthProvider.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import mockAxios from 'axios';
import JWTAuthProvider from './jwtAuthProvider';
import ReactGA from 'react-ga';

describe('jwt auth provider', () => {
let jwtAuthProvider: JWTAuthProvider;
Expand All @@ -18,11 +17,9 @@ describe('jwt auth provider', () => {
window.localStorage.__proto__.setItem = jest.fn();

jwtAuthProvider = new JWTAuthProvider('http://localhost:8000');
ReactGA.initialize('test id', { testMode: true, titleCase: false });
});

afterEach(() => {
ReactGA.testModeAPI.resetCalls();
(mockAxios.post as jest.Mock).mockClear();
});

Expand Down Expand Up @@ -75,13 +72,6 @@ describe('jwt auth provider', () => {
expect(jwtAuthProvider.user).not.toBeNull();
expect(jwtAuthProvider.user?.username).toBe('user');
expect(jwtAuthProvider.isLoggedIn()).toBeTruthy();

expect(ReactGA.testModeAPI.calls[1][0]).toEqual('send');
expect(ReactGA.testModeAPI.calls[1][1]).toEqual({
eventAction: 'Sucessfully logged in via JWT',
eventCategory: 'Login',
hitType: 'event',
});
});

it('should log the user out for an invalid login attempt', async () => {
Expand All @@ -102,13 +92,6 @@ describe('jwt auth provider', () => {

expect(localStorage.removeItem).toBeCalledWith('scigateway:token');
expect(jwtAuthProvider.isLoggedIn()).toBeFalsy();

expect(ReactGA.testModeAPI.calls[1][0]).toEqual('send');
expect(ReactGA.testModeAPI.calls[1][1]).toEqual({
eventAction: 'Failed to log in via JWT',
eventCategory: 'Login',
hitType: 'event',
});
});

it('should call api to verify token', async () => {
Expand Down
9 changes: 0 additions & 9 deletions src/authentication/jwtAuthProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import Axios from 'axios';
import BaseAuthProvider from './baseAuthProvider';
import ReactGA from 'react-ga';

export default class JWTAuthProvider extends BaseAuthProvider {
public logIn(username: string, password: string): Promise<void> {
Expand All @@ -13,19 +12,11 @@ export default class JWTAuthProvider extends BaseAuthProvider {
password,
})
.then((res) => {
ReactGA.event({
category: 'Login',
action: 'Sucessfully logged in via JWT',
});
this.storeToken(res.data.token);
this.storeUser(username);
return;
})
.catch((err) => {
ReactGA.event({
category: 'Login',
action: 'Failed to log in via JWT',
});
this.handleAuthError(err);
});
}
Expand Down
47 changes: 21 additions & 26 deletions src/cookieConsent/cookieConsent.component.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import { Provider } from 'react-redux';
import { buildTheme } from '../theming';
import { StyledEngineProvider, ThemeProvider } from '@mui/material/styles';
import Cookies from 'js-cookie';
import ReactGA from 'react-ga';
import { createLocation } from 'history';
import { push } from 'connected-react-router';
import { render, screen } from '@testing-library/react';
Expand Down Expand Up @@ -92,38 +91,38 @@ describe('Cookie consent component', () => {
});

it("initalises analytics if cookie consent is true but analytics hasn't yet been initialised", () => {
jest.spyOn(document.head, 'appendChild');

Cookies.get = jest
.fn()
.mockImplementationOnce((name) =>
name === 'cookie-consent' ? JSON.stringify({ analytics: true }) : 'null'
);

ReactGA.initialize = jest.fn();
ReactGA.set = jest.fn();
ReactGA.pageview = jest.fn();

render(<CookieConsent />, { wrapper: Wrapper });

expect(store.getActions().length).toEqual(1);
expect(store.getActions()[0]).toEqual(initialiseAnalytics());

expect(ReactGA.initialize).toHaveBeenCalled();
expect(ReactGA.initialize).toHaveBeenCalledWith('test id', {
titleCase: false,
gaOptions: {
cookieExpires: 60 * 60 * 24 * 365,
cookieFlags: 'Samesite=None;Secure',
},
});

expect(ReactGA.set).toHaveBeenCalled();
expect(ReactGA.set).toHaveBeenCalledWith({
anonymizeIp: true,
page: '/',
});

expect(ReactGA.pageview).toHaveBeenCalled();
expect(ReactGA.pageview).toHaveBeenCalledWith('/');
const expectedUrlScript = document.createElement('script');
expectedUrlScript.async = true;
expectedUrlScript.src = `https://www.googletagmanager.com/gtag/js?id=${state.scigateway.analytics?.id}`;

const expectedGtagScript = document.createElement('script');
expectedGtagScript.innerText =
'window.dataLayer = window.dataLayer || [];' +
'function gtag(){dataLayer.push(arguments);}' +
"gtag('js', new Date());" +
`gtag('config', '${state.scigateway.analytics?.id}');`;

expect(document.head.appendChild).toHaveBeenNthCalledWith(
1,
expectedUrlScript
);
expect(document.head.appendChild).toHaveBeenNthCalledWith(
2,
expectedGtagScript
);
});

it('should set open to false if cookie-consent cookie is set', () => {
Expand All @@ -133,10 +132,6 @@ describe('Cookie consent component', () => {
name === 'cookie-consent' ? JSON.stringify({ analytics: true }) : null
);

ReactGA.initialize = jest.fn();
ReactGA.set = jest.fn();
ReactGA.pageview = jest.fn();

render(<CookieConsent />, { wrapper: Wrapper });

expect(screen.queryByText('text')).toBeNull();
Expand Down
30 changes: 15 additions & 15 deletions src/cookieConsent/cookieConsent.component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import Button from '@mui/material/Button';
import Snackbar from '@mui/material/Snackbar';
import Cookies from 'js-cookie';
import { initialiseAnalytics } from '../state/actions/scigateway.actions';
import ReactGA from 'react-ga';
import { Action } from 'redux';
import { AnalyticsState, StateType } from '../state/state.types';
import { connect } from 'react-redux';
Expand Down Expand Up @@ -52,20 +51,21 @@ export const CookieConsent = (
consentCookie &&
consentCookie.analytics
) {
ReactGA.initialize(props.analytics.id, {
titleCase: false,
gaOptions: {
cookieExpires: 60 * 60 * 24 * 365, // one year
cookieFlags: 'Samesite=None;Secure',
},
});
const page = `${props.location.pathname}${props.location.search}`;
ReactGA.set({
anonymizeIp: true,
page,
});
// need to send initial pageview
ReactGA.pageview(page);
//Global Site Tag (gtag.js) - Google Analytics
const urlScript = document.createElement('script');
urlScript.async = true;
urlScript.src = `https://www.googletagmanager.com/gtag/js?id=${props.analytics.id}`;

const gtagScript = document.createElement('script');
gtagScript.innerText =
'window.dataLayer = window.dataLayer || [];' +
'function gtag(){dataLayer.push(arguments);}' +
"gtag('js', new Date());" +
`gtag('config', '${props.analytics.id}');`;

document.head.appendChild(urlScript);
document.head.appendChild(gtagScript);

props.initialiseAnalytics();
}

Expand Down
Loading

0 comments on commit 6e68bdc

Please sign in to comment.