jLinux

Untitled

Dec 28th, 2015
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict';
  2.  
  3. import * as Hapi from 'hapi';
  4. import * as HapiAuthJwt2 from 'hapi-auth-jwt2';
  5.  
  6. const server = new Hapi.Server();
  7.  
  8. server.connection({ host: 'localhost', port: 3000 });
  9.  
  10. const people = { // our "users database"
  11.     1: {
  12.         id: 1,
  13.         name: 'Jen Jones'
  14.     }
  15. };
  16.  
  17. // bring your own validation function
  18. const validate = function (decoded, request, callback) {
  19.     // do your checks to see if the person is valid
  20.     if (!people[decoded.id]) {
  21.         return callback(null, false);
  22.     }
  23.     else {
  24.         return callback(null, true);
  25.     }
  26. };
  27.  
  28. server.register( HapiAuthJwt2, function (err) {
  29.  
  30.     if(err){
  31.         console.log(err);
  32.     }
  33.  
  34.     server.auth.strategy('jwt', 'jwt',
  35.         { key: 'NeverShareYourSecret',        
  36.             validateFunc: validate,          
  37.             verifyOptions: { algorithms: [ 'HS256' ] } // pick a strong algorithm
  38.         });
  39.  
  40.     server.auth.default('jwt');
  41.  
  42.     server.route([
  43.         {
  44.             method: "GET", path: "/", config: { auth: false },
  45.             handler: function(request, reply) {
  46.                 reply({text: 'Token not required'});
  47.             }
  48.         },
  49.         {
  50.             method: 'GET', path: '/restricted', config: { auth: 'jwt' },
  51.             handler: function(request, reply) {
  52.                 reply({text: 'You used a Token!'})
  53.                     .header("Authorization", request.headers.authorization);
  54.             }
  55.         }
  56.     ]);
  57. });
  58.  
  59. server.start(function () {
  60.     console.log('Server running at:', server.info.uri);
  61. });
Advertisement
Add Comment
Please, Sign In to add comment