Skip to content

Commit

Permalink
Url functionality and tests (#194)
Browse files Browse the repository at this point in the history
Co-authored-by: Maximilian Øystå Lloyd <[email protected]>
  • Loading branch information
max-nav and Maximilian Øystå Lloyd authored Feb 22, 2024
1 parent 34300a0 commit 9422b03
Show file tree
Hide file tree
Showing 8 changed files with 174 additions and 63 deletions.
43 changes: 0 additions & 43 deletions packages/client/src/helpers/urls.ts

This file was deleted.

33 changes: 16 additions & 17 deletions packages/client/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { logoutWarningController } from './controllers/logout-warning';
import './main.css';
import { useLoadIfActiveSession } from './screensharing';
import './views/breadcrumb';
import './views/context-link';
import './views/context-link';
import './views/decorator-utils';
import './views/dropdown-menu';
import './views/language-selector';
Expand All @@ -24,22 +24,21 @@ import './views/search-input';
import './views/search-menu';
import './views/feedback';
import './views/login-button';
import './views/chatbot-wrapper';
import './views/chatbot-wrapper';
import { Auth } from './api';
import { addFaroMetaData } from './faro';
import { analyticsLoaded, analyticsReady, createEvent } from './events';
import { MessageEvents, analyticsLoaded, analyticsReady, createEvent } from './events';
import { type ParamKey } from 'decorator-shared/params';
import { param, hasParam, updateDecoratorParams, env } from './params';

console.log('Decorator client loaded');
import { makeEndpointFactory } from 'decorator-shared/urls';

import.meta.glob('./styles/*.css', { eager: true });

// Just for testing
export const CONTEXTS = ['privatperson', 'arbeidsgiver', 'samarbeidspartner'] as const;

const texts = window.__DECORATOR_DATA__.texts;

const makeEndpoint = makeEndpointFactory(() => window.__DECORATOR_DATA__.params, env('APP_URL'));

updateDecoratorParams({});

if (hasParam('logoutWarning')) {
Expand All @@ -50,6 +49,7 @@ window.addEventListener('message', (e) => {
if (e.data.source === 'decoratorClient' && e.data.event === 'ready') {
window.postMessage({ source: 'decorator', event: 'ready' });
}

if (e.data.source === 'decoratorClient' && e.data.event == 'params') {
const payload = e.data.payload;

Expand Down Expand Up @@ -102,16 +102,15 @@ window.addEventListener('activecontext', (event) => {
});

async function populateLoggedInMenu(authObject: Auth) {
fetch(
`${env('APP_URL')}/user-menu?${formatParams({
...window.__DECORATOR_DATA__.params,
name: authObject.name,
level: `Level${authObject.securityLevel}` as LoginLevel,
})}`,
{
credentials: 'include',
}
)
const url = makeEndpoint('/user-menu', {
name: authObject.name,
// Should have function for this and tests
level: `Level${authObject.securityLevel}` as LoginLevel,
});

fetch(url, {
credentials: 'include',
})
.then((res) => res.text())
.then((html) => {
const userMenu = document.querySelector('user-menu');
Expand Down
4 changes: 2 additions & 2 deletions packages/client/src/views/context-link.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { erNavDekoratoren } from '../helpers/urls';
import { erNavDekoratoren } from 'decorator-shared/urls';
import headerClasses from '../styles/header.module.css';
import { tryParse } from 'decorator-shared/json';
import { type AnalyticsEventArgs } from '../analytics/constants';
Expand All @@ -21,7 +21,7 @@ class ContextLink extends HTMLElement {
window.addEventListener('activecontext', this.handleActiveContext);

this.addEventListener('click', (e) => {
if (erNavDekoratoren()) {
if (erNavDekoratoren(window.location.href)) {
e.preventDefault();
}

Expand Down
2 changes: 1 addition & 1 deletion packages/server/src/views/decorator-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export const DecoratorData = ({
params,
features,
environment,
}: {
}: {
texts: ClientTexts;
params: Params;
features: Features;
Expand Down
Empty file added packages/shared/events.ts
Empty file.
75 changes: 75 additions & 0 deletions packages/shared/test/urls.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { describe, expect, it } from 'bun:test';
import { makeEndpointFactory, makeLoginUrl } from 'lib/urls';

const dummyEnv = {
LOGIN_URL: 'https://www.nav.no/login',
APP_URL: 'https://www.nav.no',
MIN_SIDE_URL: 'https://www.nav.no/min-side',
MIN_SIDE_ARBEIDSGIVER_URL: 'https://www.nav.no/min-side-arbeidsgiver',
};

describe('URLs', () => {
it('It includes params from the defaultParams function', () => {
const params = {
simple: true,
} as any;

const callEndpoint = makeEndpointFactory(
() => ({
...params,
}),
'http://localhost:3000'
);

expect(
callEndpoint('/user-menu', {
feedback: true,
})
).toBe('http://localhost:3000/user-menu?simple=true&feedback=true');
});

it('Basic login URL with redirect is created correctly', () => {
const loginUrl = makeLoginUrl({
environment: dummyEnv,
params: {
level: 'Level3',
redirectToApp: false,
redirectToUrl: 'https://www.nav.no',
context: 'privatperson',
language: 'nb',
},
});

expect(loginUrl).toBe('https://www.nav.no/login?redirect=https://www.nav.no&level=Level3&locale=nb');
});

it('Redirect should be min side arbeidsgiver if context is arbeidsgiver', () => {
const loginUrl = makeLoginUrl({
environment: dummyEnv,
params: {
level: 'Level3',
redirectToApp: false,
redirectToUrl: '',
context: 'arbeidsgiver',
language: 'nb',
},
});

expect(loginUrl).toBe(`https://www.nav.no/login?redirect=${dummyEnv.MIN_SIDE_ARBEIDSGIVER_URL}&level=Level3&locale=nb`);
});

it('Redirect should be min side if no redirectToUrl is set and redirectToApp is false and context is anything but arbeidsgiver', () => {
const loginUrl = makeLoginUrl({
environment: dummyEnv,
params: {
level: 'Level3',
redirectToApp: false,
redirectToUrl: '',
context: 'privatperson',
language: 'nb',
},
});

expect(loginUrl).toBe(`https://www.nav.no/login?redirect=${dummyEnv.MIN_SIDE_URL}&level=Level3&locale=nb`);
});
});
3 changes: 3 additions & 0 deletions packages/shared/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,9 @@ export type Features = {
'dekoratoren.chatbotscript': boolean;
};

/**
* Computed values based on params and environment
*/
export type AppState = {
texts: ClientTexts;
params: Params;
Expand Down
77 changes: 77 additions & 0 deletions packages/shared/urls.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { formatParams } from './json';
import { Environment, Language, Params } from './params';

type IdPortenLocale = 'nb' | 'nn' | 'en' | 'se';

const idPortenLocaleMap: Record<Language, IdPortenLocale> = {
nb: 'nb',
nn: 'nn',
se: 'se',
en: 'en',
pl: 'en',
ru: 'en',
uk: 'en',
};

export function getIdPortenLocale(language: Language) {
return idPortenLocaleMap[language];
}

export function makeEndpointFactory(defaultParams: () => Params, origin: string) {
return (endpoint: string, params: Partial<Params>) => {
const formattedParams = formatParams({
...defaultParams(),
...params,
});

return `${origin}${endpoint}?${formattedParams}`;
};
}

type GetUrlLoginOptions = {
environment: Pick<Environment, 'APP_URL' | 'MIN_SIDE_URL' | 'MIN_SIDE_ARBEIDSGIVER_URL' | 'LOGIN_URL'>;
params: Pick<Params, 'redirectToApp' | 'redirectToUrl' | 'context' | 'level' | 'language'>;
isClientSide?: boolean;
};

function makeRedirectUrlLogin({ environment, params, isClientSide = false }: GetUrlLoginOptions) {
const { redirectToUrl, redirectToApp } = params;

const appUrl = environment.APP_URL;

if (isClientSide && erNavDekoratoren(appUrl)) {
return appUrl;
}

if (redirectToUrl) {
return redirectToUrl;
}

if (redirectToApp) {
return appUrl;
}

if (params.context === 'arbeidsgiver') {
return environment.MIN_SIDE_ARBEIDSGIVER_URL;
}

return environment.MIN_SIDE_URL;
}

export function makeLoginUrl(
options: GetUrlLoginOptions & {
overrideLevel?: string;
}
) {
const redirectUrl = makeRedirectUrlLogin(options);
const idPortenLocale = getIdPortenLocale(options.params.language);

console.log('idPortenLocale', idPortenLocale);

const { environment, params } = options;
return `${environment.LOGIN_URL}?redirect=${redirectUrl}&level=${options.overrideLevel || params.level}&locale=${idPortenLocale}`;
}

export function erNavDekoratoren(url: string) {
return url.includes('dekoratoren') || url.includes('localhost');
}

0 comments on commit 9422b03

Please sign in to comment.