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

Feature/no msal react #272

Merged
merged 26 commits into from
May 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
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: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
backend/web-bff/App/.env.dev

HELP.md
.gradle
build/
Expand Down
133 changes: 98 additions & 35 deletions backend/web-bff/App/app.js
Original file line number Diff line number Diff line change
@@ -1,66 +1,129 @@
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
require('dotenv').config({path:".env"});

const path = require('path');
const express = require('express');
const session = require('express-session');
const MongoStore = require('connect-mongo');
const createError = require('http-errors');
const logger = require('morgan');

require('dotenv').config();
const rateLimit = require('express-rate-limit')

var path = require('path');
var express = require('express');
var session = require('express-session');
var createError = require('http-errors');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const cors = require('cors')

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var authRouter = require('./routes/auth');
const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const authRouter = require('./routes/auth');
const apiRouter = require('./routes/api');

// initialize express
var app = express();
/**
* Initialize express
*/
const app = express();
const DEVELOPMENT = process.env.ENVIRONMENT === "development";

/**
* Using express-session middleware for persistent user session. Be sure to
* familiarize yourself with available options. Visit: https://www.npmjs.com/package/express-session
* Using cookie-session middleware for persistent user session.
*/
app.use(session({
secret: process.env.EXPRESS_SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
secure: false, // set this to true on production
}
const connection_string = `mongodb://${process.env.DB_USER}:${process.env.DB_PASSWORD}@${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_NAME}`


if (DEVELOPMENT) {
// Use in memory storage for development purposes.
// Keep in mind that when the server shuts down, so does the session information.
app.use(session({
name: 'pigeon session',
secret: process.env.EXPRESS_SESSION_SECRET,
resave: false,
saveUninitialized: false,
// expires: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // 7 days
cookie: {
httpOnly: true,
secure: false, // make sure this is true in production
maxAge: 7 * 24 * 60 * 60 * 1000,
},
//store: MongoStore.create(
// {mongoUrl: connection_string})

}));
} else {
// When using production mode, please make sure a mongodb instance is running and accepting connections
// on port PORT. Also make sure the user exists.
app.use(session({
name: 'pigeon session',
secret: process.env.EXPRESS_SESSION_SECRET,
resave: false,
saveUninitialized: false,
// expires: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // 7 days
cookie: {
httpOnly: true,
secure: true, // make sure this is true in production
maxAge: 7 * 24 * 60 * 60 * 1000,
},
store: MongoStore.create(
{mongoUrl: connection_string})
}));
}


/**
* Initialize the rate limiter.
*
*/
const limiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 4000,
});

// view engine setup
app.use(limiter);

/**
* Initialize the cors protection.
* Requests from our frontend are allowed.
*/
const corsOptions = {
origin: [/localhost/, "https://sel2-6.ugent.be/"],
optionsSuccessStatus: 200,
credentials: true,
}
app.use('*', cors(corsOptions));


// view engine setup for debugging
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

app.use(logger('dev'));
app.use(express.json());
app.use(cookieParser());
app.use(express.urlencoded({ extended: false }));
app.use(express.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, 'public')));

/**
* Make our routes accessible.
*/
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/auth', authRouter);
app.use('/web/users', usersRouter);
app.use('/web/auth', authRouter);
app.use('/web/api', apiRouter)

// catch 404 and forward to error handler
/**
* Catch 404 and forward to error handler.
*/
app.use(function (req, res, next) {
next(createError(404));
});

// error handler
/**
* Error handler.
*/
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.locals.error = DEVELOPMENT ? err : {};

// render the error page
res.status(err.status || 500);
res.render('error');
});

module.exports = app;
module.exports = app;
9 changes: 4 additions & 5 deletions backend/web-bff/App/auth/AuthProvider.js
Original file line number Diff line number Diff line change
Expand Up @@ -105,13 +105,13 @@ class AuthProvider {
req.session.idToken = tokenResponse.idToken;
req.session.account = tokenResponse.account;

res.redirect(options.successRedirect);
next();
} catch (error) {
if (error instanceof msal.InteractionRequiredAuthError) {
return this.login({
scopes: options.scopes || [],
redirectUri: options.redirectUri,
successRedirect: options.successRedirect || '/',
successRedirect: '/',
})(req, res, next);
}

Expand All @@ -125,7 +125,6 @@ class AuthProvider {
if (!req.body || !req.body.state) {
return next(new Error('Error: response not found'));
}

const authCodeRequest = {
...req.session.authCodeRequest,
code: req.body.code,
Expand All @@ -145,7 +144,7 @@ class AuthProvider {
req.session.idToken = tokenResponse.idToken;
req.session.account = tokenResponse.account;
req.session.isAuthenticated = true;

const state = JSON.parse(this.cryptoProvider.base64Decode(req.body.state));
res.redirect(state.successRedirect);
} catch (error) {
Expand Down Expand Up @@ -270,4 +269,4 @@ class AuthProvider {

const authProvider = new AuthProvider(msalConfig);

module.exports = authProvider;
module.exports = authProvider;
14 changes: 7 additions & 7 deletions backend/web-bff/App/authConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,10 @@
* Licensed under the MIT License.
*/

require('dotenv').config({ path: '.env.dev' });
require('dotenv').config({ path: '.env' });

/**
* Configuration object to be passed to MSAL instance on creation.
* For a full list of MSAL Node configuration parameters, visit:
* https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-node/docs/configuration.md
*/
const msalConfig = {
auth: {
Expand All @@ -26,14 +24,16 @@ const msalConfig = {
}
}
}

/**
* Environment constants.
*/
const REDIRECT_URI = process.env.REDIRECT_URI;
const POST_LOGOUT_REDIRECT_URI = process.env.POST_LOGOUT_REDIRECT_URI;
const FRONTEND_URI = process.env.FRONTEND_URI;
const BACKEND_API_ENDPOINT = process.env.BACKEND_API_ENDPOINT;

module.exports = {
msalConfig,
REDIRECT_URI,
POST_LOGOUT_REDIRECT_URI,
FRONTEND_URI,
BACKEND_API_ENDPOINT
};
};
28 changes: 11 additions & 17 deletions backend/web-bff/App/bin/www.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,22 @@
* Module dependencies.
*/

var app = require('../app');
var debug = require('debug')('msal:server');
var http = require('http');
const app = require('../app');
const debug = require('debug')('msal:server');
const http = require('http');


/**
* Get port from environment and store in Express.
*/

var port = normalizePort(process.env.PORT || '3000');
const port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
* Create HTTP server.
*/

var server = http.createServer(app);
const server = http.createServer(app);

/**
* Listen on provided port, on all network interfaces.
Expand All @@ -30,35 +30,30 @@ server.on('error', onError);
server.on('listening', onListening);

/**
* Normalize a port into a number, string, or false.
* Parse port into a number, string, or false.
*/

function normalizePort(val) {
var port = parseInt(val, 10);

let port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}

if (port >= 0) {
// port number
return port;
}

return false;
}

/**
* Event listener for HTTP server "error" event.
*/

function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}

var bind = typeof port === 'string'
let bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;

Expand All @@ -80,10 +75,9 @@ function onError(error) {
/**
* Event listener for HTTP server "listening" event.
*/

function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
let addr = server.address();
let bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
Expand Down
30 changes: 17 additions & 13 deletions backend/web-bff/App/fetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,40 +2,44 @@
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/

var axios = require('axios');
const https = require('https');
const axios = require('axios');
const {BACKEND_API_ENDPOINT} = require("./authConfig");


/**
* Attaches a given access token to a Backend API Call
* @param endpoint REST API endpoint to call
* @param accessToken raw access token string
* @param method The http method for the call. Choice out of 'GET', 'PUT', etc...
* @param body body of request
* @param headers headers of request
*/
async function fetch(endpoint, accessToken) {
async function fetch(endpoint, accessToken, method, body, headers) {
let methods = ["GET", "POST", "PATCH", "PUT", "DELETE"]
if (!(methods.includes(method))) {
throw new Error('Not a valid HTTP method');
}
const url = new URL(endpoint, BACKEND_API_ENDPOINT)
console.log(accessToken)
const headers = {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
const authHeaders = {
"Authorization": `Bearer ${accessToken}`,
}
const finalHeaders = { ...headers, ...authHeaders }

const config= {
method: "GET",
method: method,
url: url.toString(),
headers: headers,
data: body,
headers: finalHeaders,
}

console.log(`request made to ${BACKEND_API_ENDPOINT}/${endpoint} at: ` + new Date().toString());
console.log(`${method} request made to ${BACKEND_API_ENDPOINT}/${endpoint} at: ` + new Date().toString());

try {

const response = await axios(config);
return await response.data;
} catch (error) {
throw new Error(error);
}
}

module.exports = fetch;
module.exports = fetch;
Loading
Loading