I need to maintain a user login in firebase - javascript

I have a page that autheticate the login, but i have two types of users, one adm e other a shopkeeper, after login, they are redirect to their respective pages, how can i maintain their login after redirect the pages after logging? I'm using firebase.
i'm trying to use persistence, but i dont know how it works properly.
$("#btnLogin").click(function(){
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)
.then(function(){
var email = $("#inputEmail").val();
var senha = $("#inputSenha").val();
if(email != "" && senha != ""){
var login = firebase.auth().signInWithEmailAndPassword(email, senha);
login.then(function(result){
window.location.href = "";
}).catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
alert("não foi possível conectar");
console.log(errorMessage);
});
}else{
window.alert("Preencha todos os campos!");
}
}).catch((error)=>{
var errorCode = error.code;
var errorMessage = error.message;
alert("Erro percistencia");
console.log(errorMessage);
});
});

To keep an active session, we usually save a token in the "local storage" and make a request to the server to check if the token is linked to a user.

Related

JavaScript stops working when I refresh page

I have this block of JavaScript code:
var input = document.getElementById("password_field");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("login").click();
}
});
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
document.getElementById("user_div").style.display = "block";
document.getElementById("login_div").style.display = "none";
var user = firebase.auth().currentUser;
if(user != null) {
var email_id = user.email;
var email_verified = user.emailVerified;
document.getElementById('user_para').innerHTML = "You are logged in as<strong> " + email_id + "</strong>.";
if (email_verified === false) {
document.getElementById('user_verified').innerHTML = "<strong>You are not verified. Please check for an email from perason for a verification link. You will not be able to access anything without verification.";
} else {
document.getElementById('user_verified').innerHTML = "";
document.getElementById('sandboxaccess').style.display = "block";
}
}
} else {
document.getElementById("user_div").style.display = "none";
document.getElementById("login_div").style.display = "block";
}
});
function login () {
var userEmail = document.getElementById('email_field').value;
var userPass = document.getElementById('password_field').value;
firebase.auth().signInWithEmailAndPassword(userEmail, userPass).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
window.alert("Error: " + errorMessage);
});
}
function logout() {
firebase.auth().signOut();
}
It works fine initially, but when I refresh the page, all of the JavaScript stops working. It works perfectly fine on Apache localhost (refreshing works on localhost too). What is the solution to this?
Here it is before refresh:
before refresh
Here it is after refresh:
after refresh
The logout button is in both.
Errors on console
Remove this line of code from your program:
var user = firebase.auth().currentUser
You already have a user object as the parameter of your callback function. The currentUser returned here might actually be wrongly null and overwriting the correct one being passed in.
I think the code is executed before the DOM is loaded.
how about this:
document.addEventListener('DOMContentLoaded', function (){
// your code
});

firebase.auth() error in createusermethod in java Script

This is my java script for Register page for web using firebase authentication.When i fill the email and password till Alert message Testing will execute but firebase.auth()..... it will not execute and the page will get refresh automatically.
var email=document.getElementById("inemail").value;
var password=document.getElementById("inpass").value;
var password1=document.getElementById("inpass1").value;
var lPassword=password.length;
var lPassword1=password1.length;
if(lPassword < 7)
{
alert("Password Should more than seven Charecter");
return;
}
else if(password!=password1){
alert("Correctly Enter the Password");
return;
}
else if(password==password1 || lPassword1==lPassword)
{
alert("Testing");
firebase.auth().createUserWithEmailAndPassword(email.toString(),password.toString()).catch(function(error) {
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);
});
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
var email = user.email;
alert("Sucessfully Created");
}
else {
alert("sorry Try again");
}
});
}
}
in This script have any errors?if it have error please help me to find-out.
As Ticherhaz explains in his comment, your need to use the then() method to detect when the Promise returned by the asynchronous createUserWithEmailAndPassword() method is fulfilled.
The following should do the trick:
firebase.auth().createUserWithEmailAndPassword(email.toString(),password.toString())
.then(userCredential => {
var email = userCredential.user.email;
alert("Sucessfully Created");
})
.catch(function(error) {
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);
});
}
Note that, as explained in the doc, "on successful creation of the user account, this user will also be signed in to your application", so you don't need to use the onAuthStateChanged() method in this case.
In one of your comments above you say "only till alert message 'testing' this script is executing". Actually, if there is no error with the new user creation, the rejection handler callback passed to catch() is not called and therefore you don't get a feedback on the fact that the createUserWithEmailAndPassword() was correctly executed. For that you need the then() method.

firebase login wrong password

I need help, i keep getting an error where, whenever i log in it keeps saying wrong password even though i typed it correctly, registering the account is fine and it auto logs in but the moment i sign out the account, refresh and then log in it keeps saying wrong password, can anyone help me with this?
function loginbtn(){
//[then signs in the new user]
var loginEmail = document.getElementById('txtEmail').value;
var loginPass = document.getElementById('txtPass').value;
if (loginEmail.lenght <= 0){
alert('Please enter an email address.');
}
if (loginPass.lenght <= 0){
alert('Please enter a password.');
}
// Sign in with email and pass.
firebase.auth().signInWithEmailAndPassword(loginEmail, loginPass).catch(function(error){
// Handle Errors here.
var errorCode = error.code;
var errorMsg = error.message;
// [START_EXCLUDE]
if (errorCode ==='auth/wrong-password'){
alert('Wrong password.');
} else {
alert(errorMsg);
}
console.log(error);
document.getElementById('btnLogin').disabled = false;
});
// [END authwithemail]
//disables the button after logging in
document.getElementById('btnLogin').disabled = true;
}
This is the right way to signin correctly:
firebase.auth().signInWithEmailAndPassword(loginEmail , loginPass)
.then(function(firebaseUser) {
// Success
})
.catch(function(error) {
// Error Handling
});

How to keep user logged in with Firebase no matter what?

I am developing an app under the Ionic Framework and I am also using Firebase.
Now, it happens that after a few hours or for a crash of the app or restarting the device, the Authentication is lost.
How can I manage to have my user ALWAYS logged in, no matter what happen ? (Like Facebook for example)
Here is my Login Controller from the page login.html :
.controller('loginController',['$scope', '$firebaseArray', 'CONFIG', '$document', '$state', function($scope, $firebaseArray, CONFIG, $document, $state) {
// Perform the login action when the user submits the login form
$scope.doLogin = function(userLogin) {
if($document[0].getElementById("user_name").value != "" && $document[0].getElementById("user_pass").value != ""){
firebase.auth().signInWithEmailAndPassword(userLogin.username, userLogin.password).then(function() {
var userId = firebase.auth().currentUser.uid;
firebase.database().ref('accounts/' + userId + '/currentBusiness/').update({
name: "No current business arround",
description: "Seems there's nothing arround...",
})
$state.go("tab.favorites");
}, function(error) {
// An error happened.
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode === 'auth/invalid-email') {
alert('Enter a valid email.');
return false;
}else if (errorCode === 'auth/wrong-password') {
alert('Incorrect password.');
return false;
}else if (errorCode === 'auth/argument-error') {
alert('Password must be string.');
return false;
}else if (errorCode === 'auth/user-not-found') {
alert('No such user found.');
return false;
}else if (errorCode === 'auth/too-many-requests') {
alert('Too many failed login attempts, please try after sometime.');
return false;
}else if (errorCode === 'auth/network-request-failed') {
alert('Request timed out, please try again.');
return false;
}else {
alert(errorMessage);
return false;
}
});
}else{
alert('Please enter email and password');
return false;
}//end check client username password
};// end $scope.doLogin()
}])
I will answer my own question because I found the solution :
In my case, you have to use this code :
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
$state.go("tab.favorites");
// User is signed in.
} else {
// No user is signed in.
}
});
Try to store Login in a sharedPreferences or with an external resources once logged in, and then remove value when an user logs out.

Use user credentials to login to facebook using javascript sdk

I am using Javascript sdk with a facebook app to create login page for user.
FB.login prompts the user to enter facebook username and password. I have saved all the info such as user_id, Access_token, and all info. However, when the user logout. I want to login to facebook without the need to re-enter username and password again. i want to use the user-id and access token to login directly using the javascript API.
Thanks
function updateButton(response) {
button = document.getElementById('fb-auth');
userInfo = document.getElementById('user-info');
testbut = document.getElementById('test');
var rr = getResponse("user_profile.xml");
if(rr != null)
{
response = rr;
}
if (response.authResponse) {alert('me/permissions/?access_token='+
response.authResponse.accessToken);
FB.api('me/permissions/?access_token='+ response.authResponse.accessToken
,function(response)
{
for (var name in response) {
alert(response.data);
}
alert(response);
});
//user is connected
FB.api('/me', function(info) {
login(response, info);
});
button.onclick = function() {
FB.logout(function(response) {
logout(response);
});
};
} else {
//user is not connected
button.innerHTML = 'Login';
button.onclick = function() {
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(info) {
login(response, info);
});
} else {
//user cancelled login or did not grant authorization
showLoader(false);
}
},
{scope:'email,user_birthday,status_update,publish_stream,user_about_me'});
}
}
}
// run for the current status and whenerve it is changed
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.statusChange', updateButton);
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol
+ '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
function login(response, info){
if (response.authResponse) {
ajaxFunction(response);
var accessToken = response.authResponse.accessToken;
userInfo.innerHTML = '<img src="https://graph.facebook.com/' + info.id
+ "<br /> Your Access Token: " + accessToken;
button.innerHTML = 'Logout';
document.getElementById('other').style.display = "block";
}
}
function logout(response){
userInfo.innerHTML = "";
document.getElementById('debug').innerHTML = "";
document.getElementById('other').style.display = "none";
}
You have to store User access token in your database to user for next time.
Here is some small hint to pass access token using javascript sdk
FB.api('me/permissions/?access_token=Your access token',function(response){console.log(response)});
Chiming in a bit late, but my guess is you are trying to login using an expired or invalidated short-term access token. For future logins, you should convert the short-term access token to a long-term access token, good for about 60 days. The conversion to a long-term token needs to happen on your server as it requires your app-secret. Details are here. The long-term token is what you should be storing in your database (or similar) for future use.

Categories

Resources