Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: hybrid approach adaptions #1105

Merged
merged 3 commits into from
Apr 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 78 additions & 78 deletions server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,84 @@ export function app() {
);
}

const hybridRedirect = (req: express.Request, res: express.Response, next: express.NextFunction) => {
const url = req.originalUrl;
let newUrl: string;
for (const entry of HYBRID_MAPPING_TABLE) {
const icmUrlRegex = new RegExp(entry.icm);
const pwaUrlRegex = new RegExp(entry.pwa);
if (icmUrlRegex.exec(url) && entry.handledBy === 'pwa') {
newUrl = url.replace(icmUrlRegex, `/${entry.pwaBuild}`);
break;
} else if (pwaUrlRegex.exec(url) && entry.handledBy === 'icm') {
const config: { [is: string]: string } = {};
if (/;lang=[\w_]+/.test(url)) {
const [, lang] = /;lang=([\w_]+)/.exec(url);
config.lang = lang;
}
if (!config.lang) {
config.lang = environment.defaultLocale;
}

if (/;currency=[\w_]+/.test(url)) {
const [, currency] = /;currency=([\w_]+)/.exec(url);
config.currency = currency;
}

if (/;channel=[^;]*/.test(url)) {
config.channel = /;channel=([^;]*)/.exec(url)[1];
} else {
config.channel = environment.icmChannel;
}

if (/;application=[^;]*/.test(url)) {
config.application = /;application=([^;]*)/.exec(url)[1];
} else {
config.application = environment.icmApplication || '-';
}

const build = [ICM_WEB_URL, entry.icmBuild]
.join('/')
.replace(/\$<(\w+)>/g, (match, group) => config[group] || match);
newUrl = url.replace(pwaUrlRegex, build).replace(/;.*/g, '');
break;
}
}
if (newUrl) {
if (logging) {
console.log('RED', newUrl);
}
res.redirect(301, newUrl);
} else {
next();
}
};

if (process.env.SSR_HYBRID) {
server.use('*', hybridRedirect);
}

const icmProxy = proxy(ICM_BASE_URL, {
// preserve original path
proxyReqPathResolver: (req: express.Request) => req.originalUrl,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
proxyReqOptDecorator: (options: any) => {
if (process.env.TRUST_ICM) {
// https://github.com/villadora/express-http-proxy#q-how-to-ignore-self-signed-certificates-
options.rejectUnauthorized = false;
}
return options;
},
// fool ICM so it thinks it's running here
// https://www.npmjs.com/package/express-http-proxy#preservehosthdr
preserveHostHdr: true,
});

if (process.env.PROXY_ICM || process.env.SSR_HYBRID) {
console.log("making ICM available for all requests to '/INTERSHOP'");
server.use('/INTERSHOP', icmProxy);
}

// Serve static files from browser folder
server.get(/\/.*\.(js|css)$/, (req, res) => {
// remove all parameters
Expand Down Expand Up @@ -232,22 +310,6 @@ export function app() {
})
);

const icmProxy = proxy(ICM_BASE_URL, {
// preserve original path
proxyReqPathResolver: (req: express.Request) => req.originalUrl,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
proxyReqOptDecorator: (options: any) => {
if (process.env.TRUST_ICM) {
// https://github.com/villadora/express-http-proxy#q-how-to-ignore-self-signed-certificates-
options.rejectUnauthorized = false;
}
return options;
},
// fool ICM so it thinks it's running here
// https://www.npmjs.com/package/express-http-proxy#preservehosthdr
preserveHostHdr: true,
});

const angularUniversal = (req: express.Request, res: express.Response) => {
if (logging) {
console.log(`SSR ${req.originalUrl}`);
Expand Down Expand Up @@ -311,68 +373,6 @@ export function app() {
);
};

const hybridRedirect = (req: express.Request, res: express.Response, next: express.NextFunction) => {
const url = req.originalUrl;
let newUrl: string;
for (const entry of HYBRID_MAPPING_TABLE) {
const icmUrlRegex = new RegExp(entry.icm);
const pwaUrlRegex = new RegExp(entry.pwa);
if (icmUrlRegex.exec(url) && entry.handledBy === 'pwa') {
newUrl = url.replace(icmUrlRegex, `/${entry.pwaBuild}`);
break;
} else if (pwaUrlRegex.exec(url) && entry.handledBy === 'icm') {
const config: { [is: string]: string } = {};
if (/;lang=[\w_]+/.test(url)) {
const [, lang] = /;lang=([\w_]+)/.exec(url);
config.lang = lang;
}
if (!config.lang) {
config.lang = environment.defaultLocale;
}

if (/;currency=[\w_]+/.test(url)) {
const [, currency] = /;currency=([\w_]+)/.exec(url);
config.currency = currency;
}

if (/;channel=[^;]*/.test(url)) {
config.channel = /;channel=([^;]*)/.exec(url)[1];
} else {
config.channel = environment.icmChannel;
}

if (/;application=[^;]*/.test(url)) {
config.application = /;application=([^;]*)/.exec(url)[1];
} else {
config.application = environment.icmApplication || '-';
}

const build = [ICM_WEB_URL, entry.icmBuild]
.join('/')
.replace(/\$<(\w+)>/g, (match, group) => config[group] || match);
newUrl = url.replace(pwaUrlRegex, build).replace(/;.*/g, '');
break;
}
}
if (newUrl) {
if (logging) {
console.log('RED', newUrl);
}
res.redirect(301, newUrl);
} else {
next();
}
};

if (process.env.SSR_HYBRID) {
server.use('*', hybridRedirect);
}

if (process.env.PROXY_ICM || process.env.SSR_HYBRID) {
console.log("making ICM available for all requests to '/INTERSHOP'");
server.use('/INTERSHOP', icmProxy);
}

if (/^(on|1|true|yes)$/i.test(process.env.PROMETHEUS)) {
const axios = require('axios');
const onFinished = require('on-finished');
Expand Down
2 changes: 1 addition & 1 deletion src/app/core/identity-provider/auth0.identity-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ export class Auth0IdentityProvider implements IdentityProvider {
});
this.oauthService.setupAutomaticSilentRefresh();
this.apiTokenService
.restore$(['basket', 'order'])
.restore$(['user', 'order'])
.pipe(
switchMap(() => from(this.oauthService.loadDiscoveryDocumentAndTryLogin())),
switchMap(() =>
Expand Down
48 changes: 26 additions & 22 deletions src/app/core/utils/api-token/api-token.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,14 @@ import { getLoggedInUser, getUserAuthorized, loadUserByAPIToken } from 'ish-core
import { CookiesService } from 'ish-core/utils/cookies/cookies.service';
import { mapToProperty, whenTruthy } from 'ish-core/utils/operators';

type ApiTokenCookieType = 'user' | 'basket' | 'order';
export type ApiTokenCookieType = 'user' | 'order';

interface ApiTokenCookie {
apiToken: string;
type: ApiTokenCookieType;
isAnonymous?: boolean;
orderId?: string;
creator?: string;
}

@Injectable({ providedIn: 'root' })
Expand Down Expand Up @@ -67,11 +69,11 @@ export class ApiTokenService {
.pipe(
map(([user, basket, orderId, apiToken]): ApiTokenCookie => {
if (user) {
return { type: 'user', apiToken };
return { apiToken, type: 'user', isAnonymous: false, creator: 'pwa' };
} else if (basket) {
return { type: 'basket', apiToken };
return { apiToken, type: 'user', isAnonymous: true, creator: 'pwa' };
} else if (orderId) {
return { type: 'order', apiToken, orderId };
return { apiToken, type: 'order', orderId, creator: 'pwa' };
} else {
const apiTokenCookieString = this.cookiesService.get('apiToken');
const apiTokenCookie: ApiTokenCookie = apiTokenCookieString
Expand Down Expand Up @@ -139,10 +141,10 @@ export class ApiTokenService {

hasUserApiTokenCookie() {
const apiTokenCookie = this.parseCookie();
return apiTokenCookie?.type === 'user';
return apiTokenCookie?.type === 'user' && !apiTokenCookie?.isAnonymous;
}

restore$(types: ApiTokenCookieType[] = ['user', 'basket', 'order']): Observable<boolean> {
restore$(types: ApiTokenCookieType[] = ['user', 'order']): Observable<boolean> {
if (isPlatformServer(this.platformId)) {
return of(true);
}
Expand All @@ -153,23 +155,25 @@ export class ApiTokenService {
if (types.includes(cookie?.type)) {
switch (cookie?.type) {
case 'user': {
this.store.dispatch(loadUserByAPIToken());
return race(
this.store.pipe(select(getUserAuthorized), whenTruthy(), take(1)),
timer(5000).pipe(map(() => false))
);
if (cookie.isAnonymous) {
this.store.dispatch(loadBasketByAPIToken({ apiToken: cookie.apiToken }));
return race(
this.store.pipe(
select(getCurrentBasketId),
whenTruthy(),
take(1),
map(() => true)
),
timer(5000).pipe(map(() => false))
);
} else {
this.store.dispatch(loadUserByAPIToken());
return race(
this.store.pipe(select(getUserAuthorized), whenTruthy(), take(1)),
timer(5000).pipe(map(() => false))
);
}
}
case 'basket':
this.store.dispatch(loadBasketByAPIToken({ apiToken: cookie.apiToken }));
return race(
this.store.pipe(
select(getCurrentBasketId),
whenTruthy(),
take(1),
map(() => true)
),
timer(5000).pipe(map(() => false))
);
case 'order': {
this.store.dispatch(loadOrderByAPIToken({ orderId: cookie.orderId, apiToken: cookie.apiToken }));
return race(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { AccountFacade } from 'ish-core/facades/account.facade';
import { AppFacade } from 'ish-core/facades/app.facade';
import { CheckoutFacade } from 'ish-core/facades/checkout.facade';
import { selectQueryParam } from 'ish-core/store/core/router';
import { ApiTokenService } from 'ish-core/utils/api-token/api-token.service';
import { ApiTokenCookieType, ApiTokenService } from 'ish-core/utils/api-token/api-token.service';
import { CookiesService } from 'ish-core/utils/cookies/cookies.service';
import { makeHttpError } from 'ish-core/utils/dev/api-service-utils';
import { BasketMockData } from 'ish-core/utils/dev/basket-mock-data';
Expand All @@ -20,8 +20,6 @@ import { PunchoutService } from '../services/punchout/punchout.service';

import { PunchoutIdentityProvider } from './punchout-identity-provider';

type ApiTokenCookieType = 'user' | 'basket' | 'order';

function getSnapshot(queryParams: Params): ActivatedRouteSnapshot {
return {
queryParamMap: convertToParamMap(queryParams),
Expand Down
34 changes: 29 additions & 5 deletions src/hybrid/default-url-mapping-table.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,16 +49,16 @@ export const HYBRID_MAPPING_TABLE: HybridMappingEntry[] = [
id: 'Product Detail Page',
icm: `${ICM_CONFIG_MATCH}/ViewProduct-Start.*(\\?|&)SKU=(?<sku>[\\w-]+).*$`,
pwaBuild: `product/$<sku>${PWA_CONFIG_BUILD}`,
pwa: `^.*/product/([\\w-]+).*$`,
icmBuild: `ViewProduct-Start?SKU=$1`,
pwa: `/(?!cat)((?!.*-cat.*-sku).*-)?sku(.*?)(-cat(.*))?$`,
icmBuild: `ViewProduct-Start?SKU=$2`,
handledBy: 'pwa',
},
{
id: 'Category Page',
icm: `${ICM_CONFIG_MATCH}/ViewStandardCatalog-Browse.*(\\?|&)CatalogID=(?<catalog>[\\w-]+).*$`,
pwaBuild: `category/$<catalog>${PWA_CONFIG_BUILD}`,
pwa: `^.*/category/([\\w-]+).*$`,
icmBuild: `ViewStandardCatalog?CatalogID=$1&CategoryName=$1`,
pwa: `^/(?!category|categoryref/.*$)(.*-)?cat([^?]*)`,
icmBuild: `ViewStandardCatalog-Browse?CatalogID=$2&CategoryName=$2`,
handledBy: 'pwa',
},
{
Expand All @@ -67,7 +67,7 @@ export const HYBRID_MAPPING_TABLE: HybridMappingEntry[] = [
pwaBuild: `basket${PWA_CONFIG_BUILD}`,
pwa: '^/basket.*$',
icmBuild: 'ViewCart-View',
handledBy: 'pwa',
handledBy: 'icm',
},
{
id: 'Login',
Expand Down Expand Up @@ -101,4 +101,28 @@ export const HYBRID_MAPPING_TABLE: HybridMappingEntry[] = [
icmBuild: 'ViewUserAccount-Start',
handledBy: 'icm',
},
{
id: 'Register',
icm: `${ICM_CONFIG_MATCH}/ViewUserAccount-ShowRegister.*$`,
pwaBuild: `register${PWA_CONFIG_BUILD}`,
pwa: '^/register.*$',
icmBuild: 'ViewUserAccount-ShowRegister',
handledBy: 'pwa',
},
{
id: 'Product Compare',
icm: `${ICM_CONFIG_MATCH}/ViewProductCompare-Show.*$`,
pwaBuild: `compare${PWA_CONFIG_BUILD}`,
pwa: '^/compare.*$',
icmBuild: 'ViewProductCompare-Show',
handledBy: 'pwa',
},
{
id: 'Quick Order',
icm: `${ICM_CONFIG_MATCH}/ViewQuickorder-Start.*$`,
pwaBuild: `quick-order${PWA_CONFIG_BUILD}`,
pwa: '^/quick-order.*$',
icmBuild: 'ViewQuickorder-Start',
handledBy: 'icm',
},
];