From 4ec0237e10e1fb91205a4db1c1a9f36b07639a66 Mon Sep 17 00:00:00 2001 From: ManifoldFR <wilson.jallet@gmail.com> Date: Thu, 30 Aug 2018 23:14:52 +0200 Subject: [PATCH] Charger les configs JS depuis des fichiers locaux, exclus du bundle --- src/admin_view/admin.router.ts | 3 -- src/index.ts | 2 +- src/ldap/config.js | 19 ++++++------ src/server.ts | 56 ++++++++++++++++------------------ webpack.config.js | 10 +++++- 5 files changed, 46 insertions(+), 44 deletions(-) diff --git a/src/admin_view/admin.router.ts b/src/admin_view/admin.router.ts index bad6546..a3c0f7f 100644 --- a/src/admin_view/admin.router.ts +++ b/src/admin_view/admin.router.ts @@ -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'); }); diff --git a/src/index.ts b/src/index.ts index 84a371a..4773230 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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); }); diff --git a/src/ldap/config.js b/src/ldap/config.js index de1801b..91d253a 100644 --- a/src/ldap/config.js +++ b/src/ldap/config.js @@ -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 }; diff --git a/src/server.ts b/src/server.ts index 2b194c2..3153aa6 100644 --- a/src/server.ts +++ b/src/server.ts @@ -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) diff --git a/webpack.config.js b/webpack.config.js index 43d18e4..3369645 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -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', -- GitLab