Skip to content
Snippets Groups Projects
Commit 4ec0237e authored by Wilson JALLET's avatar Wilson JALLET :money_with_wings:
Browse files

Charger les configs JS depuis des fichiers locaux, exclus du bundle

parent 2d26837c
No related branches found
No related tags found
No related merge requests found
......@@ -26,9 +26,6 @@ let port = process.env.PORT || 3000;
*/
router.get('/', function (req, res) {
console.log("adminview: GET handler for /adminview route");
console.log('adminview: Connecting to ' + req.url);
console.log('adminview: Trying to go to admin page...');
res.redirect('/adminview/admin');
});
......
......@@ -8,5 +8,5 @@ import colors from 'colors';
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(colors.blue(`Express server listening on port ${port}.`));
console.log(colors.blue("Express server listening on port %s."), port);
});
......@@ -2,15 +2,16 @@
* @file Importe la configuration du LDAP au sein de l'application, et remplace certaines valeurs en fonction des variables d'environnement.
* @author manifold
*/
var fs = require('fs');
var path = require('path');
const fs = require('fs');
const path = require('path');
const colors = require('colors');
// Point central ; tous les champs de la BDD sont 'cachés' dans config.json et pas visibles directement
const configPath = path.resolve('./', 'ldap_config.json');
const ldapConfig = JSON.parse(fs.readFileSync(configPath, 'utf8'));
const credentialsPath = path.resolve('./', 'ldap_connexion_config.json');
const credentialsConfig = JSON.parse(fs.readFileSync(credentialsPath, 'utf8'));
const credsPath = path.resolve('./', 'ldap_connexion_config.json');
console.log(colors.cyan("Loading LDAP config file from %s"), configPath);
console.log(colors.cyan("Loading LDAP credentials from %s"), credsPath);
const ldapConfig = JSON.parse(fs.readFileSync(configPath));
const credentialsConfig = JSON.parse(fs.readFileSync(credsPath));
// Override config server from environment
if (process.env.LDAP_URI != null) {
......@@ -18,6 +19,6 @@ if (process.env.LDAP_URI != null) {
}
module.exports = {
"ldapConfig": ldapConfig,
"credentialsConfig": credentialsConfig
ldapConfig,
credentialsConfig
};
......@@ -4,12 +4,11 @@
* La configuration inclut tout le _middleware_ définissant les API et les services
* nécessaire utilisés, comme `express-session`, GraphiQL, GraphQL Voyager.
*
* TODO: changer cette description... ^
* TODD: qu'arrive-t-il aux requetes avec un cookie expire? elles ne sont traitees ni par passport.session() ni par passport.authenticate('ldapauth')...
* @todo changer cette description... ^
* @todo qu'arrive-t-il aux requetes avec un cookie expire? elles ne sont traitees ni par passport.session() ni par passport.authenticate('ldapauth')...
*
* @author manifold, kadabra
*/
*/
import express from 'express';
import bodyParser from 'body-parser';
// packages pour graphql
......@@ -30,7 +29,6 @@ import favicon from 'serve-favicon';
import morgan from 'morgan';
// packages pour pouvoir importer depuis des fichiers de config
import path from 'path';
import fs from 'fs';
import { ldapConfig, credentialsConfig } from './ldap/config';
......@@ -45,11 +43,6 @@ app.use(bodyParser.urlencoded({ //parses bodies of media type "application/x-www
}));
app.use(cookieParser()); //parses Cookie header and populate req.cookies with an object keyed by the cookie names. was necessary for express-session before its v1.5.0. on peut probablement l'enlever desormais.
/**
* @desc TRUCS DIVERS
*/
// cache le fait que l'application tourne sous Express dans le header HTTP.
app.disable('x-powered-by');
// Morgan is middleware for logging requests
......@@ -59,14 +52,10 @@ app.use(favicon(path.resolve('./', 'assets', 'favicon.ico')));
// specifies path to static assets. ......je comprends pas ce que c'est. TODO
app.use('/assets', express.static(path.resolve('./', 'assets')));
/**
* FIN TRUCS DIVERS
*/
/**
* @desc AUTHENTIFICATION POUR LES REQUETES POSSEDANT UN COOKIE ET PROVENANT D'UN UTILISATEUR DEJA AUTHENTIFIE
* Remarque: introduit aussi les middlewares session et passport, qui sont aussi utiles pour l'authentification dans les autres cas.
* Remarque: introduit aussi les middlewares session et passport,
* qui sont aussi utiles pour l'authentification dans les autres cas.
*/
/**
......@@ -76,8 +65,11 @@ app.use('/assets', express.static(path.resolve('./', 'assets')));
/**
/* defines parameters for *session store*. (adds field req.session and do some magic stuff)
* basically, searches for a session matching the received cookie and, if found, adds field req.blasomethingbla containing serialized object representing user (i.e. similar to what passport.serializeUser() could produce)
* @todo it is important to configure this right!!! please check out https://www.npmjs.com/package/express-session and make sure you understand the way session is stored. (en vrai c'est vraiment important...)
* basically, searches for a session matching the received cookie and, if found, adds field req.blasomethingbla containing serialized
* object representing user (i.e. similar to what passport.serializeUser() could produce)
* @todo do this right
* it is important to configure this right!!! please check out https://www.npmjs.com/package/express-session
* and make sure you understand the way session is stored. (en vrai c'est vraiment important...)
*/
app.use(session({
secret: ldapConfig.sessionSecret,
......@@ -85,15 +77,17 @@ app.use('/assets', express.static(path.resolve('./', 'assets')));
saveUninitialized: false,
//store: // TODO: change this. express-session doc warns that default value is ok to use for development only
}));
app.use(passport.initialize()); //initialize Passport. (adds hidden field req._passport and do some magic stuff)
app.use(passport.initialize());
//initialize Passport. (adds hidden field req._passport and do some magic stuff)
//GHETTO
//app.use(passport.session()); //this is equivalent to app.use(passport.authenticate('session'))
//this is equivalent to app.use(passport.authenticate('session'))
app.use(passport.session(), (req, res, next)=>{
console.log("Used passport.session()");
console.log(`passport.session() found user: ${req.user ? req.user.uid : "none"}`);
console.log("passport.session() user is authenticated:", req.isAuthenticated());
console.log(
`passport.session: found user: ${req.user ? req.user.uid : "none"}
authenticated: ${req.isAuthenticated()}`);
next();
}); //this is equivalent to app.use(passport.authenticate('session'))
});
// *aucun* effet sur les requetes n'ayant pas ete reconnues par app.use(session(...)) (e.g. les requetes sans cookie ou les requetes avec cookie expired). source: lecture directe du code passport/lib/strategies/session.js sur github... :/
/*
......@@ -110,7 +104,6 @@ app.use((req, res, next) => {
* i.e. quand l'utilisateur submit le formulaire de login avec ses identifiants/mdp dans le front
* Remarque: configure aussi passport pour l'authentification ldap, ce qui est aussi utile pour les requetes de connexion via ldap venant de adminview
*/
const FRONTEND_SERVER_URL = process.env.FRONTEND_SERVER_URL || 'http://localhost:8888';
// Options de configuration pour le _middleware_ `cors`.
......@@ -163,8 +156,9 @@ app.post('/login', (req, res, next) => {
// return next(err); // handle error? or drop request and answer with res.json()?
}
// If all went well
console.log("| Authentication succeeded! :-)");
// passport.authenticate automatically includes a Set-Cookie HTTP header in the response. The JSON body is just to signal the frontend that all went well
console.log("| Authentication succeeded! :)");
// passport.authenticate automatically includes a Set-Cookie HTTP header in
// the response. The JSON body is just to signal the frontend that all went well
return res.status(200).json({
message: 'Authentication succeeded',
authSucceeded: true
......@@ -202,9 +196,11 @@ app.use('/graphql',
let password;
console.log("Responding to graphql request...");
console.log(`| User: ${req.user ? req.user.uid : "none"}`);
console.log(`| Authorization: ${req.headers.authorization}`);
console.log("| User is authenticated:",req.isAuthenticated());
console.log(`
| User: ${req.user ? req.user.uid : "none"}
| Authorization: ${req.headers.authorization}
| Authenticated: ${req.isAuthenticated()}
`.trim());
if(req.isAuthenticated()) {
console.log("graphql API is receiving a request from an authenticated user! \\o/");
......@@ -220,7 +216,7 @@ app.use('/graphql',
uid = dn.split("=")[1].split(",")[0];
password = passwd;
}
return {
schema,
graphiql: environment == 'development', // gives access to GraphiQL if req comes from browser (je crois)
......
......@@ -11,7 +11,11 @@ const config = {
},
//devtool: 'inline-source-map',
externals: [
nodeExternals()
nodeExternals(),
{
ldapConfig: './ldap_config.json',
credentialsConfig: './ldap_connexion_config.json'
}
],
module: {
......@@ -24,6 +28,10 @@ const config = {
},{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}, {
type: 'javascript/auto',
test: /\.json$/,
use: ['file-loader']
},{
test: /\.(png|jpg|ico)$/,
loader: 'file-loader',
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment