Skip to content

Commit

Permalink
Merge pull request #249 from salzhrani/v-17
Browse files Browse the repository at this point in the history
hapi v17
  • Loading branch information
nelsonic committed Feb 26, 2018
2 parents 91111ce + 2df67f3 commit 5817d6b
Show file tree
Hide file tree
Showing 31 changed files with 1,183 additions and 1,173 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ lib-cov

# Coverage directory used by tools like istanbul
coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
Expand All @@ -33,3 +34,4 @@ node_modules

# Vagrant VM (temporary files)
.vagrant
package-lock.json
4 changes: 2 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
language: node_js
node_js:
- "6"
- "8"
- "8.9.0"
- "9"
- "node"
env:
- JWT_SECRET="EverythingIsAwesome!"
before_install:
Expand Down
159 changes: 81 additions & 78 deletions README.md

Large diffs are not rendered by default.

55 changes: 30 additions & 25 deletions example/server.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
var Hapi = require('hapi');
var hapiAuthJWT = require('../lib/');
var JWT = require('jsonwebtoken'); // used to sign our content
var port = process.env.PORT || 8000; // allow port to be set
const Hapi = require('hapi');
const hapiAuthJWT = require('../lib/');
const JWT = require('jsonwebtoken'); // used to sign our content
const port = process.env.PORT || 8000; // allow port to be set

var secret = 'NeverShareYourSecret'; // Never Share This! even in private GitHub repos!
const secret = 'NeverShareYourSecret'; // Never Share This! even in private GitHub repos!

var people = {
const people = {
1: {
id: 1,
name: 'Anthony Valid User'
}
};

// use the token as the 'authorization' header in requests
var token = JWT.sign(people[1], secret); // synchronous
const token = JWT.sign(people[1], secret); // synchronous
console.log(token);
// bring your own validation function
var validate = function (decoded, request, callback) {
const validate = async function (decoded, request, h) {
console.log(" - - - - - - - decoded token:");
console.log(decoded);
console.log(" - - - - - - - request info:");
Expand All @@ -26,23 +26,20 @@ var validate = function (decoded, request, callback) {

// do your checks to see if the person is valid
if (!people[decoded.id]) {
return callback(null, false);
return { isValid: false };
}
else {
return callback(null, true);
return { isValid : true };
}
};

var server = new Hapi.Server();
server.connection({ port: port });

server.register(hapiAuthJWT, function (err) {
if(err){
console.log(err);
}
const init = async() => {
const server = new Hapi.Server({ port: port });
await server.register(hapiAuthJWT);
// see: http://hapijs.com/api#serverauthschemename-scheme
server.auth.strategy('jwt', 'jwt',
{ key: secret, validateFunc: validate,
{ key: secret,
validate,
verifyOptions: { ignoreExpiration: true }
});

Expand All @@ -51,20 +48,28 @@ server.register(hapiAuthJWT, function (err) {
server.route([
{
method: "GET", path: "/", config: { auth: false },
handler: function(request, reply) {
reply({text: 'Token not required'});
handler: function(request, h) {
return {text: 'Token not required'};
}
},
{
method: 'GET', path: '/restricted', config: { auth: 'jwt' },
handler: function(request, reply) {
reply({message: 'You used a Valid JWT Token to access /restricted endpoint!'})
.header("Authorization", request.headers.authorization);
handler: function(request, h) {
const response = h.response({message: 'You used a Valid JWT Token to access /restricted endpoint!'});
response.header("Authorization", request.headers.authorization);
return response;
}
}
]);
});
await server.start();
return server;


};

server.start(function () {
init().then(server => {
console.log('Server running at:', server.info.uri);
}).catch(err => {
console.log(err);
});

76 changes: 38 additions & 38 deletions example/simple_server.js
Original file line number Diff line number Diff line change
@@ -1,57 +1,57 @@
var Hapi = require('hapi');
const Hapi = require('hapi');

var people = { // our "users database"
const people = { // our "users database"
1: {
id: 1,
name: 'Jen Jones'
}
};

// bring your own validation function
var validate = function (decoded, request, callback) {
const validate = async function (decoded, request, h) {

// do your checks to see if the person is valid
if (!people[decoded.id]) {
return callback(null, false);
return { valid: false };
}
else {
return callback(null, true);
return { valid: true };
}
};

var server = new Hapi.Server();
server.connection({ port: 8000 });
// include our module here ↓↓
server.register(require('../lib'), function (err) {

if(err){
console.log(err);
}

server.auth.strategy('jwt', 'jwt',
{ key: 'NeverShareYourSecret', // Never Share your secret key
validateFunc: validate // validate function defined above
});

server.auth.default('jwt');

server.route([
{
method: "GET", path: "/", config: { auth: false },
handler: function(request, reply) {
reply({text: 'Token not required'});
}
},
{
method: 'GET', path: '/restricted', config: { auth: 'jwt' },
handler: function(request, reply) {
reply({text: 'You used a Token!'})
.header("Authorization", request.headers.authorization);
}
const init = async () => {
const server = new Hapi.Server({ port: 8000 });
// include our module here ↓↓
await server.register(require('../lib'));
server.auth.strategy('jwt', 'jwt',
{ key: 'NeverShareYourSecret', // Never Share your secret key
validate // validate function defined above
});

server.auth.default('jwt');

server.route([
{
method: "GET", path: "/", config: { auth: false },
handler: function(request, h) {
return {text: 'Token not required'};
}
]);
});

server.start(function () {
},
{
method: 'GET', path: '/restricted', config: { auth: 'jwt' },
handler: function(request, h) {
const response = h.response({text: 'You used a Token!'});
response.header("Authorization", request.headers.authorization);
return response;
}
}
]);
await server.start();
return server;
}
init().then(server => {
console.log('Server running at:', server.info.uri);
})
.catch(err => {
console.log(err);
});
24 changes: 17 additions & 7 deletions lib/extract.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict';

var Cookie = require('cookie'); // highly popular decoupled cookie parser
const Cookie = require('cookie'); // highly popular decoupled cookie parser

/**
* customOrDefaultKey is a re-useable method to determing if the developer
Expand All @@ -24,11 +24,11 @@ function customOrDefaultKey (options, key, _default) {
*/
module.exports = function extract (request, options) {
// The key holding token value in url or cookie defaults to token
var auth, token;
var cookieKey = customOrDefaultKey(options, 'cookieKey', 'token');
var headerKey = customOrDefaultKey(options, 'headerKey', 'authorization');
var urlKey = customOrDefaultKey(options, 'urlKey', 'token');
var pattern = new RegExp(options.tokenType + '\\s+([^$]+)', 'i');
let auth, token;
const cookieKey = customOrDefaultKey(options, 'cookieKey', 'token');
const headerKey = customOrDefaultKey(options, 'headerKey', 'authorization');
const urlKey = customOrDefaultKey(options, 'urlKey', 'token');
const pattern = new RegExp(options.tokenType + '\\s+([^$]+)', 'i');

if (urlKey && request.query[urlKey]) { // tokens via url: https://github.com/dwyl/hapi-auth-jwt2/issues/19
auth = request.query[urlKey];
Expand All @@ -42,7 +42,7 @@ module.exports = function extract (request, options) {
} else if (cookieKey && request.headers.cookie) {
auth = Cookie.parse(request.headers.cookie)[cookieKey];
}

// strip pointless "Bearer " label & any whitespace > http://git.io/xP4F
return auth ? auth.replace(/Bearer/gi, '').replace(/ /g, '') : null;
};
Expand All @@ -55,3 +55,13 @@ module.exports = function extract (request, options) {
module.exports.isValid = function isValid (token) {
return token.split('.').length === 3;
};

/**
* isHeadless is a check to see if the header section of the JWT exists
*
* @param token - the token extracted from Header/Cookie/query
* @returns {boolean} true|false - true if JWT is without a header section, false if it is not
*/
module.exports.isHeadless = function isHeadless(token) {
return token.split('.').length === 2;
};
Loading

0 comments on commit 5817d6b

Please sign in to comment.