Guest User

Untitled

a guest
Aug 7th, 2018
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.27 KB | None | 0 0
  1. const axios = require('axios');
  2. const queryString = require('querystring');
  3. const config = require('../config/config');
  4. const jwt = require('jsonwebtoken');
  5. const loggingController = require('./loggingController');
  6. const forumController = require('./forumController');
  7. const appSettingsController = require('./applicationSettingsController');
  8. const RolePermission = require('../models/RolePermission');
  9.  
  10. let groups = null;
  11.  
  12. exports.login = async (req, res) => {
  13. try {
  14. const authInfo = req.body;
  15. const accessToken = await getAccessToken(
  16. authInfo.username,
  17. authInfo.password
  18. );
  19.  
  20. let tokenResponse = null;
  21. if (accessToken) {
  22. tokenResponse = await createJwt(accessToken);
  23. }
  24.  
  25. res.status(200).send({
  26. auth: true,
  27. token: tokenResponse[0],
  28. name: tokenResponse[1]
  29. });
  30. } catch (err) {
  31. if (err.status === 401) {
  32. return res.status(401).send({
  33. auth: false,
  34. name: 'InvalidLogin'
  35. });
  36. } else {
  37. loggingController.logError(err);
  38. res.status(500).send({ message: err.message, stack: err.stack });
  39. }
  40. }
  41. };
  42.  
  43. exports.unravelPayload = (req, res, next) => {
  44. const token = req.headers['x-access-token'];
  45. let payload = null;
  46. if (token) payload = decodeToken(token);
  47. req.tokenPayload = payload;
  48. };
  49.  
  50. exports.authorize = (req, res, next) => {
  51. const token = req.headers['x-access-token'];
  52. if (!token) res.status(401).send('Unauthorized');
  53. else req.tokenPayload = decodeToken(token);
  54. next();
  55. };
  56.  
  57. exports.getUserGroups = (req, res) => {
  58. const response = [];
  59. if (req.tokenPayload) {
  60. req.tokenPayload.otherMemberGroups.forEach(group => response.push(group));
  61. response.push(req.tokenPayload.memberGroupId);
  62. }
  63. res.send(response);
  64. };
  65.  
  66. exports.getUserName = (req, res) => {
  67. let response = null;
  68. if (req.tokenPayload) {
  69. response = JSON.stringify(req.tokenPayload.name);
  70. }
  71. res.send(response);
  72. };
  73.  
  74. exports.getAllPermissionsForRoles = async (req, res) => {
  75. try {
  76. groups = await forumController.getGroupsFromForums();
  77. const rolePermissions = await RolePermission.findAll();
  78. const response = rolePermissions.map(mapGroupIdsToGroups);
  79. res.send(response);
  80. } catch (err) {
  81. loggingController.logError(err);
  82. res.status(500).send({ message: err.message, stack: err.stack });
  83. }
  84. };
  85.  
  86. decodeToken = token => {
  87. return jwt.verify(token, config.secret, (err, decoded) => {
  88. if (err)
  89. return res.status(500).send({
  90. err: err,
  91. auth: false,
  92. message: 'Failed to authenticate token',
  93. name: 'InternalServerError'
  94. });
  95.  
  96. return decoded;
  97. });
  98. };
  99.  
  100. getAccessToken = async (username, password) => {
  101. const clientId = await appSettingsController.findOneApplicationSettingByKey(
  102. 'forumClientId'
  103. );
  104. const clientSecret = await appSettingsController.findOneApplicationSettingByKey(
  105. 'forumClientSecret'
  106. );
  107. const authTokenUrl = await appSettingsController.findOneApplicationSettingByKey(
  108. 'forumAuthTokenUrl'
  109. );
  110. const resp = await axios.post(
  111. authTokenUrl,
  112. queryString.stringify({
  113. username: username,
  114. password: password,
  115. client_id: clientId,
  116. client_secret: clientSecret,
  117. grant_type: 'password',
  118. scope: 'manager'
  119. })
  120. );
  121.  
  122. if (resp.data && resp.data.error && resp.data.error === 'invalid_grant') {
  123. let err = {
  124. message: 'Invalid Login',
  125. status: '401'
  126. };
  127. throw err;
  128. } else if (resp.data && resp.data.error) {
  129. throw new Error('An error occurred during authorization to the forums');
  130. }
  131.  
  132. return resp.data.access_token;
  133. };
  134.  
  135. createJwt = async accessToken => {
  136. const apiUrl = await appSettingsController.findOneApplicationSettingByKey(
  137. 'forumApiUrl'
  138. );
  139. const apiKey = await appSettingsController.findOneApplicationSettingByKey(
  140. 'forumApiKey'
  141. );
  142. const clientTokenExpiration = await appSettingsController.findOneApplicationSettingByKey(
  143. 'clientTokenExpiration'
  144. );
  145.  
  146. let authenticatedMemberId = -1;
  147. let authenticatedMember = null;
  148. const oauthMemberResponse = await axios.get(`${apiUrl}/core/me`, {
  149. headers: {
  150. Authorization: `Bearer ${accessToken}`
  151. }
  152. });
  153.  
  154. authenticatedMemberId = oauthMemberResponse.data.id;
  155.  
  156. if (authenticatedMemberId > -1) {
  157. const authenticatedMemberResponse = await axios.get(
  158. `${apiUrl}/core/members/${authenticatedMemberId}?key=${apiKey}`
  159. );
  160. authenticatedMember = authenticatedMemberResponse.data;
  161. }
  162. let token = null;
  163. if (authenticatedMember) {
  164. token = jwt.sign(
  165. {
  166. id: authenticatedMember.id,
  167. memberGroupId: authenticatedMember.primaryGroup.id.toString(),
  168. otherMemberGroups: authenticatedMember.secondaryGroups.map(x =>
  169. x.id.toString()
  170. ),
  171. name: authenticatedMember.name,
  172. email: authenticatedMember.email
  173. },
  174. config.secret,
  175. {
  176. expiresIn: clientTokenExpiration
  177. }
  178. );
  179. }
  180.  
  181. return [token, authenticatedMember.name];
  182. };
  183.  
  184. mapGroupIdsToGroups = entity => {
  185. let responseModel = {
  186. id: entity.id,
  187. name: entity.name,
  188. description: entity.description,
  189. groups: [],
  190. createdAt: entity.createdAt,
  191. updatedAt: entity.updatedAt
  192. };
  193.  
  194. const groupIdsArray = entity.groupIds ? entity.groupIds.split(',') : [];
  195. responseModel.groups = groups.filter(x =>
  196. groupIdsArray.includes(x.id.toString())
  197. );
  198.  
  199. return responseModel;
  200. };
Add Comment
Please, Sign In to add comment