Guest User

Untitled

a guest
Oct 16th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1. "use strict";
  2.  
  3. var restify = require("restify");
  4.  
  5. var users = require("./users");
  6. // The users module will have a getAuthorizationFromAccessTokenAsync promise-returning export. (Convert to callbacks if you wish).
  7. // It rejects in cause of not authorized, or fulfills with a { scope, customerId } object if the user is authorized.
  8. // The scope property indicates which scopes the user corresponding to a given access token has.
  9.  
  10. module.exports = function authPlugin(serverRequest, serverResponse, next) {
  11. var isBearer = serverRequest.authorization && serverRequest.authorization.scheme === "Bearer";
  12.  
  13. function isPrivateRequest() {
  14. // TODO write your own custom logic here.
  15. }
  16.  
  17. function isRequestOutOfScope(scopes) {
  18. // TODO write your own custom logic here.
  19. }
  20.  
  21. function send401Response(message) {
  22. // We are using the HAL hypertext JSON spec to indicate links you should follow,
  23. // but sent whatever 401 you want.
  24. serverResponse.header("WWW-Authenticate", 'Bearer realm="Who goes there?"');
  25. serverResponse.header("Content-Type", "application/hal+json");
  26.  
  27. next(new restify.UnauthorizedError(message, {
  28. _links: { "oauth2-token": { href: "/token" } }, // TODO: write your own code to pull from the routing table
  29. message: message
  30. }));
  31. }
  32.  
  33. function send403Response(message) {
  34. next(new restify.ForbiddenError(message));
  35. }
  36.  
  37. function auth(bearerToken) {
  38. if (!bearerToken) {
  39. send401Response("Bearer authorization credentials are missing or invalid.");
  40. return;
  41. }
  42.  
  43. serverRequest.pause();
  44.  
  45. users.getAuthorizationFromAccessTokenAsync(bearerToken).then(
  46. function (authorizationDetails) {
  47. if (isRequestOutOfScope(authorizationDetails.scope)) {
  48. send403Response("Request is out of scope.");
  49. return;
  50. }
  51.  
  52. serverRequest.customerId = authorizationDetails.customerId;
  53. next();
  54. serverRequest.resume();
  55. },
  56. function (error) {
  57. send401Response(error.message);
  58. }
  59. ).end();
  60. }
  61.  
  62. if (isPrivateRequest()) {
  63. return isBearer ? auth(serverRequest.authorization.credentials) :
  64. send401Response("Bearer token required. Follow the oauth2-token link to get it!");
  65. }
  66.  
  67. return next();
  68. };
Add Comment
Please, Sign In to add comment