Skip to content

Instantly share code, notes, and snippets.

@annaliahsiao
Last active March 21, 2024 14:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save annaliahsiao/b105275f37c02efedbd3919d87812fcc to your computer and use it in GitHub Desktop.
Save annaliahsiao/b105275f37c02efedbd3919d87812fcc to your computer and use it in GitHub Desktop.
Firebase FaceBook Authentication
//初始化 firebase
var config = {
apiKey: "<API_KEY>",
authDomain: "<PROJECT_ID>.firebaseapp.com",
databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
projectId: "<PROJECT_ID>",
storageBucket: "<BUCKET>.appspot.com",
messagingSenderId: "<SENDER_ID>",
};
firebase.initializeApp(config);
var provider;
function fb_login(){
provider = new firebase.auth.FacebookAuthProvider();//取得FaceBook授權的Scope
provider.addScope('user_birthday'); //取得FaceBook登入者的生日
provider.addScope('email'); //取得FaceBook登入者的信箱
provider.addScope('user_friends'); //取得FaceBook登入者的朋友
/**provider.addScope('FB權限值'):取得FaceBook登入者的權限資料,例如生日、大頭貼或是其他FB開放的功能可以在這裡做設定*/
firebase.auth().useDeviceLanguage(); //默認瀏覽器定義FB登入視窗的顯示語言
provider.setCustomParameters({
'display': 'popup' //FB登入視窗以popup顯示
});
/**provider.setCustomParameters({'FB可提供的存取權杖傳回'}):取得FaceBook登入的權限, 在成功時會將控制流程和存取權杖傳回應用程式,這裡需要注意的是firebase目前不提供以下參數的回傳 'client_id', 'redirect_uri', 'scope', 'response_type'以及'state',所以比較常見的有 'auth_type', 'display'和'locale'*/
firebase.auth().signInWithPopup(provider).then(function(result) {
//取得Facebook Access Token
var token = result.credential.accessToken;
// 取得FaceBook登入者的資料
var user = result.user;
console.log(user);
}).catch(function(error) {
// 錯誤訊息的提示程式碼與訊息
var errorCode = error.code;
var errorMessage = error.message;
if (error.code === 'auth/account-exists-with-different-credential') {
// 使用者 註冊的mail帳號.
var email = error.email;
// 使用firebase.auth.AuthCredential類型的錯誤訊息
var pendingCred = error.credential;
auth.fetchProvidersForEmail(email).then(function(providers) {
// 登入使用email
auth.fetchSignInMethodsForEmail(email).then(function(methods) {
if (methods[0] === 'password') {
// 如果使用者用密碼登入,要求使用者輸入密碼
var password = promptUserForPassword();
auth.signInWithEmailAndPassword(email, password).then(function(user) {
return user.link(pendingCred);
}).then(function() {
// 成功登入為 Firebase 使用者.
});
return;
}
});
});
// 其他登入方式,必須取得該登入方式
var provider = getProviderForProviderId(methods[0]);
auth.signInWithPopup(provider).then(function(result) {
result.user.linkAndRetrieveDataWithCredential(pendingCred).then(function(usercred) {
// 成功登入為 Firebase 使用者.
});
});
}else{
console.log(errorMessage,errorCode)
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment