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

Use url builder to generate all URLs #30

Merged
merged 2 commits into from
Oct 17, 2024
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
2 changes: 1 addition & 1 deletion src/interfaces/service-container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@ import { StatsWalesApi } from '../services/stats-wales-api';

export interface ServiceContainer {
swapi: StatsWalesApi;
buildUrl: (path: string, locale: Locale, query?: Record<string, string>) => string;
buildUrl: (path: string, locale: Locale | string, query?: Record<string, string>) => string;
}
9 changes: 2 additions & 7 deletions src/middleware/ensure-authenticated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,12 @@ import JWT from 'jsonwebtoken';
import { JWTPayloadWithUser } from '../interfaces/jwt-payload-with-user';
import { logger } from '../utils/logger';
import { appConfig } from '../config';
import { Locale } from '../enums/locale';

import { localeUrl } from './language-switcher';

const config = appConfig();

export const ensureAuthenticated = (req: Request, res: Response, next: NextFunction) => {
logger.debug(`checking if user is authenticated for route ${req.originalUrl}...`);

const locale = req.language as Locale;

try {
if (!req.cookies.jwt) {
throw new Error('JWT cookie not found');
Expand All @@ -30,7 +25,7 @@ export const ensureAuthenticated = (req: Request, res: Response, next: NextFunct
if (decoded.exp && decoded.exp <= Date.now() / 1000) {
logger.error('JWT token has expired');
res.status(401);
return res.redirect(localeUrl('/auth/login', locale, { error: 'expired' }));
return res.redirect(req.buildUrl(`/auth/login`, req.language, { error: 'expired' }));
}

// store the token string in the request as we need it for Authorization header in API requests
Expand All @@ -43,7 +38,7 @@ export const ensureAuthenticated = (req: Request, res: Response, next: NextFunct
} catch (err) {
logger.error(`authentication failed: ${err}`);
res.status(401);
return res.redirect(localeUrl('/auth/login', locale));
return res.redirect(req.buildUrl(`/auth/login`, req.language));
}

return next();
Expand Down
13 changes: 7 additions & 6 deletions src/middleware/language-switcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,19 @@

import { ignoreRoutes, SUPPORTED_LOCALES, i18next } from './translation';

export const localeUrl = (path: string, locale: Locale, query?: Record<string, string>): string => {
export const localeUrl = (path: string, locale: Locale | string, query?: Record<string, string>): string => {
const locales = SUPPORTED_LOCALES as string[];

let pathElements = path
const pathElements = path
.split('/')
.filter(Boolean) // strip empty elements to avoid trailing slash
.filter((element) => !locales.includes(element)); // strip language from the path if present

if (![Locale.English, Locale.EnglishGb].includes(locale)) {
// translate the url path to the new locale
pathElements = pathElements.map((element) => i18next.t(`routes.${element}`, { lng: locale }));
}
// TODO: re-enable path translation once the router knows how to handle it

Check warning on line 17 in src/middleware/language-switcher.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

Unexpected 'todo' comment: 'TODO: re-enable path translation once...'
// if (![Locale.English, Locale.EnglishGb].includes(locale as Locale)) {
// // translate the url path to the new locale
// pathElements = pathElements.map((element) => i18next.t(`routes.${element}`, { lng: locale }));
// }

const newPath = isEmpty(pathElements) ? '' : `/${pathElements.join('/')}`;
const queryString = isEmpty(query) ? '' : `?${new URLSearchParams(query).toString()}`;
Expand Down
23 changes: 10 additions & 13 deletions src/middleware/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -214,18 +214,15 @@
"routes": {
"healthcheck": "healthcheck",
"feedback": "feedback",
"view": {
"start": "dataset"
},
"publish": {
"start": "publish",
"title": "title",
"upload": "upload",
"preview": "preview",
"confirm": "confirm",
"sources": "sources",
"source_confirmation": "source-confirmation",
"tasklist": "tasklist"
}
"dataset": "dataset",
"publish": "publish",
"start": "start",
"title": "title",
"preview": "preview",
"upload": "upload",
"confirm": "confirm",
"sources": "sources",
"source_confirmation": "source-confirmation",
"tasklist": "tasklist"
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Technically these should never get used as the url builder skips attempting to translate URLs when the locale is English.

However, we'll need them as fallback if the Welsh is missing, and the Welsh language translations need the right keys in order to work, so it makes sense for the English translation file to have them as a source.

Copy link
Collaborator Author

@wheelsandcogs wheelsandcogs Oct 16, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PS - these must be flat - the builder translates each part of the path individually not as a whole.

}
}
4 changes: 2 additions & 2 deletions src/routes/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,11 @@ auth.get('/callback', (req: Request, res: Response) => {
}

logger.debug('User successfully logged in');
res.redirect(`/${req.language}`);
res.redirect(req.buildUrl('/', req.language));
});

auth.get('/logout', (req: Request, res: Response) => {
logger.debug('logging out user');
res.clearCookie('jwt', { domain: cookieDomain });
res.redirect(`/${req.language}/auth/login`);
res.redirect(req.buildUrl(`/auth/login`, req.language));
});
2 changes: 1 addition & 1 deletion src/routes/error-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export const errorHandler: ErrorRequestHandler = (err: any, req: Request, res: R
case 401:
logger.error('401 error detected, logging user out');
res.clearCookie('jwt', { domain: cookieDomain });
res.redirect(`/${req.language}/auth/login`);
res.redirect(req.buildUrl(`/auth/login`, req.language));
break;

case 404:
Expand Down
Loading
Loading