我正在开发一个画布应用程序,我想使用 JS SDK 完成以下任务:
检查用户是否授予了特定的扩展权限
如果是这样,请调用一些函数 startServerProcess()
如果没有,请显示身份验证对话框以获取权限,并在用户未提供足够访问权限时提醒用户。
我想在客户端完全处理这个问题,除非用户提供正确的权限,否则永远不会调用 startServerProcess(),因为它执行的服务器脚本依赖于这些权限。
搜索后我找到了这个解决方案,但它只使用我不想每次都调用的 FB.login() ,因为如果用户已经通过身份验证,则会打开一个烦人的身份验证对话框,然后立即自动关闭。
我最初的解决方案是调用 FB.getLoginStatus(),然后在可能的情况下对 /me/permissions 进行图形 api 调用,并且仅在我确实必须显示身份验证对话框时才调用 FB.login()。
这是我现在拥有的代码:
$('#my_ui_button').click(function() {
require_perms(function(is_authenticated) {
if(!is_authenticated) {
startServerProcess();
} else {
alert('Sorry, we cannot start the server process until you grant permission');
}
});
});
function require_perms(callback) {
// check if the user is logged in + connected to the app
FB.getLoginStatus(function(response) {
// if the user is logged in, continue to check permissions
if(response.authResponse) {
FB.api('/me/permissions', function(perms_response) {
// if photo access already exists, we're good to go
if(perms_response['data'][0]['user_photos'] && perms_response['data'][0]['friends_photos']) {
console.log('permissions are already granted.');
callback(true);
// photo access does not exist, so show an auth dialog
} else {
// get photo permissions
console.log('requesting permission...');
FB.login(function(response) {
if(response.authResponse) {
console.log('permission granted');
callback(true);
} else {
console.log('permission request failed');
callback(false);
}
}, {
scope : 'user_photos,friends_photos'
});
}
});
// user is not connected to the app, so show an auth dialog
} else {
// get photo permissions
console.log('requesting permission...');
FB.login(function(response) {
if(response.authResponse) {
console.log('permission granted');
callback(true);
} else {
console.log('permission request failed');
callback(false);
}
}, {
scope : 'user_photos,friends_photos'
});
}
});
}
这似乎是解决问题的一种混乱方式吗?我特别不喜欢我重复 FB.login() 代码的事实,但我遇到了一些问题,考虑到图形 api 调用的异步性质(或者我只是需要更多的睡眠)。
任何意见/建议将不胜感激。谢谢。