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

[ENH] Configuration to disable authentication #105

Merged
merged 7 commits into from
Jan 18, 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
24 changes: 18 additions & 6 deletions api/auth.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,28 @@
import { Params, expressjwt } from 'express-jwt';
import * as fs from 'fs';
import * as jwt from 'jsonwebtoken';
import * as config from './config';

const pubkey = fs.readFileSync(__dirname + '/auth.pub', 'ascii').trim();
const pubkey = config.authentication ? fs.readFileSync(__dirname + '/auth.pub', 'ascii').trim() : null;
const ezbidsPrivateKey = fs.readFileSync(`${__dirname}/ezbids.key`, 'ascii').trim();
const ezbidsPublicKey = fs.readFileSync(`${__dirname}/ezbids.pub`, 'ascii').trim();

export const validateWithJWTConfig = (options?: Params) => {
return expressjwt({
secret: pubkey,
algorithms: ['RS256'],
...options,
});
if (config.authentication) {
return expressjwt({
secret: pubkey,
algorithms: ['RS256'],
...options,
});
} else {
return (req: any, res: any, next: any) => {
req.auth = {
sub: 0,
};

next();
};
}
};

export const verifyJWT = (jwtToVerify?: string): string | jwt.JwtPayload | undefined => {
Expand Down
2 changes: 2 additions & 0 deletions api/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,5 @@ export const express = {
host: '0.0.0.0',
port: '8082',
};

export const authentication = process.env.BRAINLIFE_AUTHENTICATION === 'true';
3 changes: 1 addition & 2 deletions api/controllers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,10 +100,9 @@ router.get('/health', (req, res) => {
* Session: $ref: '#/components/schemas/Session'
*/
router.post('/session', validateWithJWTConfig(), (req: Request, res: express.Response, next) => {
if (!req.auth.sub) res.sendStatus(HTTP_STATUS.BAD_REQUEST);

req.body.status = 'created';
req.body.request_headers = req.headers;

const session = new models.Session({
...req.body,
ownerId: req.auth.sub,
Expand Down
25 changes: 16 additions & 9 deletions api/controllers.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { NextFunction, Response } from 'express';
import { Request } from 'express-jwt';
import { ISession, Session } from './models';
import { Types, Document } from 'mongoose';
import * as config from './config';

export enum HTTP_STATUS {
OK = 200,
Expand All @@ -28,24 +29,30 @@ export const validateUserCanAccessSession = (onlyOwnerCanAccess: boolean) => {
const sessionId = req.params.session_id;
const userId = req.auth.sub as unknown as number;

if (!sessionId || !userId) {
return res.status(HTTP_STATUS.BAD_REQUEST).json({ err: 'No sessionId or userId found' });
if (!sessionId) {
return res.status(HTTP_STATUS.BAD_REQUEST).json({ err: 'No sessionId found' });
}

if (config.authentication && !userId) {
return res.status(HTTP_STATUS.BAD_REQUEST).json({ err: 'No userId found' });
}

return Session.findById(sessionId)
.then((session) => {
if (!session)
return res
.status(HTTP_STATUS.BAD_REQUEST)
.status(HTTP_STATUS.NOT_FOUND)
.json({ err: 'Could not find session with ID: ' + sessionId });

const isOwner = userId === (session.ownerId || '');
const isInAllowedUserList = session.allowedUsers.some((allowedUser) => allowedUser === userId);
if (config.authentication) {
const isOwner = userId === (session.ownerId || '');
const isInAllowedUserList = session.allowedUsers.some((allowedUser) => allowedUser === userId);

if (onlyOwnerCanAccess && !isOwner) {
return res.status(HTTP_STATUS.UNAUTHORIZED).json({ err: 'unauthorized' });
} else if (!onlyOwnerCanAccess && !isOwner && !isInAllowedUserList) {
return res.status(HTTP_STATUS.UNAUTHORIZED).json({ err: 'unauthorized' });
if (onlyOwnerCanAccess && !isOwner) {
return res.status(HTTP_STATUS.UNAUTHORIZED).json({ err: 'unauthorized' });
} else if (!onlyOwnerCanAccess && !isOwner && !isInAllowedUserList) {
return res.status(HTTP_STATUS.UNAUTHORIZED).json({ err: 'unauthorized' });
}
}

req.ezBIDS = {
Expand Down
15 changes: 15 additions & 0 deletions dev.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,19 @@

set -ex

BRAINLIFE_AUTHENTICATION=true
while getopts "d" flag; do
case $flag in
d)
BRAINLIFE_AUTHENTICATION=false
;;
\?)
;;
esac
done

export BRAINLIFE_AUTHENTICATION

git submodule update --init --recursive

(cd api && npm install)
Expand All @@ -12,6 +25,8 @@ mkdir -p /tmp/workdir

npm run prepare-husky

./generate_keys.sh

# ok docker compose is now included in docker as an option for docker
if [[ $(command -v docker-compose) ]]; then
# if the older version is installed use the dash
Expand Down
2 changes: 2 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ services:
./dev.sh
environment:
MONGO_CONNECTION_STRING: mongodb://mongodb:27017/ezbids
BRAINLIFE_AUTHENTICATION: ${BRAINLIFE_AUTHENTICATION}
ports:
- 8082:8082 #localhost runs on local browser to it needs to access api via host port

Expand Down Expand Up @@ -61,6 +62,7 @@ services:
- ./ui/src:/ui/src #don't copy node_modules which might be compiled for mac (vite won't work)
environment:
VITE_APIHOST: http://localhost:8082
VITE_BRAINLIFE_AUTHENTICATION: ${BRAINLIFE_AUTHENTICATION}
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000"]
ports:
Expand Down
9 changes: 9 additions & 0 deletions generate_keys.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!/bin/bash

set -ex

if [ ! -f api/ezbids.key ]; then
openssl genrsa -out api/ezbids.key 2048
chmod 600 api/ezbids.key
openssl rsa -in api/ezbids.key -pubout > api/ezbids.pub
fi
Loading