Skip to content

Commit

Permalink
Merge pull request #6 from sandybemonkey/CLEAN_CODE_AND_REPO
Browse files Browse the repository at this point in the history
Refactor files structure and do some little fixes
  • Loading branch information
sandybemonkey committed Aug 10, 2018
2 parents 0844340 + eee4e3f commit 4e36c05
Show file tree
Hide file tree
Showing 27 changed files with 6,097 additions and 454 deletions.
77 changes: 46 additions & 31 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,64 +4,79 @@
*/
import express from 'express';
import logger from 'morgan';
import session from 'express-session';

import userInfosHelper from './helpers/userInfo';
import idHintHelper from './helpers/idHintToken';
import logoutHelper from './helpers/logout';
import authorizationHelper from './helpers/authorization';
import getAccessTokenHelper from './helpers/accessToken';
import { getAuthorizationUrl, getLogoutUrl } from './helpers/utils';
import getAccessToken from './controllers/accessToken';
import getFDData from './controllers/callFD';

const app = express();
const port = process.env.PORT || '3000';

/**
* session config
* @type {{secret: string, cookie: {}, saveUninitialized: boolean, resave: boolean}}
*/
const sessionConfig = {
secret: 'demo secret', // put your own secret
cookie: {},
saveUninitialized: true,
resave: true,
};

// session config for production
if (app.get('env') === 'production') {
app.set('trust proxy', 1); // trust first proxy
sessionConfig.cookie.secure = true; // serve secure cookies
}

if (process.env.NODE_ENV !== 'test') {
app.use(logger('dev'));
}

app.set('view engine', 'ejs');
app.set('port', port);

app.use(express.static('public'));
app.use(session(sessionConfig));


/**
* Routes
*/
// Routes (@see @link{ see https://expressjs.com/en/guide/routing.html }
app.get('/', (req, res) => {
res.render('pages/index');
const isAuth = false;
res.render('pages/index', { isAuth });
});

app.get('/login', (req, res) => {
res.redirect(authorizationHelper.getAuth());
res.redirect(getAuthorizationUrl());
});

app.get('/callback', (req, res) => {
// check if the mandatory Authorization code is there.
if (!req.query.code) {
res.sendStatus(400);
}
getAccessTokenHelper.getAccessToken(res, req.query.code);
getAccessToken(res, req);
});

app.get('/profile', (req, res) => {
/**
* Getting the user informations by calling helpers/userInfo.
* @type {{}}
*/
const user = userInfosHelper.sendUserInfo();
res.render('pages/profile', { user });
const isAuth = true;
const user = req.session.userInfo;
const isFdData = false;
res.render('pages/profile', { user, isAuth, isFdData });
});
app.get('/callFd', (req, res) => {
getFDData(req, res);
});

app.get('/logout', (req, res) => {
res.redirect(logoutHelper.logout());
res.redirect(getLogoutUrl(req));
});

app.get('/end', (req, res) => {
app.get('/logged-out', (req, res) => {
const isAuth = false;
// resetting the id token hint.
idHintHelper.resetHintToken();
res.render('pages/end');
req.session.id_token = null;
req.session.userInfo = null;
res.render('pages/logged-out', { isAuth });
});

const server = app.listen(port);
// Starting server
const port = process.env.PORT || '3000';
const server = app.listen(port, () => {
// eslint-disable-next-line no-console
console.log(`\x1b[32mServer listening on http://localhost:${port}\x1b[0m`);
});

export default server;
5 changes: 2 additions & 3 deletions config/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@
"CLIENT_SECRET": "c48ff5ae96e870f507507555f7bc4dd361d2aac31df219fe6e92bbcca65f73f5",
"SECRET_KEY": "8f373c6e6a48ce0f5931f414b6739e4e0aa82eda20a083dc5c0522b6c691b17b",
"REDIRECT_URL": "http://localhost:3000/callback",
"LOGOUT_REDIRECT_URL": "http://localhost:3000/end",
"LOGOUT_REDIRECT_URL": "http://localhost:3000/logged-out",
"SCOPE": "openid profile birth",
"STATE": "customState11",
"NONCE": "customNone11"
"FD_MOCK_URL": "http://localhost:4000/revenu-fiscal-de-reference"
}
47 changes: 47 additions & 0 deletions controllers/accessToken.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/**
* Helper to get an access token from France Connect.
* @see @link{ https://partenaires.franceconnect.gouv.fr/fcp/fournisseur-service# }
*/
import axios from 'axios';
import querystring from 'querystring';
import getUser from '../helpers/user';
import config from '../config/config.json';

const tokenUrl = config.TOKEN_URL;
const redirectUrl = config.REDIRECT_URL;
const clientId = config.CLIENT_SECRET;
const secretKey = config.SECRET_KEY;

/**
* Init FranceConnect authentication login process.
* Make every http call to the different API endpoints.
*/
const getAccessToken = async (res, req) => {
// Set request params.
const url = tokenUrl;
const body = {
grant_type: 'authorization_code',
redirect_uri: redirectUrl,
client_id: clientId,
client_secret: secretKey,
code: req.query.code,
};
const headerConfig = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
};

// Request access token.
await axios.post(url, querystring.stringify(body), headerConfig)
.then(response => response.data)
.then((tokenData) => {
req.accessToken = tokenData.access_token;
req.session.id_token = tokenData.id_token;
// Make a call to the France Connect API endpoint to get user data.
getUser(req, res);
})
.catch(err => res.send(err.message));
};

export default getAccessToken;
43 changes: 43 additions & 0 deletions controllers/callFD.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
* Use to send the access token to an data provider.
* @return Response with the queried data from the provider.
* @see @link{ https://partenaires.franceconnect.gouv.fr/fcp/fournisseur-donnees }
* @see @link{ https://github.com/france-connect/data-providers-examples }
*/
import axios from 'axios/index';
import config from '../config/config.json';

const fdMockUrl = config.FD_MOCK_URL;
// this value is only for a demo purpose you should use the Access token send by FC
const fakeAccessToken = '9af033eb295d0fe113988d29a26527f920114973b3a1ca7bdb44768fd0c73937';

const getFDData = (req, res) => {
axios({
method: 'GET',
/**
* only valid used with dat-providers-example code from France Connect repo.
* If use using your code change the url's value.
*/
url: fdMockUrl,
headers: { Authorization: `Bearer ${fakeAccessToken}` },
})
.then((fdResponse) => {
const isFdData = true;
const isAuth = true;
const user = req.session.userInfo;
const dgfipData = [];
const responsedata = fdResponse.data;

for (const property in responsedata) {
if (property !== null) {
dgfipData[property] = fdResponse.data[property];
}
}
res.render('pages/profile', {
user, isAuth, isFdData, dgfipData,
});
})
.catch(err => res.send(err.message));
};

export default getFDData;
70 changes: 0 additions & 70 deletions helpers/accessToken.js

This file was deleted.

9 changes: 0 additions & 9 deletions helpers/authorization.js

This file was deleted.

29 changes: 0 additions & 29 deletions helpers/idHintToken.js

This file was deleted.

13 changes: 0 additions & 13 deletions helpers/logout.js

This file was deleted.

14 changes: 9 additions & 5 deletions helpers/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,26 @@
*/

import axios from 'axios';
import userInfosHelper from './userInfo';
import config from '../config/config.json';

exports.getUser = async (token, res) => {
if (!token) res.sendStatus(401);
const getUser = async (req, res) => {
if (!req.accessToken) {
res.status(401).send('Access token is required');
return;
}
// Set request header
const headerConfig = {
headers: {
Authorization: `Bearer ${token}`,
Authorization: `Bearer ${req.accessToken}`,
},
};
await axios.get(config.USERINFO_URL, headerConfig)
.then((response) => {
// Helper to set userInfo value available to the profile page.
userInfosHelper.getUserInfo(response.data);
req.session.userInfo = response.data;

res.redirect('profile');
})
.catch(err => res.send(err.message));
};
export default getUser;
26 changes: 0 additions & 26 deletions helpers/userInfo.js

This file was deleted.

0 comments on commit 4e36c05

Please sign in to comment.