要使用通过其他方式获得的访问令牌(如iOS Facebook SDK)登录Facebook,请在服务器上定义调用适当Accounts方法的方法:
$FB = function () {
if (Meteor.isClient) {
throw new Meteor.Error(500, "Cannot run on client.");
}
var args = Array.prototype.slice.call(arguments);
if (args.length === 0) {
return;
}
var path = args[0];
var i = 1;
// Concatenate strings together in args
while (_.isString(args[i])) {
path = path + "/" + args[i];
i++;
}
if (_.isUndefined(path)) {
throw new Meteor.Error(500, 'No Facebook API path provided.');
}
var FB = Meteor.npmRequire('fb');
var fbResponse = Meteor.sync(function (done) {
FB.napi.apply(FB, [path].concat(args.splice(i)).concat([done]));
});
if (fbResponse.error !== null) {
console.error(fbResponse.error.stack);
throw new Meteor.Error(500, "Facebook API error.", {error: fbResponse.error, request: args});
}
return fbResponse.result;
};
Meteor.methods({
/**
* Login to Meteor with a Facebook access token
* @param accessToken Your Facebook access token
* @returns {*}
*/
facebookLoginWithAccessToken: function (accessToken) {
check(accessToken, String);
var serviceData = {
accessToken: accessToken
};
// Confirm that your accessToken is you
try {
var tokenInfo = $FB('debug_token', {
input_token: accessToken,
access_token: Meteor.settings.facebook.appId + '|' + Meteor.settings.facebook.secret
});
} catch (e) {
throw new Meteor.Error(500, 'Facebook login failed. An API error occurred.');
}
if (!tokenInfo.data.is_valid) {
throw new Meteor.Error(503, 'This access token is not valid.');
}
if (tokenInfo.data.app_id !== Meteor.settings.facebook.appId) {
throw new Meteor.Error(503, 'This token is not for this app.');
}
// Force the user id to be the access token's user id
serviceData.id = tokenInfo.data.user_id;
// Returns a token you can use to login
var loginResult = Accounts.updateOrCreateUserFromExternalService('facebook', serviceData, {});
// Login the user
this.setUserId(loginResult.userId);
// Return the token and the user id
return loginResult;
}
}
Run Code Online (Sandbox Code Playgroud)
此代码取决于meteorhacks:npm包.你应该调用meteor add meteorhacks:npm并拥有一个package.json带有Facebook节点API 的文件:{ "fb": "0.7.0" }.
如果您使用demeteorizer部署应用程序,则必须编辑输出package.json并将scrumptious依赖项设置"0.0.1"为"0.0.0".
在客户端上,使用适当的参数调用方法,然后您已登录!
在Meteor 0.8+中,结果Accounts.updateOrCreateUserFromExternalService已更改为包含的对象{userId: ...},此外,不再具有标记的标记.
| 归档时间: |
|
| 查看次数: |
1804 次 |
| 最近记录: |