Skip to content

Commit

Permalink
#300: BE auth service setup
Browse files Browse the repository at this point in the history
  • Loading branch information
tholulomo committed Feb 19, 2023
1 parent e686d9a commit 9ba0d1b
Show file tree
Hide file tree
Showing 7 changed files with 121 additions and 27 deletions.
11 changes: 6 additions & 5 deletions resfulservice/config/constant.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
module.exports = {
samples: 'https://materialsmine.org/wi/about?view=instances&uri=http://materialsmine.org/ns/PolymerNanocomposite',
articles: 'https://materialsmine.org/wi/about?view=instances&uri=http%3A%2F%2Fmaterialsmine.org%2Fns%2FResearchArticle',
images: 'https://materialsmine.org/wi/about?view=instances&uri=http://semanticscience.org/resource/Image',
charts: 'https://materialsmine.org/wi/about?view=instances&uri=http://semanticscience.org/resource/Chart'
}
samples: 'https://materialsmine.org/wi/about?view=instances&uri=http://materialsmine.org/ns/PolymerNanocomposite',
articles: 'https://materialsmine.org/wi/about?view=instances&uri=http%3A%2F%2Fmaterialsmine.org%2Fns%2FResearchArticle',
images: 'https://materialsmine.org/wi/about?view=instances&uri=http://semanticscience.org/resource/Image',
charts: 'https://materialsmine.org/wi/about?view=instances&uri=http://semanticscience.org/resource/Chart',
supportedBrowser: ['Firefox', 'Chrome', 'Canary', 'Safari', 'Opera', 'IE']
};
1 change: 1 addition & 0 deletions resfulservice/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"nodemailer": "^6.7.2",
"sinon": "^14.0.0",
"swagger-ui-express": "^4.2.0",
"ua-parser-js": "^1.0.33",
"unique-names-generator": "^4.7.1",
"winston": "^3.5.1",
"ws": "^8.7.0"
Expand Down
89 changes: 89 additions & 0 deletions resfulservice/src/controllers/authController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
const User = require('../models/user');
const UAParser = require('ua-parser-js');
const { setInternal } = require('../middlewares/isInternal');
const { successWriter, errorWriter } = require('../utils/logWriter');
const { supportedBrowser } = require('../../config/constant');

// Generate and send token info to FE
const _redirect = ({ _id, email, displayName }, req, res) => {
successWriter(req, 'success', 'Found/Created user successfully');
const token = setInternal(req, { _id, email, displayName });
successWriter(req, 'success', 'Login token generated successfully');
// res.status(200).json({ userId: _id, token, displayName });
return res.redirect(`${req.env.ROUTER}/auth/${JSON.stringify({ userId: _id, token, displayName })}`);
};

// Validate user or create if it does not exists
const _validateUser = async (req) => {
const { logger, env } = req;
logger.info('_validateUser(): Function entry');

const email = req.headers[env.MM_AUTH_EMAIL_HEADER] ?? env.MM_USER_EMAIL;
const userExist = await User.findOne({ email });

if (userExist) return userExist;

const user = new User({
userid: req.headers[env.MM_AUTH_USER_HEADER] ?? 'anon',
email,
givenName: req.headers[env.MM_AUTH_GIVEN_NAME_HEADER] ?? env.MM_USER,
surName: req.headers[env.MM_AUTH_SURNAME_HEADER] ?? env.MM_USER,
displayName: req.headers[env.MM_AUTH_DISPLAYNAME_HEADER] ?? env.MM_USER
});

const savedUser = await user.save();
return savedUser;
};

/**
* Alternative Auth Service for dev purposes
* @param {*} req
* @param {*} res
* @param {*} next
* @returns {*} response
*/
exports.devLoginService = async (req, res, next) => {
const { logger } = req;
logger.info('authenticationService(): Function entry');

try {
const user = await _validateUser(req);
return _redirect(user, req, res);
} catch (err) {
next(errorWriter(req, err, 'authenticationService', 500));
}
};

/**
* Auth Service
* @param {*} req
* @param {*} res
* @param {*} next
* @returns {*} response
*/
exports.authenticationService = async (req, res, next) => {
const { logger, env } = req;
logger.info('authenticationService(): Function entry');

const uaParser = new UAParser();
const userAgent = req.headers['user-agent'];
const browser = uaParser.setUA(userAgent).getBrowser().name;
if (!supportedBrowser.includes(browser)) return res.status(200).json({ message: 'Successful!' });

// 1. Check environment & determine Login type
const currentEnv = req.env.MM_RUNTIME_ENV;
if (currentEnv === 'dev') return this.devLoginService(req, res, next);

try {
// 2. Auth service
if (req.headers[env.MM_AUTH_EMAIL_HEADER]) {
const error = new Error('No user info, auth service failure');
return next(errorWriter(req, error, 'authenticationService', 500));
}

const user = await _validateUser(req);
return _redirect(user, req, res);
} catch (err) {
next(errorWriter(req, err, 'authenticationService', 500));
}
};
23 changes: 8 additions & 15 deletions resfulservice/src/middlewares/isInternal.js
Original file line number Diff line number Diff line change
@@ -1,38 +1,31 @@
const { decodeToken, signToken } = require('../utils/jwtService');
const { errorWriter } = require('../utils/logWriter');

exports.getInternal = (req, res, next) => {
const log = req.logger;
const isInternal = req.get('Authorization')?.split(' ')[1];
let decodedToken;
if (!isInternal) {
log.error('getInternal(): 403 - isInternal not provided. Not authorized');
const error = new Error('Not authorized.');
error.statusCode = 403;
throw error;
throw errorWriter(req, 'Not authorized.', 'getInternal()', 403);
}
try {
decodedToken = decodeToken(req, isInternal);
} catch (err) {
log.error(`getInternal(): 500 - ${err}`);
err.statusCode = 500;
throw err;
throw errorWriter(req, err, 'getInternal()', 500);
}
req.internal = decodedToken;
next();
};

exports.setInternal = (req, res, next) => {
const log = req.logger;
exports.setInternal = (req, payload) => {
let signedToken;
try {
signedToken = signToken(req, {
...payload,
isInternal: true
});

return signedToken;
} catch (err) {
log.error(`getInternal(): 500 - ${err}`);
err.statusCode = 500;
throw err;
throw errorWriter(req, err, 'getInternal()', 500);
}
req.signedToken = signedToken;
next();
};
8 changes: 8 additions & 0 deletions resfulservice/src/routes/authService.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const express = require('express');
const router = express.Router();
const AuthController = require('../controllers/authController');

router.route('/')
.get(AuthController.authenticationService);

module.exports = router;
14 changes: 8 additions & 6 deletions resfulservice/src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,14 @@ const { createServer: createHttpServer } = require('http');
const { WebSocketServer } = require('ws');
const { useServer: useWsServer } = require('graphql-ws/lib/use/ws');
const { globalMiddleWare, log } = require('./middlewares');
const knowledgeRoutes = require('./routes/kg-wrapper');
const adminRoutes = require('./routes/admin');
const searchRoutes = require('./routes/search');
const fileRoutes = require('./routes/files');
const authRoutes = require('./routes/authService');
const elasticSearch = require('./utils/elasticSearch');
const pixelatedRoutes = require('./routes/pixelated');
const fileRoutes = require('./routes/files');
const invalidRoutes = require('./routes/invalid');
const knowledgeRoutes = require('./routes/kg-wrapper');
const pixelatedRoutes = require('./routes/pixelated');
const searchRoutes = require('./routes/search');
const resolvers = require('./graphql/resolver');
const typeDefs = require('./graphql');
const getHttpContext = require('./graphql/context/getHttpContext');
Expand All @@ -24,10 +25,11 @@ const app = express();
globalMiddleWare(app);
elasticSearch.ping(log);

app.use('/knowledge', knowledgeRoutes);
app.use('/admin', adminRoutes);
app.use('/search', searchRoutes);
app.use('/secure', authRoutes);
app.use('/files', fileRoutes);
app.use('/knowledge', knowledgeRoutes);
app.use('/search', searchRoutes);
app.use('/pixelated', pixelatedRoutes);
app.use('/*', invalidRoutes);

Expand Down
2 changes: 1 addition & 1 deletion resfulservice/src/utils/jwtService.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ module.exports = {
signToken: (req, payload) => {
const logger = req.logger;
try {
const signed = jwt.sign(payload, getTkns(req), { expiresIn: req.timer || '8h' });
const signed = jwt.sign(payload, getTkns(req), { expiresIn: req.timer ?? '8h' });
return signed;
} catch (err) {
logger.error(`[signToken]: Failed to sign - ${err}`);
Expand Down

0 comments on commit 9ba0d1b

Please sign in to comment.