gpt4 book ai didi

javascript - 如何使用Cordova插件和Firebase模板将Facebook身份验证详细信息发送到Firebase

转载 作者:行者123 更新时间:2023-11-30 00:00:51 24 4
gpt4 key购买 nike

抱歉,这个问题有点长,因为我已经尝试解决此问题一段时间了,并希望确保我不会遗漏任何信息。我正在构建一个Cordova应用程序,并将Firebase用于身份验证/数据库后端。我已经尝试使用“使用Facebook登录”按钮对用户进行Firebase身份验证了近一个星期,但是我一直无法使其正常工作。

最初,我尝试在此处按照Firebase的示例进行操作:https://firebase.google.com/docs/auth/web/facebook-login(我需要使用“高级:手动处理登录流程”,因为它是Cordova Android和iOS应用程序),因此该示例对我来说不起作用Facebook的SDK脚本(//connect.facebook.net/en_US/sdk.js)不断抛出错误:

file://connect.facebook.net/en_US/sdk.js Failed to load resource: net::ERR_FILE_NOT_FOUND

我试图以几种方式解决此错误,例如:


将其更改为https://connect.facebook.net/en_US/sdk.js(这导致错误:Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings.
在Facebook应用程序设置中将相关链接添加到“有效OAuth重定向URI”和域列表中
将文件存储在本地文件系统中(以及在手机上的应用程序内部)
在index.html文件的头部包含整个SDK


这些尝试均无济于事。因此,我决定从这里使用插件cordova-plugin-facebook:https://github.com/bisrael/cordova-plugin-facebook

这是我用来通过插件从Facebook获取用户信息的代码:

function logInWithFacebook(){
CordovaFacebook.login({
onSuccess: function(result) {
console.log(result);
console.log(result.authToken);
// Store or send the user auth/access key here?
// Get user's name
retrieveUserDetails();
if(result.declined.length > 0) {
alert("The User declined something!");
}
},
onFailure: function(result) {
if(result.cancelled) {
alert("The user doesn't like my app");
} else if(result.error) {
alert("There was an error:" + result.errorLocalized);
}
}
});
}

function retrieveUserDetails(){
// Now that the user has authroised the app, make request to CordovaFacebook plugin to get user's name
CordovaFacebook.graphRequest({
path: '/me',
params: { fields: 'name' },
onSuccess: function (userData) {
console.log(userData);
console.log(userData.name);
// Here somehow send the retrieved username and send it to the Firebase function so that it's linked with the auth key.
},
onFailure: function (result) {
if (result.error) {
Error.log('error', 'There was an error in graph request:' + result.errorLocalized);
}
}
});
}


现在,我可以单击登录按钮,并通过Facebook成功登录。该过程从Facebook返回用户身份验证/访问密钥和用户名。

据我了解,Firebase的文档( https://firebase.google.com/docs/auth/web/facebook-login)中的手动登录流程示例采用从Facebook返回的密钥,将其转换为Firebase密钥,然后将用户新创建的Firebase密钥及其用户名输入到Firebase的服务器中。

在以下示例代码中,这似乎很简单:

function checkLoginState(event) {
if (event.authResponse) {
// User is signed-in Facebook.
var unsubscribe = firebase.auth().onAuthStateChanged(function(firebaseUser) {
unsubscribe();
// Check if we are already signed-in Firebase with the correct user.
if (!isUserEqual(event.authResponse, firebaseUser)) {
// Build Firebase credential with the Facebook auth token.
var credential = firebase.auth.FacebookAuthProvider.credential(
event.authResponse.accessToken);
// Sign in with the credential from the Facebook user.
firebase.auth().signInWithCredential(credential).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});
} else {
// User is already signed-in Firebase with the correct user.
}
});
} else {
// User is signed-out of Facebook.
firebase.auth().signOut();
}
}

function isUserEqual(facebookAuthResponse, firebaseUser) {
if (firebaseUser) {
var providerData = firebaseUser.providerData;
for (var i = 0; i < providerData.length; i++) {
if (providerData[i].providerId === firebase.auth.FacebookAuthProvider.PROVIDER_ID &&
providerData[i].uid === facebookAuthResponse.userID) {
// We don't need to re-auth the Firebase connection.
return true;
}
}
}
return false;
}

FB.Event.subscribe('auth.authResponseChange', checkLoginState);


我的问题是,如何将从Cordova插件代码返回的auth密钥和用户名发送到Firebase的示例代码,以使其正常运行?

Firebase的示例代码包括此侦听器,该侦听器侦听Facebook授权状态中的任何更改: FB.Event.subscribe('auth.authResponseChange', checkLoginState);,但是由于它使用Facebook的SDK,因此无法使用我当前的设置。

我使用以下Firebase聊天应用程序作为模板来工作: https://gist.github.com/puf/8f67d3376d80ed2d02670d20bfc4ec7d,您可以看到它具有“使用Facebook登录”按钮,但是没有用于处理该过程的代码,因此我尝试应用部分手动日志在Firebase的文档( https://firebase.google.com/docs/auth/web/facebook-login)中的流示例中,使用从cordova-plugin-facebook查询返回的数据,并将二者与Firebase的聊天应用程序模板集成。

对于下一步该做什么我真的很茫然,我已经尝试了所有我能想到的。对于解决此问题的任何帮助将非常感谢。
先感谢您!

更新

问题和解答:

目前如何运作?

现在,我有一个“ Facebook登录”按钮-单击此按钮,它将运行 logInWithFacebook()。该功能使用 CordovaFacebook插件,在用户使用Facebook登录后,它还会运行功能 retrieveUserDetails()retrieveUserDetails()从Facebook获取一些用户信息,我希望这些信息然后插入到我的Firebase数据库中。

logInWithFacebook()正常工作(它会打开一个Facebook登录页面,并且当用户登录时,我可以console.log用户的Facebook ID和Facebook访问令牌。

retrieveUserDetails()也可以正常工作(我可以console.log来自Facebook的用户名)。

您希望它如何工作?

我对上半部分的工作方式感到满意(使用Facebook登录并检索用户详细信息可以正常工作)。但是,我希望此登录触发Firebase的身份验证状态更改侦听器,以便Firebase检测并确认用户已登录:

firebase.auth().onAuthStateChanged(function(user) {
if (user) {
console.log("User is signed in.");
} else {
console.log("User is not signed in.");
}
});


什么不按您想要的方式工作?

流程的前半部分正常运行,但是当我处理从Facebook返回的accessToken时我迷路了。通过阅读文档,我认为Firebase应该将此令牌转换为Firebase访问令牌,然后用于将用户登录到Firebase(这也会触发上述AuthStateChanged函数)。从那里,我希望能够将我从Facebook检索到的所有数据(用户名等)插入到Firebase数据库中。但是主要的问题是将Facebook accessToken转换为Firebase登录名(原始问题的第二个代码块是我尝试在其中执行转换/登录Firebase的位置)。

因为我使用的是Cordova,所以这种方法(使用插件登录Facebook,然后处理accessToken的转换)似乎是使用Facebook登录的唯一方法。但是我完全不知道如何完成下半场。

更新2

我已经从文档中的示例convert-Facebook-token-to-Firebase-token代码中裁剪了一些部分,因此不需要Facebook SDK。它似乎正在工作。这是删除了SDK相关部分之后的代码:

// First, define the Facebook accessToken:
var FBaccessToken = result.accessToken;

// Build Firebase credential with the Facebook auth token.
var credential = firebase.auth.FacebookAuthProvider.credential(
FBaccessToken);
// Sign in with the credential from the Facebook user.
firebase.auth().signInWithCredential(credential).then(function(user){

console.log("It looks like we signed into Firebase with the Facebook token correctly.");

}, function(error) {
console.log("Something went wrong, user isn't signed into Firebase with the FB token.");
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});


我仍然需要从Facebook添加用户的电子邮件,并在登录Firebase时也尝试发送该电子邮件-这样,我将在Firebase控制台中为该用户提供一些标识符,但这是一个好的开始。

第二次更新

用户授权应用后,以下代码成功从Facebook获取了用户数据:

    CordovaFacebook.graphRequest({
path: '/me',
params: { fields: 'first_name,last_name,email,locale,gender,age_range,picture.width(200).height(200)' },
onSuccess: function (userData) {
console.log(userData)
var first_name = userData.first_name;
var last_name = userData.last_name;
var email = userData.email;
var locale = userData.locale;
var gender = userData.gender;
var min_age = userData.age_range.min;
var profile_picture = userData.picture.data.url;

// Enter user details into the Firebase database:
firebase.database().ref('users/' + uid).set({
first_name: first_name,
last_name: last_name,
email: email,
locale: locale,
gender: gender,
min_age: min_age,
profile_picture : profile_picture
});
console.log("Facebook user data should now be in the database!");
},
onFailure: function (result) {
if (result.error) {
Error.log('error', 'There was an error in graph request:' + result.errorLocalized);
}
}
});

最佳答案

(仅是最后一次更新的答案,您可以找出其余的内容:))

如何从CordovaFacebook.login()获取用户电子邮件

查看CordovaFacebook documentation,您可以在传递给permissions方法的对象上添加login属性。

根据Facebook API documentation,电子邮件的权限名称仅为"email"

我还没有测试,但是我认为这应该可行:

CordovaFacebook.login({
permissions: [ 'email' ],
onSuccess: function(result) {
console.log('email:', result.email);
...
},
onFailure: function(result) {
...
}
});

关于javascript - 如何使用Cordova插件和Firebase模板将Facebook身份验证详细信息发送到Firebase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40591681/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com