-
-
Save jumplee/bfd82c4127d7d8a59503 to your computer and use it in GitHub Desktop.
Login Github
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 自定义配置 | |
var client = { | |
id: "", | |
secret: "" | |
}; | |
var redirect_uri = "http://lizheming.com:8360/login/callback"; | |
var querystring = require("querystring"); | |
var request = require("request"); | |
var github = new Github({ | |
client_id: client.id, | |
client_secret: client.secret, | |
redirect_uri: redirect_uri | |
}); | |
module.exports = Controller({ | |
indexAction: function() { | |
this.end('<a href="'+github.getAuthorizeUrl()+'">Login with Github</a>'); | |
}, | |
callbackAction: function() { | |
var that = this; | |
github.getAccessToken(this.get("code")).then(function(token) { | |
return github.getUserInfo(token.access_token); | |
}).then(function(user) { | |
that.end("email: " + user.email + "<br>" + "login: " + user.login); | |
}) | |
} | |
}) | |
function Github(config) { | |
if(!config.client_id || !config.client_secret || !config.redirect_uri) { | |
throw Error("client_id, client_secret, redirect_uri is required"); | |
} | |
for(var i in config) this[i] = config[i]; | |
if( !config.scope ) this.scope = "user"; | |
} | |
Github.prototype.getAuthorizeUrl = function() { | |
var baseUrl = "https://github.com/login/oauth/authorize"; | |
return baseUrl + "?" + querystring.stringify({ | |
client_id: this.client_id, | |
redirect_uri: this.redirect_uri, | |
scope: this.scope, | |
state: this.state || "" | |
}); | |
} | |
Github.prototype.getAccessToken = function(code) { | |
var that = this, | |
baseUrl = "https://github.com/login/oauth/access_token", | |
data = { | |
client_id: that.client_id, | |
client_secret: that.client_secret, | |
code: code, | |
redirect_uri: that.redirect_uri, | |
}; | |
if(this.state) data.state = this.state; | |
return new Promise(function(resolve, reject) { | |
return request.post({ | |
url: baseUrl, | |
headers: { "Accept": "application/json" }, | |
form: data | |
}, function(err, httpResponse, body) { | |
if(err) reject(Error(err)); | |
var res = JSON.parse(body); | |
if(res.access_token) resolve(res); | |
else reject(Error(res)); | |
}) | |
}) | |
} | |
Github.prototype.getUserInfo = function(token) { | |
return new Promise(function(resolve, reject) { | |
return request.get({ | |
url: "https://api.github.com/user", | |
headers: { | |
"User-Agent": "@lizheming", | |
"Authorization": "token "+token | |
} | |
}, function(err, httpResponse, body) { | |
if(err) reject(Error(err)); | |
var res; | |
if(!(res = JSON.parse(body))) reject(Error(body)); | |
return resolve(res); | |
}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment