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

finos/a11y-theme-builder#876: adding support for prettier #948

Merged
merged 2 commits into from
Jul 15, 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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
4 changes: 4 additions & 0 deletions code/.prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules/
build/
dist/
coverage/
12 changes: 12 additions & 0 deletions code/.prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"printWidth": 80,
"tabWidth": 4,
"useTabs": false,
"semi": true,
"singleQuote": true,
"trailingComma": "es5",
"bracketSpacing": true,
"bracketSameLine": false,
"arrowParens": "always",
"endOfLine": "lf"
}
24 changes: 23 additions & 1 deletion code/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion code/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
"docker-stop": "docker stop a11y-theme-builder",
"docker-start": "docker start a11y-theme-builder",
"docker-rm": "docker rm a11y-theme-builder",
"format": "prettier --write \"src/**/*.{js,jsx,ts,tsx,css,scss,json,md}\"",
"format:check": "prettier --check \"src/**/*.{js,jsx,ts,tsx,css,scss,json,md}\"",
"lint": "npx eslint .",
"lint:fix": "npx eslint . --fix"
},
Expand Down Expand Up @@ -50,6 +52,7 @@
"@typescript-eslint/parser": "^7.8.0",
"eslint": "^8.57.0",
"eslint-plugin-header": "^3.1.1",
"nodemon": "^3.1.0"
"nodemon": "^3.1.0",
"prettier": "^3.3.2"
}
}
31 changes: 18 additions & 13 deletions code/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@
* Copyright (c) 2023 Discover Financial Services
* Licensed under Apache-2.0 License. See License.txt in the project root for license information
*/
import express, { Request, Response, NextFunction } from "express";
import bodyParser from "body-parser";
import cookieParser from "cookie-parser";
import * as path from "path";
import { Config } from "./config";
import { addAuthMiddleware } from "./auth";
import { registerThemesEndpoint } from "./themesEndpoint";
import express, { Request, Response, NextFunction } from 'express';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import * as path from 'path';
import { Config } from './config';
import { addAuthMiddleware } from './auth';
import { registerThemesEndpoint } from './themesEndpoint';

const cfg = new Config();

Expand All @@ -19,14 +19,19 @@ function allowCrossDomain(req: Request, res: Response, next: NextFunction) {
res.header('Access-Control-Allow-Headers', 'Content-Type');
if (req.method == 'OPTIONS') {
//console.log("OPTIONS headers=",req.headers)
res.header('Access-Control-Max-Age', ""+60 * 60 * 24 * 365);
res.header('Access-Control-Max-Age', '' + 60 * 60 * 24 * 365);
return res.sendStatus(200);
}
next();
};
}

// Error handling middleware
function handleError(err: any, req: Request, res: Response, next: NextFunction) {
// Error handling middleware
function handleError(
err: any,
req: Request,
res: Response,
next: NextFunction
) {
if (err) {
const code = err.scode || 500;
const message = err.msg || err.message;
Expand All @@ -48,7 +53,7 @@ async function createApp(cfg: Config): Promise<express.Application> {
registerThemesEndpoint(app);
app.use(handleError);
app.use(express.static(path.join(__dirname, '../src/ui/build')));
app.get('/*', function(req: Request, res: Response) {
app.get('/*', function (req: Request, res: Response) {
res.sendFile(path.join(__dirname, '../src/ui/build', 'index.html'));
});
return app;
Expand All @@ -63,4 +68,4 @@ async function main() {
});
}

main();
main();
60 changes: 34 additions & 26 deletions code/src/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,61 +2,75 @@
* Copyright (c) 2023 Discover Financial Services
* Licensed under Apache-2.0 License. See License.txt in the project root for license information
*/
import express, { Request, Response, NextFunction } from "express";
import express, { Request, Response, NextFunction } from 'express';

const users: any = {
"user": "password",
"admin": "password",
user: 'password',
admin: 'password',
};

const cookieName = "user";
const cookieName = 'user';

export function addAuthMiddleware(app: express.Application, cfg: any) {

async function authenticate(req: Request, res: Response, next: NextFunction) {
async function authenticate(
req: Request,
res: Response,
next: NextFunction
) {
// const user = req.cookies[cookieName];
// console.log(`cookie ${cookieName} = ${user}`);

if (hasBasicAuthHeader(req)) {
return await basicAuth(req, res, next);
}

console.debug("Sending 401 response with WWW-Authenticate header")
res.setHeader("WWW-Authenticate", "Basic");
console.debug('Sending 401 response with WWW-Authenticate header');
res.setHeader('WWW-Authenticate', 'Basic');
res.sendStatus(401);
}

async function basicAuth(req: Request, res: Response, next: NextFunction) {
try {
const base64Credentials: any = req.headers.authorization?.split(' ')[1];
const credentials = Buffer.from(base64Credentials, 'base64').toString('ascii');
const base64Credentials: any =
req.headers.authorization?.split(' ')[1];
const credentials = Buffer.from(
base64Credentials,
'base64'
).toString('ascii');
const [uid, pwd] = credentials.split(':');
const user = await loginUser(uid, pwd);
(req as any)._ctx = user;
res.cookie(cookieName, user, { maxAge: 86400000, httpOnly: false })
res.cookie(cookieName, user, { maxAge: 86400000, httpOnly: false });
return next();
} catch (e) {
console.debug("Sending 401 response with WWW-Authenticate header")
res.setHeader("WWW-Authenticate", "Basic");
console.debug('Sending 401 response with WWW-Authenticate header');
res.setHeader('WWW-Authenticate', 'Basic');
res.sendStatus(401);
}
}

function hasBasicAuthHeader(req: Request): boolean {
return req.headers.authorization != undefined && req.headers.authorization.indexOf('Basic ') >= 0;
return (
req.headers.authorization != undefined &&
req.headers.authorization.indexOf('Basic ') >= 0
);
}

async function loginUser(uid: string, pwd: string): Promise<any> {
//console.log(`loginUser(${uid}, ${pwd})`)
if (users[uid] == pwd) {
return uid;
}
console.log(`Basic authentication failed for user ${uid}`)
throw new Error("401");
console.log(`Basic authentication failed for user ${uid}`);
throw new Error('401');
}

async function passThrough(req: Request, res: Response, next: NextFunction) {
(req as any)._ctx = "unknown";
async function passThrough(
req: Request,
res: Response,
next: NextFunction
) {
(req as any)._ctx = 'unknown';
next();
}

Expand All @@ -70,14 +84,8 @@ export function addAuthMiddleware(app: express.Application, cfg: any) {
});

if (cfg.authEnabled) {
console.info("Authentication is enabled");
console.info('Authentication is enabled');
} else {
console.info("Authentication is disabled");
console.info('Authentication is disabled');
}

}





14 changes: 6 additions & 8 deletions code/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,20 @@
* Licensed under Apache-2.0 License. See License.txt in the project root for license information
*/
export class Config {

public readonly baseUrl: string;
public readonly corsOrigin: string;
public readonly authEnabled: boolean;

constructor() {
this.baseUrl = getStr("BASE_URL", "http://localhost:3001");
this.corsOrigin = getStr("CORS_ORIGIN", "*");
this.authEnabled = getBool("AUTH_ENABLED", false);
this.baseUrl = getStr('BASE_URL', 'http://localhost:3001');
this.corsOrigin = getStr('CORS_ORIGIN', '*');
this.authEnabled = getBool('AUTH_ENABLED', false);
}

}

function getStr(name: string, def?: string): string {
if (name in process.env) {
return process.env[name] as string;
return process.env[name] as string;
}
if (def !== undefined) {
return def;
Expand All @@ -28,7 +26,7 @@ function getStr(name: string, def?: string): string {

function getBool(name: string, def: boolean): boolean {
if (name in process.env) {
return process.env[name]?.toLowerCase() === "true";
return process.env[name]?.toLowerCase() === 'true';
}
return def;
}
}
Loading