Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save annaliahsiao/8e89b70e5daee3b1d4963aacb794e9af to your computer and use it in GitHub Desktop.
Save annaliahsiao/8e89b70e5daee3b1d4963aacb794e9af to your computer and use it in GitHub Desktop.
Sign in a user with an email address and password - firebase
//初始化 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 email,
password,
user,
name,
email,
photoUrl;
//註冊會員
function sign_up(){
email = $('#account_signup').val();
password = $('#password_signup').val();
user = firebase.auth().currentUser;
firebase.auth().createUserWithEmailAndPassword(email, password).then(function(user) {
//註冊完後,可執行的動作
}).catch(function(error){
//註冊未成功的錯誤訊息
var errorMessage = error.message;
console.log(errorMessage);
});
}
//修改使用者資料
function user_profile(){
var user = firebase.auth().currentUser;
name = $('#name_signup').val();
var displayName = user.displayName,
email = user.email,
emailVerified = user.emailVerified,
photoURL = user.photoURL;
//firebase 可支援的參數有displayName、email、emailVerified、photoURL
var profile = {displayName,email,emailVerified,photoURL}
user.updateProfile(profile).then(function() {
//將修改資料傳回firebase
return user.updateProfile({'displayName': name});
}).catch(function(error) {
//修改資料未成功的錯誤訊息
var errorMessage = error.message;
console.log('profile error',errorMessage)
});
}
//登入會員
function sign_in(){
email = $('#account').val();
password = $('#password').val();
firebase.auth().signInWithEmailAndPassword(email, password).then(function(user) {
//登入成功
console.log('login');
}).catch(function(error) {
//登入錯誤訊息
var errorMessage = error.message;
console.log(errorMessage);
});
}
//取得用戶資料
function get_user_data(){
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// 取得使用者的資料
console.log(user.displayName)
} else {
// 使用者為登出狀態
console.log('not login')
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment