Start on Grant / oAUTH flow

This commit is contained in:
rijkvanzanten
2020-06-23 17:30:47 -04:00
parent 6c2daebf30
commit f8d64dab39
7 changed files with 334 additions and 5 deletions

View File

@@ -1,7 +1,10 @@
import { Router } from 'express';
import session from 'express-session';
import asyncHandler from 'express-async-handler';
import Joi from '@hapi/joi';
import * as AuthService from '../services/auth';
import grant from 'grant';
import getGrantConfig from '../utils/get-grant-config';
const router = Router();
@@ -24,4 +27,19 @@ router.post(
})
);
router.use('/sso', session({ secret: process.env.SECRET, saveUninitialized: true, resave: false }));
router.use(grant.express()(getGrantConfig()));
router.get('/sso/:provider/callback', (req, res) => {
console.log(req.session.grant);
/**
* @TODO
*
*/
res.send(req.session.grant);
});
export default router;

4
src/types/grant.d.ts vendored Normal file
View File

@@ -0,0 +1,4 @@
declare module 'grant' {
const grant: any;
export default grant;
}

View File

@@ -0,0 +1,24 @@
import { get } from 'lodash';
// The path in JSON to fetch the email address from the profile.
const profileMap = {
github: 'email',
};
/**
* Extract the email address from a given user profile coming from a providers API
*
* Falls back to OAUTH_<PROVIDER>_PROFILE_EMAIL if we don't have it preconfigured yet
*
* This is used in the SSO flow to extract the users
*/
export default function getEmailFromProfile(provider: string, profile: Record<string, any>) {
const path =
profileMap[provider] || process.env[`OAUTH_${provider.toUpperCase()}_PROFILE_EMAIL`];
if (!path) {
throw new Error('Path to email in profile object is unknown.');
}
return get(profile, path);
}

View File

@@ -0,0 +1,38 @@
/**
* Reads the environment variables to construct the configuration object required by Grant
*/
export default function getGrantConfig() {
const enabledProviders = process.env.OAUTH_PROVIDERS.split(',').map((provider) =>
provider.trim()
);
const config: any = {
defaults: {
origin: process.env.PUBLIC_URL,
transport: 'session',
prefix: '/auth/sso',
response: ['tokens', 'profile'],
},
};
for (const [key, value] of Object.entries(process.env)) {
if (key.startsWith('OAUTH') === false) continue;
const parts = key.split('_');
const provider = parts[1].toLowerCase();
if (enabledProviders.includes(provider) === false) continue;
// OAUTH <PROVIDER> SETTING = VALUE
parts.splice(0, 2);
const configKey = parts.join('_').toLowerCase();
config[provider] = {
...(config[provider] || {}),
[configKey]: value,
};
}
return config;
}