我实质上是在尝试建立一个网站,该网站通过firebase对用户的GitHub帐户进行身份验证,然后将其用户名保存在数据库中-我特别需要此用户名。我可以进行身份验证,但是firebase似乎无法访问用户名,只能访问电子邮件,显示名称等内容。目前,我只想将用户名另存为变量
我遇到了这个问题:https://developer.github.com/v3/users/#get-the-authenticated-user 我假设“登录名”是用户名? 不过,我对事物还比较陌生,无法找到任何清晰的示例说明如何使用Firebase的令牌访问此信息。 作为参考,我有一个与app.js链接的index.html,其中包含我的所有身份验证代码。
var provider = new firebase.auth.GithubAuthProvider();
provider.addScope('read:user');
//get elements
const authenticateBtn = document.getElementById('authbtn');
//add login event
authenticateBtn.addEventListener('click', e=>{
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a GitHub Access Token. You can use it to access the GitHub API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
//what I want to get
//var Username = ;
//some data I am able to get
var displayName = user.displayName;
var email = user.email;
var emailVerified = user.emailVerified;
var photoURL = user.photoURL;
var isAnonymous = user.isAnonymous;
var uid = user.uid;
var providerData = user.providerData;
//where I want to print the username
//console.log(userName);
// ...
}).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;
// ...
});
})
我真的只需要初学者说明我想做的事情是否可能,如果可以的话,确切地说明我在项目中的什么地方需要什么代码。 谢谢!
答案 0 :(得分:0)
所以我最终从朋友那里得到了一些帮助,这是我的解决方法:
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a GitHub Access Token. You can use it to access the GitHub API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
var username;
var obj;
const Http = new XMLHttpRequest();
Http.open("GET", "https://api.github.com/user?access_token="+token);
Http.send();
Http.onreadystatechange=function(){
if(this.readyState==4 && this.status==200){
obj = JSON.parse(Http.responseText);
username = obj.login;
console.log(username);
}
}
}