How do you implement forget password method in my method. I am creating a HTML project which is due soon. My code:
function toggleSignIn() {
if (!firebase.auth().currentUser) {
// [START createprovider]
var provider = new firebase.auth.GoogleAuthProvider();
// [END createprovider]
// [START addscopes]
provider.addScope('https://www.googleapis.com/auth/plus.login');
// [END addscopes]
// [START signin]
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
// [START_EXCLUDE]
document.getElementById('quickstart-oauthtoken').textContent = token;
// [END_EXCLUDE]
}).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;
// [START_EXCLUDE]
if (errorCode === 'auth/account-exists-with-different-credential') {
alert("You have already signed up with a different auth provider for that email.");
// If you are using multiple auth providers on your app you should handle linking
// the user's accounts here.
}
else if (errorCode === 'auth/auth-domain-config-required') {
alert("An auth domain configuration is required");
}
else if (errorCode === 'auth/cancelled-popup-request') {
alert("Popup Google sign in was canceled");
}
else if (errorCode === 'auth/operation-not-allowed') {
alert("Operation is not allowed");
}
else if (errorCode === 'auth/operation-not-supported-in-this-environment') {
alert("Operation is not supported in this environment");
}
else if (errorCode === 'auth/popup-blocked') {
alert("Sign in popup got blocked");
}
else if (errorCode === 'auth/popup-closed-by-user') {
alert("Google sign in popup got cancelled");
}
else if (errorCode === 'auth/unauthorized-domain') {
alert("Unauthorized domain");
}
else {
console.error(error);
}
// [END_EXCLUDE]
});
// [END signin]
} else {
// [START signout]
firebase.auth().signOut();
// [END signout]
}
// [START_EXCLUDE]
document.getElementById('quickstart-sign-ing').disabled = false;
// [END_EXCLUDE]
}
Here is a link to give you guidance:
https://firebase.google.com/docs/auth/web/manage-users#set_a_users_password
Please can you help me
To implement a forgot password button, you have to call:
firebase.auth().sendPasswordResetEmail('user#example.com')
Check the documentation for more details:
https://firebase.google.com/docs/reference/js/firebase.auth.Auth#sendPasswordResetEmail
The easiest way to implement recover forgot password functionality is to call
import { AngularFireAuth } from "#angular/fire/auth";
constructor(
public afAuth: AngularFireAuth
) { }
// Reset Forggot password
ForgotPassword(passwordResetEmail) {
return this.afAuth.auth.sendPasswordResetEmail(passwordResetEmail)
.then(() => {
window.alert('Password reset email sent, check your inbox.');
}).catch((error) => {
window.alert(error)
})
}
To implement firebase reset you first need to send email to the user and for that we use sendPasswordResetEmail method. after that if user gonna click on the email, it will be redirected to a default page provided by firebase from there user can reset their password.
But if you want to have custom page for the password reset you can do that too, to do that you need to change the action url in the email template of your firebase project then you need to setup that custom action url, for this you can read this offical doc page: https://firebase.google.com/docs/auth/custom-email-handler?hl=en&authuser=0
Related
I'm trying to make just a simple authentication app with electron and firebase redirect, but if the user is already logged in and I use the firebase.auth().currentUser.getIdToken() to get the IdToken of that user, but when i try that token in
firebase.auth().signInWithCredential(credential) I get the error that says ERROR: auth/invalid-credential
Here is my code front-end
firebase.auth().onAuthStateChanged( async function (user) {
if (user) {
// User is signed in.
var user = await firebase.auth().currentUser;
if (user != null) {
await firebase.auth().currentUser.getIdToken().then(function(idToken) {
window.location.href = "electron://"+idToken;
}).catch(function(error) {
console.log(error)
});
}
} else {
// No user is signed in.
document.getElementById("user_div").style.display = "none";
document.getElementById("login_div").style.display = "block";
}
});
Here is my code back-end
app.on('second-instance', (event, commandLine, workingDirectory) => {
if (commandLine[2]) {
var url = commandLine[2].split('/')
var id_token = url[2]
console.log('id: ', id_token)
// Build Firebase credential with the Google ID token.
var credential = firebase.auth.GoogleAuthProvider.credential(id_token);
// Sign in with credential from the Google user.
firebase.auth().signInWithCredential(credential)
.then((success)=>{
myWindow.loadFile('./scr/welcome.html')
console.log('RESULT: ',success)
})
.catch((error) => {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log('ERROR:', errorMessage)
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
console.log('ERROR:', credential)
// ...
})
}
I'm missing something or doing something wrong?
That's not how ID tokens work. The purpose of an ID token is to pass to your backend, so that it can validate the identity of the signed in user, and perform some action on their behalf. It's not valid for signing in on the client again. You might want to review the documentation on use of ID tokens to learn how this works.
signInWithCredential only works with Google Auth when you correctly construct a GoogleAuthProvider credential. There is plenty of sample code in the API documentation for that.
I'm logging in users via firebase-auth and need to pass their user uid to the redirected page. How can the user-uid be passed?
I've tried using the docs on firebase auth but cant quite solve it
loginForm.addEventListener('submit', (e) => {
e.preventDefault();
const email = loginForm['email'].value;
const password = loginForm['password'].value;
console.log(email, password);
firebase.initializeApp(config);
firebase.auth().signInWithEmailAndPassword(email, password)
.then(cred => {
if(email ==='admin#mombasa.com' && password ==='adminMomb') {
window.location = './admin-map.php';
}
else if(email ==='admin#nairobi.com' && password ==='adminNai') {
window.location = './admin-map.php';
}
else if(email ==='admin#eldoret.com' && password ==='adminEld') {
window.location = './admin-map.php';
}
else firebase.auth().onAuthStateChanged(function(user) {
window.user = user;
console.log('logged in ', user);
window.location = './dailyreports.php';
console.log('logged in ', user);
});
}).catch(
function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
console.log(errorMessage, errorCode);
}
)
;
});
On navigation to the next page, I expected to see the user-uid output in the console but it returns blank
Instead of passing the UID, it's better to pick up the state in the next page with a so-called authentication state listener.
As shown in the documentation on getting the currently signed in user:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
});
There will be no delay in picking up the user account this way on the new page, as the Firebase SDK will be able to restore the state from the information it stored in local storage.
I am having a problem with my current firebase html and javascript setup that is leading to not getting users registered to my firebase database of users. I am not receiving any error alerts in the browser when I run the below code. I have also tried running the site by running 'firebase serve' and I am not getting any errors logged to the console.
The html source includes and javascript file are below. I have tested to make sure that I am able to access the username and password fields from the Document and that is working fine. Let me know if you need to see any additional information. Thank you!
Right after the Body tag in my html I include the following scripts:
<script src="https://www.gstatic.com/firebasejs/5.0.3/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.0.3/firebase-auth.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="register.js"></script>
Then in my register.js file:
// Initialize Firebase
var config = {
apiKey: "mykey",
authDomain: "mydomain",
databaseURL: "myurl",
projectId: "myid",
storageBucket: "mybucket",
messagingSenderId: "mysenderid"
};
firebase.initializeApp(config);
$(document).ready(function(){
$("form").submit(function(){
var email = $('user').val();
var password = $('#password').val();
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(function(val) {
alert("Success!!");
console.log(val);
})
.catch(function(error) {
// Handle Errors here.
alert("ERROR");
var errorCode = error.code;
var errorMessage = error.message;
// [START_EXCLUDE]
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
alert(errorMessage);
}
console.log(error);
// [END_EXCLUDE]
}).success(function(json) {
console.log(json);
alert("TESTER");
})
// [END createwithemail]
});
});
A couple of remarks:
1/ For initialization you just need to do
<script src="https://www.gstatic.com/firebasejs/5.0.3/firebase.js"></script>
OR
<script src="https://www.gstatic.com/firebasejs/5.0.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.0.3/firebase-auth.js"></script>
See https://firebase.google.com/docs/web/setup
2/ Don't call the submit method of your form. Just get the values of the email and password fields (e.g. var email = $('user').val();) and call the Firebase createUserWithEmailAndPassword(email, password) function as you do, without submitting the form.
Note that if you want to handle a succesful registration you should add a then(), as follows, since the function returns a promise (see doc here)
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(function(val) {
//Success!!
console.log(val);
})
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
alert(errorMessage);
}
console.log(error);
});
Add a success function callback and see the response
$("form").submit(function(){
var email = $('user').val();
var password = $('#password').val();
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
alert("ERROR");
var errorCode = error.code;
var errorMessage = error.message;
// [START_EXCLUDE]
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
alert(errorMessage);
}
console.log(error);
// [END_EXCLUDE]
}).success(function(json) {
console.log(json);
});
// [END createwithemail]
});
I've a authentication Google with redirect in my app, and I would like just redirect when authentication is completely finished.
But the promise is not working
function loginGoogle() {
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithRedirect(provider);
firebase.auth().getRedirectResult().then(function (result) {
// This gives you a Google Access Token. You can use it to access the Google API.
if (result.credential) {
var token = result.credential.accessToken;
console.log('token ' + token);
}
// The signed-in user info.
var user = result.user;
console.log('user ' + user);
// if success redirect to
$state.go('maps-fullwidth');
// ...
}).catch(function (error) {
// Handle Errors here.
var errorCode = error.code;
console.log(errorCode);
var errorMessage = error.message;
// The email of the user's account used.
console.log(errorMessage);
var email = error.email;
console.log(email);
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
console.log(credential);
// ...
});
}
Thanks.
Move the getRedirectResult() call out of your loginGoogle() function. getRedirectResult() should be called on page load. An example of this in action can be found here:
https://github.com/firebase/quickstart-js/blob/master/auth/google-redirect.html
I want to add the display name to the user that was just created. But when I createUserWithEmailAndPassword it sais my currentUser is null. Anything wrong?
var name = document.getElementById("name").value;
var username = document.getElementById("username").value;
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
// Sign in with email and pass.
// [START createwithemail]
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// [START_EXCLUDE]
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
console.error(error);
}
// [END_EXCLUDE]
});
// [END createwithemail]
var user = firebase.auth().currentUser;
user.updateProfile({
displayName: username
}).then(function() {
// Update successful.
}, function(error) {
// An error happened.
});
document.getElementById("submitButton").innerHTML = "Loading...";
$("#submitButton").css("background-color", "#efefef");
$("#submitButton").css("cursor", "init");
$("#submitButton").css("color", "#aaa");
registerUserToDB(username, name, email);
console.log("shouldhave worked");
createUserWithEmailAndPassword is an asynchronous call like almost every other function in Firebase. You create the user (most likely successfully) but then immediately after you try and grab the currentUser. In almost every case you will be attempting to get the currentUser before Firebase has finished creating your user.
Rewrite inside callback:
firebase.auth().createUserWithEmailAndPassword(email, password).then(function(user) {
// [END createwithemail]
// callSomeFunction(); Optional
// var user = firebase.auth().currentUser;
user.updateProfile({
displayName: username
}).then(function() {
// Update successful.
}, function(error) {
// An error happened.
});
}, function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// [START_EXCLUDE]
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
console.error(error);
}
// [END_EXCLUDE]
});
.then will be called upon success and function(error) will be called upon error. You want to set your user after user creation was successful.
Some people don't like the nested callbacks so you could create a function that gets the current user and call the function upon success.
Docs:
Firebase Promises
Async, callbacks
You have to do like this.
import {AngularFireAuth} from '#angular/fire/auth';
import { auth } from 'firebase';
constructor(private auth: AngularFireAuth) {}
signup(username: string, email: string, password: string) {
this.auth.auth.createUserWithEmailAndPassword(email, password)
.then((user: auth.UserCredential) => {
user.user.updateProfile({
displayName: username
});
})
}
If you use Angular, then you can use dependency injection to inject an AUTH instance to the constructor, then you access to the AUTH service (this.auth.Auth), and create your account with createUserWithEmailAndPassword() method. Once the account is successfully created, it returns Promise< UserCredential >. Since it's wrapped in a Promise you have to use either async, await, or then() to access to the UserCredential typed value. The interface of UserCredential goes as following.
UserCredential: { additionalUserInfo?: AdditionalUserInfo | null; credential: AuthCredential | null; operationType?: string | null; user: User | null }
As you see there are a number of properties in the UserCredential instance, and one of them is USER (user: User | null). This property has all the information of the user. Now you can access to methods of firebase.User. The method responsible for updating the user profile is updateProfile(). It has displayName, PhotoURL properties. Now you can update the userProfile like this. user.user.updateProfile({ displayName: NAME }). Remember you have to update properties inside of parenthesis ( {} ), because updateProfile supports JavaScript object argument. This object has two properties called displayName, and photoURL.
updateProfile ( profile : { displayName ?: string | null ; photoURL ?: string | null } ) : Promise < void >
https://firebase.google.com/docs/reference/js/firebase.auth.Auth
https://firebase.google.com/docs/reference/js/firebase.auth#usercredential
https://firebase.google.com/docs/auth/web/password-auth#create_a_password-based_account
https://firebase.google.com/docs/reference/js/firebase.User#updateprofile
For anyone using the new SDK, you could do this the following way in Angular:
import {
...
createUserWithEmailAndPassword,
updateProfile,
} from '#angular/fire/auth';
signup(username: string, email: string, password: string, displayName: string): Promise<void> {
createUserWithEmailAndPassword(this.auth, email, password).then(
userCred => {
updateProfile(userCred.user, { displayName });
}
}