Advertisement
Guest User

Untitled

a guest
Jan 14th, 2016
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict'
  2.  
  3. import * as jwt from 'jsonwebtoken'
  4. import * as HapiAuthJwt from 'hapi-auth-jwt'
  5. import * as Bcrypt from 'bcrypt'
  6.  
  7. const privateKey = 'YourApplicationsPrivateKey'
  8.  
  9. const accounts = {
  10.     john: { // eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImpvaG4iLCJpYXQiOjE0NTI3MDczMTJ9.ql2-znt55Ct6ApgJQKrRea2dfrLO85yL_poYPHNIZe8
  11.         id: 123,
  12.         username: 'john',
  13.         password: '$2a$10$iqJSHD.BGr0E2IxQwYgJmeP3NvhPrXAeLSaGCj6IR/XU5QtjVu5Tm',   // 'secret'
  14.         fullName: 'John Q Public'
  15.     }
  16. }
  17.  
  18. const token = jwt.sign({ username: 'john' }, privateKey, { algorithm: 'HS256'})
  19.  
  20. console.log(`TOKEN: ${token}`)
  21.  
  22. const validateJwt = (request, decodedToken, callback) => {
  23.  
  24.     console.log(decodedToken)  // should be {accountId : 123}.
  25.  
  26.     if (decodedToken)
  27.         console.log(decodedToken.username.toString())
  28.  
  29.     const account = accounts[decodedToken.username]
  30.  
  31.     if (!account)
  32.         return callback(null, false)
  33.  
  34.     return callback( null, true, account )
  35. }
  36.  
  37. const validateBasic = function (request, username, password, callback) {
  38.  
  39.     const user = accounts[username]
  40.    
  41.     if (!user)
  42.         return callback(null, false);
  43.  
  44.     Bcrypt.compare(password, user.password, (err, isValid) => {
  45.         callback(err, isValid, {
  46.             id: user.id,
  47.             name: user.fullName,
  48.             username: username,
  49.             token: jwt.sign({ username: username }, privateKey, { algorithm: 'HS256'})
  50.         });
  51.     });
  52. };
  53.  
  54. /**
  55.  * To test:
  56.  * curl -v -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhY2NvdW50SWQiOjEyMywiaWF0IjoxMzkyNTg2NzgwfQ.nZT1lsYoJvudjEYodUdgPR-32NNHk7uSnIHeIHY5se0" http://localhost:8000/tokenRequired echo
  57.  */
  58.  
  59. exports.register = ( server, options, next ) => {
  60.  
  61.     server.register(require('hapi-auth-basic'), (err) => {
  62.  
  63.         server.auth.strategy('simple', 'basic', { validateFunc: validateBasic })
  64.  
  65.     })
  66.  
  67.     server.register(HapiAuthJwt, () => {
  68.  
  69.         server.auth.strategy('token', 'jwt', {
  70.             key: privateKey,
  71.             validateFunc: validateJwt,
  72.             verifyOptions: { algorithms: [ 'HS256' ] }
  73.         })
  74.     })
  75.  
  76.     next()
  77. }
  78.  
  79. exports.register.attributes = {
  80.     pkg: {
  81.         name: "jwt_auth",
  82.         version: "0.1.0"
  83.     }
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement