How to save user information (userName) firebase new angular 2 - javascript

I need to save in my Firebase UserName and get it when he is LogIn, but I cant figure out it. What should I add in code?
signUp(userEmail , userPassword){
firebase.auth().createUserWithEmailAndPassword(userEmail, userPassword).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
signIn(userEmail , userPassword){
firebase.auth().signInWithEmailAndPassword(userEmail, userPassword).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
Thank you for answers.

I have solved this problem . You just chain function then it will look like
firebase.auth().createUserWithEmailAndPassword(userEmail, userPassword).then(function (result) {
firebase.database().ref('/users/' + result.uid).set({
username: 'someOne',
email:userEmail,
});
console.log(result);
}).catch(function (error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});

Related

Firebase Authentication with FullName

I am trying to register user with createUserWithEmailAndPassword function, which logically receives only email and password. But I want also to write fullname field of user. Can you tell me what is the way of doing this? Thanks
But I want also to write fullname field of user.
I make the assumption that you want to update the displayName property of the user Object.
Do as follows, by using the updateProfile() method:
firebase.auth().createUserWithEmailAndPassword(email, password)
.then((userCredential) => {
// Signed in
var user = userCredential.user;
return user.updateProfile({displayName: "Your name"});
})
.then(() => {
console.log("Profile updated successfully!");
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
// ..
});

How to add user's extra information such as display name in firebase using javascript?

Using createUserWithEmailAndPassword function of firebase I am able to sign users up but how to add extra information such as display name and picture URL?
This is what I have done.
const signup = document.querySelector('#signup-form');
signup.addEventListener('submit', e=>{
e.preventDefault();
//get user info
const first_name = signup['firstname'].value;
const last_name = signup['lastname'].value;
const email = signup['email1'].value;
const password = signup['pswd1'].value;
//sigup the user
firebase.auth().createUserWithEmailAndPassword(email, password).then(()=>{
firebase.auth().onAuthStateChanged(function(user){
if(user){
user.updateProfile({
displayName: first_name
})
}
})
signup.reset();
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
window.alert("Error: " + errorMessage);
// ...
});
});
Once you have created the user, you can access user object provided by firebase. Using its updateProfile function, you can pass an object containing the properties you want the user object to have, like the code below:
var user = firebase.auth().currentUser;
user.updateProfile({
displayName: "Jane Q. User",
photoURL: "https://example.com/jane-q-user/profile.jpg"
}).then(function() {
// Update successful.
}).catch(function(error) {
// An error happened.
});
This worked for me.
firebase.auth().createUserWithEmailAndPassword(email, password).then(cred=>{
cred.user.updateProfile({
displayName: first_name + " " + last_name
})
})
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
window.alert("Error: " + errorMessage);
// ...
});

Firebase Authentication setup in Java Script

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]
});

Issue with Javascript window.location redirecting

I have an app which is written in HTML, CSS, Javascript. I am able to login using Google Authentication. I use
window.location = '/home.html'
for redirecting from index.html to home.html. Home.html has 5 list item menu options. However, clicking one specific list item menu displays index.html for a brief amount of time (which it should not be doing).
Here is the authentication JavaScript code.
function google_login_in(){
var provider = new firebase.auth.GoogleAuthProvider();
provider.addScope('https://www.googleapis.com/auth/plus.login');
firebase.auth().signInWithPopup(provider).then(function(result) {
var token = result.credential.accessToken;
var user = result.user;
}).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
var email = error.email;
var credential = error.credential;
});
}
function print_user(user) {
user.providerData.forEach(function (profile) {
console.log("Sign-in provider: "+profile.providerId);
console.log(" Provider-specific UID: "+profile.uid);
console.log(" Name: "+profile.displayName);
console.log(" Email: "+profile.email);
console.log(" Photo URL: "+profile.photoURL);
});
}
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
print_user(user);
window.location = '/home.html'
} else {
google_login_in();
}
});
Any help is greatly appreciated.
<li><a class="Baskets" href="#Baskets" onClick="document.getElementById('BasketsContent')
.style.display='block';document.getElementById('CalendarContent')
.style.display='none';document.getElementById('BrowserContent')
.style.display='none';document.getElementById('AnalyticsContent')
.style.display='none';document.getElementById('SettingsContent')
.style.display='none';document.getElementById('UpgradeContent')
.style.display='none';document.getElementById('ShareContent')
.style.display='none';">
<img class="icon1" src="./images/basket.png">
<i class="baskets"></i>Baskets</a>
</li>
use window.location.href, this will help you to navigate to the file
for example
window.location.href = 'home.html'

firebaseAuth GoogleAuthProvider() signInWithRedirect

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

Categories