Fix test, add missing await clause, add web crypto api for FE user hash

This commit is contained in:
ivanThePleasant 2022-10-26 14:27:10 +03:00
parent 16c0e79557
commit b9db4a0bea
3 changed files with 39 additions and 16 deletions

View File

@ -93,7 +93,7 @@ function App() {
setTelemetryProperties(properties); setTelemetryProperties(properties);
try { try {
fetch('https://analytics.strapi.io/api/v2/track', { await fetch('https://analytics.strapi.io/api/v2/track', {
method: 'POST', method: 'POST',
body: JSON.stringify({ body: JSON.stringify({
// This event is anonymous // This event is anonymous

View File

@ -1,12 +1,22 @@
const hash = require('hash.js'); function bufferToHex(buffer) {
return [...new Uint8Array(buffer)].map((b) => b.toString(16).padStart(2, '0')).join('');
}
const hashAdminUserEmail = (payload) => { async function digestMessage(message) {
const msgUint8 = new TextEncoder().encode(message);
const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8);
return bufferToHex(hashBuffer);
}
const hashAdminUserEmail = async (payload) => {
try { try {
const adminUserEmailHash = hash.sha256().update(payload.email).digest('hex'); return await digestMessage(payload.email);
return adminUserEmailHash;
} catch (error) { } catch (error) {
return ''; // not a secure context
const hash = import('hash.js');
return hash.sha256().update(payload.email).digest('hex');
} }
}; };

View File

@ -25,6 +25,7 @@ function setup(props) {
telemetryProperties: { telemetryProperties: {
nestedProperty: true, nestedProperty: true,
}, },
deviceId: 'someTestDeviceId',
...props, ...props,
}} }}
> >
@ -45,21 +46,33 @@ describe('useTracking', () => {
test('Call trackUsage() with all attributes', async () => { test('Call trackUsage() with all attributes', async () => {
useAppInfos.mockReturnValue({ useAppInfos.mockReturnValue({
currentEnvironment: 'testing', currentEnvironment: 'testing',
adminUserId: 'someTestUserId',
}); });
const { result } = await setup(); const { result } = await setup();
result.current.trackUsage('event', { trackingProperty: true }); result.current.trackUsage('event', { trackingProperty: true });
expect(axios.post).toBeCalledWith(expect.any(String), { expect(axios.post).toBeCalledWith(
event: 'event', expect.any(String),
uuid: 1, {
properties: expect.objectContaining({ adminUserId: 'someTestUserId',
environment: 'testing', deviceId: 'someTestDeviceId',
nestedProperty: true, event: 'event',
trackingProperty: true, eventProperties: {
}), trackingProperty: true,
}); },
groupProperties: {
nestedProperty: true,
projectId: 1,
projectType: 'Community',
},
userProperties: {},
},
{
headers: { 'Content-Type': 'application/json' },
}
);
}); });
test('Do not track if it has been disabled', async () => { test('Do not track if it has been disabled', async () => {