Skip to content

Instantly share code, notes, and snippets.

@lizheming
Last active August 29, 2015 07:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lizheming/f186093b7bff82a37a11 to your computer and use it in GitHub Desktop.
Save lizheming/f186093b7bff82a37a11 to your computer and use it in GitHub Desktop.
Github oAuth 登陆模块附 ThinkJS 示例
var querystring = require("querystring");
var request = require("request");
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);
})
})
}
module.exports = function(config) { return new Github(config) }
var github = reguire("./github.js")({
client_id: "xxxx",
client_secret: "oooo",
redirect_uri: "http://xxx.com/login/callback" //和申请 KEY 时填写的 CALLBACK 地址要一样
});
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);
})
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment