Skip to content

Instantly share code, notes, and snippets.

@agsdot
Forked from arb/github_oauth.js
Created October 23, 2016 01:45
Show Gist options
  • Save agsdot/bb7eb94e959e2beb8cf498eba209a947 to your computer and use it in GitHub Desktop.
Save agsdot/bb7eb94e959e2beb8cf498eba209a947 to your computer and use it in GitHub Desktop.
Example hapi server using GitHub OAuth
var Hapi = require('hapi');
var Bell = require('bell');
var AuthCookie = require('hapi-auth-cookie');
var server = new Hapi.Server();
server.connection({ port: 9001 });
server.register([Bell, AuthCookie], function (err) {
if (err) {
console.error(err);
return process.exit(1);
}
var authCookieOptions = {
password: 'cookie-encryption-password', //Password used for encryption
cookie: 'sitepoint-auth', // Name of cookie to set
isSecure: false
};
server.auth.strategy('site-point-cookie', 'cookie', authCookieOptions);
var bellAuthOptions = {
provider: 'github',
password: 'github-encryption-password', //Password used for encryption
clientId: 'xxxxxxxx',//'YourAppId',
clientSecret: 'xxxxxxxx',//'YourAppSecret',
isSecure: false
};
server.auth.strategy('github-oauth', 'bell', bellAuthOptions);
server.auth.default('site-point-cookie');
server.route([
{
method: 'GET',
path: '/',
config: {
auth: {
mode: 'optional'
},
handler: function (request, reply) {
if (request.auth.isAuthenticated) {
return reply('welcome back ' + request.auth.credentials.profile.displayName);
}
reply('hello stranger!');
}
}
}, {
method: 'GET',
path: '/account',
config: {
handler: function (request, reply) {
reply(request.auth.credentials.profile);
}
}
}, {
method: 'GET',
path: '/login',
config: {
auth: 'github-oauth',
handler: function (request, reply) {
if (request.auth.isAuthenticated) {
request.auth.session.set(request.auth.credentials);
return reply('Hello ' + request.auth.credentials.profile.displayName);
}
reply('Not logged in...').code(401);
}
}
}, {
method: 'GET',
path: '/logout',
config: {
auth: false,
handler: function (request, reply) {
request.auth.session.clear();
reply.redirect('/');
}
}
}
]);
server.start(function (err) {
if (err) {
console.error(err);
return process.exit(1);
}
console.log('Server started at %s', server.info.uri);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment