├── .travis.yml ├── .gitignore ├── AUTHORS ├── History.md ├── Makefile ├── test ├── support │ └── server.js └── koa-github.test.js ├── example.js ├── package.json ├── LICENSE ├── README.md └── index.js /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - '0.11' 4 | script: make test 5 | 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | coverage 2 | *.seed 3 | *.log 4 | *.csv 5 | *.dat 6 | *.out 7 | *.pid 8 | *.gz 9 | 10 | pids 11 | logs 12 | results 13 | 14 | npm-debug.log 15 | node_modules 16 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | # Ordered by date of first contribution. 2 | # Auto-generated by 'contributors' on Wed, 01 Jan 2014 16:08:04 GMT. 3 | # https://github.com/xingrz/node-contributors 4 | 5 | dead_horse (https://github.com/dead-horse) 6 | -------------------------------------------------------------------------------- /History.md: -------------------------------------------------------------------------------- 1 | 2 | 0.0.5 / 2014-03-12 3 | ================== 4 | 5 | * use istanbul, remove unused dependencies 6 | * Merge pull request #1 from zdalniacy/master 7 | * Merge pull request #1 from zdalniacy/patch-1 8 | * Fixing coveralls for koa-github 9 | 10 | 0.0.4 / 2014-01-08 11 | ================== 12 | 13 | * use utility 14 | * add travis.yml 15 | * add bundge 16 | 17 | 0.0.3 / 2014-01-02 18 | ================== 19 | 20 | * support redirect 21 | * remove redirectPath 22 | * update denpendencies 23 | * remove devDependencies co 24 | * add test 25 | * use assert 26 | * add authors 27 | 28 | 0.0.2 / 2014-01-01 29 | ================== 30 | 31 | * add readme 32 | 33 | 0.0.1 / 2014-01-01 34 | ================== 35 | 36 | * add example 37 | * add github auth koa middleware 38 | * Initial commit 39 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | TESTS = test/*.test.js 2 | REPORTER = spec 3 | TIMEOUT = 5000 4 | MOCHA_OPTS = 5 | NPM_INSTALL = npm install --registry=http://registry.cnpmjs.org --cache=${HOME}/.npm/.cache/cnpm --disturl=http://dist.u.qiniudn.com 6 | 7 | install: 8 | @$(NPM_INSTALL) 9 | 10 | test: 11 | @NODE_ENV=test ./node_modules/mocha/bin/mocha \ 12 | --harmony-generators \ 13 | --reporter $(REPORTER) \ 14 | --timeout $(TIMEOUT) \ 15 | --require should \ 16 | $(MOCHA_OPTS) \ 17 | $(TESTS) 18 | 19 | test-cov: 20 | @NODE_ENV=test node --harmony \ 21 | node_modules/.bin/istanbul cover ./node_modules/.bin/_mocha \ 22 | -- -u exports \ 23 | --reporter $(REPORTER) \ 24 | --timeout $(TIMEOUT) \ 25 | $(MOCHA_OPTS) \ 26 | $(TESTS) 27 | @-$(MAKE) check-coverage 28 | 29 | check-coverage: 30 | @./node_modules/.bin/istanbul check-coverage \ 31 | --statements 100 \ 32 | --functions 100 \ 33 | --branches 100 \ 34 | --lines 100 35 | 36 | .PHONY: test 37 | -------------------------------------------------------------------------------- /test/support/server.js: -------------------------------------------------------------------------------- 1 | //use http://localhost:7001 to test 2 | 3 | var koa = require('koa'); 4 | var http = require('http'); 5 | var session = require('koa-sess'); 6 | var githubAuth = require('../../'); 7 | 8 | var app = koa(); 9 | 10 | app.name = 'nae-web'; 11 | app.keys = ['key1', 'key2']; 12 | 13 | app.use(session()); 14 | app.use(githubAuth({ 15 | clientID: '5ec1d25d2a3baf99a03c', 16 | clientSecret: '513607494a244e2759738cae3d50a89494c1e7f0', 17 | callbackURL: 'http://localhost:7001/github/auth/callback', 18 | userKey: 'user', 19 | timeout: 10000 20 | })); 21 | 22 | app.use(function *handler() { 23 | if (!this.session.githubToken) { 24 | this.body = 'login with github'; 25 | } else { 26 | this.body = this.session.user; 27 | } 28 | }); 29 | 30 | app.on('error', function (err) { 31 | if (!err.status || err.status >= 500) { 32 | logger.error(err); 33 | } 34 | }); 35 | 36 | module.exports = http.createServer(app.callback()); 37 | -------------------------------------------------------------------------------- /example.js: -------------------------------------------------------------------------------- 1 | //use http://localhost:7001 to test 2 | 3 | var koa = require('koa'); 4 | var http = require('http'); 5 | var session = require('koa-sess'); 6 | var githubAuth = require('./'); 7 | 8 | var app = koa(); 9 | 10 | app.name = 'nae-web'; 11 | app.keys = ['key1', 'key2']; 12 | 13 | app.use(session()); 14 | app.use(githubAuth({ 15 | clientID: '5ec1d25d2a3baf99a03c', 16 | clientSecret: '513607494a244e2759738cae3d50a89494c1e7f0', 17 | callbackURL: 'http://localhost:7001/github/auth/callback', 18 | userKey: 'user', 19 | timeout: 10000 20 | })); 21 | 22 | app.use(function *handler() { 23 | if (!this.session.githubToken) { 24 | this.body = 'login with github'; 25 | } else { 26 | this.body = this.session.user; 27 | } 28 | }); 29 | 30 | app.on('error', function (err) { 31 | if (!err.status || err.status >= 500) { 32 | logger.error(err); 33 | } 34 | }); 35 | 36 | http.createServer(app.callback()).listen(7001); 37 | console.log('open http://localhost:7001/ in your browser!'); 38 | -------------------------------------------------------------------------------- /test/koa-github.test.js: -------------------------------------------------------------------------------- 1 | /**! 2 | * koa-github - test/koa-github.test.js 3 | * 4 | * MIT Licensed 5 | * 6 | * Authors: 7 | * dead_horse (http://deadhorse.me) 8 | */ 9 | 10 | 'use strict'; 11 | 12 | /** 13 | * Module dependencies. 14 | */ 15 | 16 | var app = require('./support/server'); 17 | var should = require('should'); 18 | var request = require('supertest'); 19 | 20 | describe('koa-github', function () { 21 | describe('GET /github/auth', function () { 22 | it('should redirect ok', function (done) { 23 | request(app) 24 | .get('/github/auth') 25 | .expect(302, done); 26 | }); 27 | }); 28 | 29 | describe('GET /github/auth/callback', function () { 30 | it('should 400', function (done) { 31 | request(app) 32 | .get('/github/auth/callback?code=123') 33 | .expect(400, done); 34 | }); 35 | 36 | it('should 403', function (done) { 37 | request(app) 38 | .get('/github/auth/callback?code=123&state=123') 39 | .expect(403, done); 40 | }); 41 | }); 42 | }); -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "koa-github", 3 | "version": "0.0.5", 4 | "description": "simple github auth middleware for koa ", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "make test" 8 | }, 9 | "files": [ 10 | "index.js" 11 | ], 12 | "repository": { 13 | "type": "git", 14 | "url": "git://github.com/dead-horse/koa-github.git" 15 | }, 16 | "keywords": [ 17 | "github", 18 | "oauth2", 19 | "koa", 20 | "middleware", 21 | "auth", 22 | "login" 23 | ], 24 | "author": "dead_horse", 25 | "license": "MIT", 26 | "bugs": { 27 | "url": "https://github.com/dead-horse/koa-github/issues" 28 | }, 29 | "homepage": "https://github.com/dead-horse/koa-github", 30 | "dependencies": { 31 | "co-urllib": "0.0.1", 32 | "debug": "0.7.4", 33 | "utility": "0.1.10" 34 | }, 35 | "devDependencies": { 36 | "contributors": "*", 37 | "koa": "*", 38 | "koa-sess": "*", 39 | "should": "2.1.1", 40 | "supertest": "0.8.3", 41 | "istanbul": "git://github.com/gotwarlost/istanbul.git#harmony", 42 | "mocha": "^2.4.1" 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2013 dead_horse 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | this software and associated documentation files (the "Software"), to deal in 7 | the Software without restriction, including without limitation the rights to 8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software is furnished to do so, 10 | subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | koa-github [![Build Status](https://secure.travis-ci.org/koajs/koa-github.png)](http://travis-ci.org/koajs/koa-github) 2 | ========== 3 | 4 | simple github auth middleware for koa 5 | 6 | [![NPM](https://nodei.co/npm/koa-github.png?downloads=true)](https://nodei.co/npm/koa-github/) 7 | 8 | ## Example 9 | 10 | ```js 11 | //use http://localhost:7001 to test 12 | 13 | var koa = require('koa'); 14 | var http = require('http'); 15 | var session = require('koa-sess'); 16 | var githubAuth = require('koa-github'); 17 | 18 | var app = koa(); 19 | 20 | app.name = 'nae-web'; 21 | app.keys = ['key1', 'key2']; 22 | 23 | app.use(session()); 24 | app.use(githubAuth({ 25 | clientID: '5ec1d25d2a3baf99a03c', 26 | clientSecret: '513607494a244e2759738cae3d50a89494c1e7f0', 27 | callbackURL: 'http://localhost:7001', 28 | userKey: 'user', 29 | timeout: 10000 30 | })); 31 | 32 | app.use(function *handler() { 33 | if (!this.session.githubToken) { 34 | this.body = 'login with github'; 35 | } else { 36 | this.body = this.session.user; 37 | } 38 | }); 39 | 40 | app.on('error', function (err) { 41 | if (!err.status || err.status >= 500) { 42 | logger.error(err); 43 | } 44 | }); 45 | 46 | http.createServer(app.callback()).listen(7001); 47 | ``` 48 | 49 | ## Options 50 | 51 | ``` 52 | @param {Object} options 53 | - [String] clientID github client ID // regist in https://github.com/settings/applications 54 | - [String] clientSecret github client secret 55 | - [String] callbackURL github redirect url 56 | - [String] signinPath sign in with github's triggle path, default is `/github/auth` 57 | - [String] tokenKey session key, default is githubToken 58 | - [String] userKey user key, if set user key, will request github once to get the user info 59 | - [Array] scope A comma separated list of scopes 60 | - [Number] timeout request github api timeout 61 | - [String] redirect redirect key when call signinPath, so we can redirect after auth, default is `redirect_uri` 62 | ``` 63 | 64 | * clientID, clentSecret and callbackURL are registered in https://github.com/settings/applications. 65 | * if you set userKey field, `koa-github` will request to get the user info and set this object to `this.session[options.userKey]`, otherwise `koa-github` will not do this request. 66 | * if you triggle by `/github/auth?redirect_uri=/callback`, `koa-github` will redirect to `/callback` after auth, and the redirect_uri only accept start with `/`. 67 | 68 | ## Licences 69 | (The MIT License) 70 | 71 | Copyright (c) 2013 dead-horse and other contributors 72 | 73 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 74 | 75 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 76 | 77 | THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 78 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | /**! 2 | * koa-github - index.js 3 | * 4 | * MIT Licensed 5 | * 6 | * Authors: 7 | * dead_horse (http://deadhorse.me) 8 | */ 9 | 10 | 'use strict'; 11 | 12 | /** 13 | * Module dependencies. 14 | */ 15 | 16 | var urllib = require('co-urllib'); 17 | var debug = require('debug')('koa-github'); 18 | var utility = require('utility'); 19 | var util = require('util'); 20 | var qsParse = require('querystring').parse; 21 | var urlParse = require('url').parse; 22 | var assert = require('assert'); 23 | 24 | var defaultOptions = { 25 | tokenKey: 'githubToken', 26 | signinPath: '/github/auth', 27 | timeout: 5000, 28 | scope: ['user'], 29 | redirect: 'redirect_uri' 30 | }; 31 | 32 | /** 33 | * auth with github 34 | * need use session middleware before 35 | * see http://developer.github.com/v3/oauth/#web-application-flow 36 | * 37 | * @param {Object} options 38 | * - [String] clientID github client ID 39 | * - [String] clientSecret github client secret 40 | * - [String] callbackURL github callback url 41 | * - [String] signinPath sign in with github's triggle path, default is /github/auth 42 | * - [String] tokenKey session key, default is githubToken 43 | * - [String] userKey user key, if set user key, will request github once to get the user info 44 | * - [Array] scope A comma separated list of scopes 45 | * - [Number] timeout request github api timeout 46 | * - [String] redirect redirect key when call signinPath, so we can redirect after auth, default is redirect_uri 47 | * 48 | */ 49 | module.exports = function (options) { 50 | options = options || {}; 51 | if (!options.clientID || !options.clientSecret || !options.callbackURL) { 52 | throw new Error('github auth need clientID, clientSecret and callbackURL'); 53 | } 54 | for (var key in defaultOptions) { 55 | if (!utility.has(options, key)) { 56 | options[key] = defaultOptions[key]; 57 | } 58 | } 59 | options.callbackURL = options.callbackURL; 60 | options.callbackPath = urlParse(options.callbackURL).path; 61 | 62 | urllib.TIMEOUT = options.timeout; 63 | debug('init github auth middleware with options %j', options); 64 | 65 | return function *githubAuth(next) { 66 | if (!this.session) { 67 | return this.throw('github auth need session', 500); 68 | } 69 | 70 | // first step: redirect to github 71 | if (this.path === options.signinPath) { 72 | var state = utility.randomString(); 73 | var redirectUrl = 'https://github.com/login/oauth/authorize?'; 74 | redirectUrl = util.format('%sclient_id=%s&redirect_uri=%s&scope=%s&state=%s', 75 | redirectUrl, options.clientID, options.callbackURL, options.scope, state); 76 | 77 | this.session._githubstate = state; 78 | 79 | //try to get the redirect url and set it to session 80 | try { 81 | var redirect = decodeURIComponent(urlParse(this.url, true).query[options.redirect] || ''); 82 | if (redirect[0] === '/') { 83 | this.session._githubredirect = redirect; 84 | debug('get github callback redirect uri: %s', redirect); 85 | } 86 | } catch (err) { 87 | debug('decode redirect uri error'); 88 | } 89 | debug('request github auth, redirect to %s', redirectUrl); 90 | //if already signin 91 | if (this.session[options.tokenKey]) { 92 | debug('already has github token'); 93 | redirectUrl = this.session._githubredirect || '/'; 94 | delete this.session._githubredirect; 95 | } 96 | return this.redirect(redirectUrl); 97 | } 98 | 99 | // secound step: github callback 100 | if (this.path === options.callbackPath) { 101 | //if already signin 102 | if (this.session[options.tokenKey]) { 103 | debug('already has github token'); 104 | return this.redirect('/'); 105 | } 106 | 107 | debug('after auth, jump from github.'); 108 | var url = urlParse(this.request.url, true); 109 | 110 | // must have code 111 | if (!url.query.code || !url.query.state) { 112 | debug('request url need `code` and `state`'); 113 | return this.throw(400); 114 | } 115 | 116 | // check the state, protect against cross-site request forgery attacks 117 | if (url.query.state !== this.session._githubstate) { 118 | debug('request state is %s, but the state in session is %s', 119 | url.query.state, this.session._githubstate); 120 | delete this.session._githubstate; 121 | return this.throw(403); 122 | } 123 | 124 | //step three: request to get the access token 125 | var tokenUrl = 'https://github.com/login/oauth/access_token'; 126 | var requsetOptions = { 127 | data: { 128 | client_id: options.clientID, 129 | client_secret: options.clientSecret, 130 | code: url.query.code 131 | } 132 | }; 133 | debug('request the access token with data: %j', requsetOptions.data); 134 | var token; 135 | try { 136 | var result = yield urllib.request(tokenUrl, requsetOptions); 137 | assert.equal(result[1].statusCode, 200, 138 | 'response status ' + result[1].statusCode + ' not match 200'); 139 | 140 | token = qsParse(result[0].toString()).access_token; 141 | assert(token, 'response without access_token'); 142 | } catch (err) { 143 | return this.throw('request github token error: ' + err.message, 500); 144 | } 145 | 146 | this.session[options.tokenKey] = token; 147 | debug('get access_token %s and store in session.%s', token, options.tokenKey); 148 | delete this.session._githubstate; 149 | 150 | //step four: if set userKey, get user 151 | if (options.userKey) { 152 | var result; 153 | try { 154 | var userUrl = 'https://api.github.com/user'; 155 | var authOptions = { 156 | headers: { 157 | Authorization: 'token ' + token, 158 | 'user-agent': 'koa-github' 159 | }, 160 | dataType: 'json' 161 | }; 162 | result = yield urllib.request(userUrl, authOptions); 163 | assert.equal(result[1].statusCode, 200, 164 | 'response status ' + result[1].statusCode + ' not match 200'); 165 | assert(result[0], 'response without user info'); 166 | } catch (err) { 167 | return this.throw('request github user info error: ' + err.message, 500); 168 | } 169 | debug('get user info %j and store in session.%s', result[0], options.userKey); 170 | this.session[options.userKey] = result[0]; 171 | } 172 | var githubredirect = this.session._githubredirect || '/'; 173 | delete this.session._githubredirect; 174 | return this.redirect(githubredirect); 175 | } 176 | 177 | yield next; 178 | }; 179 | }; 180 | --------------------------------------------------------------------------------