Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const axios = require('axios');
- const queryString = require('querystring');
- const config = require('../config/config');
- const jwt = require('jsonwebtoken');
- const loggingController = require('./loggingController');
- const forumController = require('./forumController');
- const appSettingsController = require('./applicationSettingsController');
- const RolePermission = require('../models/RolePermission');
- let groups = null;
- exports.login = async (req, res) => {
- try {
- const authInfo = req.body;
- const accessToken = await getAccessToken(
- authInfo.username,
- authInfo.password
- );
- let tokenResponse = null;
- if (accessToken) {
- tokenResponse = await createJwt(accessToken);
- }
- res.status(200).send({
- auth: true,
- token: tokenResponse[0],
- name: tokenResponse[1]
- });
- } catch (err) {
- if (err.status === 401) {
- return res.status(401).send({
- auth: false,
- name: 'InvalidLogin'
- });
- } else {
- loggingController.logError(err);
- res.status(500).send({ message: err.message, stack: err.stack });
- }
- }
- };
- exports.unravelPayload = (req, res, next) => {
- const token = req.headers['x-access-token'];
- let payload = null;
- if (token) payload = decodeToken(token);
- req.tokenPayload = payload;
- };
- exports.authorize = (req, res, next) => {
- const token = req.headers['x-access-token'];
- if (!token) res.status(401).send('Unauthorized');
- else req.tokenPayload = decodeToken(token);
- next();
- };
- exports.getUserGroups = (req, res) => {
- const response = [];
- if (req.tokenPayload) {
- req.tokenPayload.otherMemberGroups.forEach(group => response.push(group));
- response.push(req.tokenPayload.memberGroupId);
- }
- res.send(response);
- };
- exports.getUserName = (req, res) => {
- let response = null;
- if (req.tokenPayload) {
- response = JSON.stringify(req.tokenPayload.name);
- }
- res.send(response);
- };
- exports.getAllPermissionsForRoles = async (req, res) => {
- try {
- groups = await forumController.getGroupsFromForums();
- const rolePermissions = await RolePermission.findAll();
- const response = rolePermissions.map(mapGroupIdsToGroups);
- res.send(response);
- } catch (err) {
- loggingController.logError(err);
- res.status(500).send({ message: err.message, stack: err.stack });
- }
- };
- decodeToken = token => {
- return jwt.verify(token, config.secret, (err, decoded) => {
- if (err)
- return res.status(500).send({
- err: err,
- auth: false,
- message: 'Failed to authenticate token',
- name: 'InternalServerError'
- });
- return decoded;
- });
- };
- getAccessToken = async (username, password) => {
- const clientId = await appSettingsController.findOneApplicationSettingByKey(
- 'forumClientId'
- );
- const clientSecret = await appSettingsController.findOneApplicationSettingByKey(
- 'forumClientSecret'
- );
- const authTokenUrl = await appSettingsController.findOneApplicationSettingByKey(
- 'forumAuthTokenUrl'
- );
- const resp = await axios.post(
- authTokenUrl,
- queryString.stringify({
- username: username,
- password: password,
- client_id: clientId,
- client_secret: clientSecret,
- grant_type: 'password',
- scope: 'manager'
- })
- );
- if (resp.data && resp.data.error && resp.data.error === 'invalid_grant') {
- let err = {
- message: 'Invalid Login',
- status: '401'
- };
- throw err;
- } else if (resp.data && resp.data.error) {
- throw new Error('An error occurred during authorization to the forums');
- }
- return resp.data.access_token;
- };
- createJwt = async accessToken => {
- const apiUrl = await appSettingsController.findOneApplicationSettingByKey(
- 'forumApiUrl'
- );
- const apiKey = await appSettingsController.findOneApplicationSettingByKey(
- 'forumApiKey'
- );
- const clientTokenExpiration = await appSettingsController.findOneApplicationSettingByKey(
- 'clientTokenExpiration'
- );
- let authenticatedMemberId = -1;
- let authenticatedMember = null;
- const oauthMemberResponse = await axios.get(`${apiUrl}/core/me`, {
- headers: {
- Authorization: `Bearer ${accessToken}`
- }
- });
- authenticatedMemberId = oauthMemberResponse.data.id;
- if (authenticatedMemberId > -1) {
- const authenticatedMemberResponse = await axios.get(
- `${apiUrl}/core/members/${authenticatedMemberId}?key=${apiKey}`
- );
- authenticatedMember = authenticatedMemberResponse.data;
- }
- let token = null;
- if (authenticatedMember) {
- token = jwt.sign(
- {
- id: authenticatedMember.id,
- memberGroupId: authenticatedMember.primaryGroup.id.toString(),
- otherMemberGroups: authenticatedMember.secondaryGroups.map(x =>
- x.id.toString()
- ),
- name: authenticatedMember.name,
- email: authenticatedMember.email
- },
- config.secret,
- {
- expiresIn: clientTokenExpiration
- }
- );
- }
- return [token, authenticatedMember.name];
- };
- mapGroupIdsToGroups = entity => {
- let responseModel = {
- id: entity.id,
- name: entity.name,
- description: entity.description,
- groups: [],
- createdAt: entity.createdAt,
- updatedAt: entity.updatedAt
- };
- const groupIdsArray = entity.groupIds ? entity.groupIds.split(',') : [];
- responseModel.groups = groups.filter(x =>
- groupIdsArray.includes(x.id.toString())
- );
- return responseModel;
- };
Add Comment
Please, Sign In to add comment