token.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. 'use strict';
  2. const _ = require('lodash');
  3. const error = require('../lib/error');
  4. const userModel = require('../models/user');
  5. const authModel = require('../models/auth');
  6. const helpers = require('../lib/helpers');
  7. const TokenModel = require('../models/token');
  8. module.exports = {
  9. /**
  10. * @param {Object} data
  11. * @param {String} data.identity
  12. * @param {String} data.secret
  13. * @param {String} [data.scope]
  14. * @param {String} [data.expiry]
  15. * @param {String} [issuer]
  16. * @returns {Promise}
  17. */
  18. getTokenFromEmail: (data, issuer) => {
  19. let Token = new TokenModel();
  20. data.scope = data.scope || 'user';
  21. data.expiry = data.expiry || '30d';
  22. return userModel
  23. .query()
  24. .where('email', data.identity)
  25. .andWhere('is_deleted', 0)
  26. .andWhere('is_disabled', 0)
  27. .first()
  28. .then(user => {
  29. if (user) {
  30. // Get auth
  31. return authModel
  32. .query()
  33. .where('user_id', '=', user.id)
  34. .where('type', '=', 'password')
  35. .first()
  36. .then(auth => {
  37. if (auth) {
  38. return auth.verifyPassword(data.secret)
  39. .then(valid => {
  40. if (valid) {
  41. if (data.scope !== 'user' && _.indexOf(user.roles, data.scope) === -1) {
  42. // The scope requested doesn't exist as a role against the user,
  43. // you shall not pass.
  44. throw new error.AuthError('Invalid scope: ' + data.scope);
  45. }
  46. // Create a moment of the expiry expression
  47. let expiry = helpers.parseDatePeriod(data.expiry);
  48. if (expiry === null) {
  49. throw new error.AuthError('Invalid expiry time: ' + data.expiry);
  50. }
  51. return Token.create({
  52. iss: issuer || 'api',
  53. attrs: {
  54. id: user.id
  55. },
  56. scope: [data.scope]
  57. }, {
  58. expiresIn: expiry.unix()
  59. })
  60. .then(signed => {
  61. return {
  62. token: signed.token,
  63. expires: expiry.toISOString()
  64. };
  65. });
  66. } else {
  67. throw new error.AuthError('Invalid password');
  68. }
  69. });
  70. } else {
  71. throw new error.AuthError('No password auth for user');
  72. }
  73. });
  74. } else {
  75. throw new error.AuthError('No relevant user found');
  76. }
  77. });
  78. },
  79. /**
  80. * @param {Access} access
  81. * @param {Object} [data]
  82. * @param {String} [data.expiry]
  83. * @param {String} [data.scope] Only considered if existing token scope is admin
  84. * @returns {Promise}
  85. */
  86. getFreshToken: (access, data) => {
  87. let Token = new TokenModel();
  88. data = data || {};
  89. data.expiry = data.expiry || '30d';
  90. if (access && access.token.get('attrs').id) {
  91. // Create a moment of the expiry expression
  92. let expiry = helpers.parseDatePeriod(data.expiry);
  93. if (expiry === null) {
  94. throw new error.AuthError('Invalid expiry time: ' + data.expiry);
  95. }
  96. let token_attrs = {
  97. id: access.token.get('attrs').id
  98. };
  99. // Only admins can request otherwise scoped tokens
  100. let scope = access.token.get('scope');
  101. if (data.scope && access.token.hasScope('admin')) {
  102. scope = [data.scope];
  103. if (data.scope === 'job-board' || data.scope === 'worker') {
  104. token_attrs.id = 0;
  105. }
  106. }
  107. return Token.create({
  108. iss: 'api',
  109. scope: scope,
  110. attrs: token_attrs
  111. }, {
  112. expiresIn: expiry.unix()
  113. })
  114. .then(signed => {
  115. return {
  116. token: signed.token,
  117. expires: expiry.toISOString()
  118. };
  119. });
  120. } else {
  121. throw new error.AssertionFailedError('Existing token contained invalid user data');
  122. }
  123. },
  124. /**
  125. * @param {Object} user
  126. * @returns {Promise}
  127. */
  128. getTokenFromUser: user => {
  129. let Token = new TokenModel();
  130. let expiry = helpers.parseDatePeriod('1d');
  131. return Token.create({
  132. iss: 'api',
  133. attrs: {
  134. id: user.id
  135. },
  136. scope: ['user']
  137. }, {
  138. expiresIn: expiry.unix()
  139. })
  140. .then(signed => {
  141. return {
  142. token: signed.token,
  143. expires: expiry.toISOString(),
  144. user: user
  145. };
  146. });
  147. }
  148. };