To access the content of my app (under ionic), my users have to log in first. Sometimes, the app crashes and it "logs the user out" (well in fact it loses the session but firebase has the user still logged in).
I would like to use the local storage method but I am having a hard time understanding how to put the code together.
I found this tutorial here : Use local storage to login user
And here is my controller :
console.log(window.localStorage.getItem("username"));
console.log(window.localStorage.getItem("password"));
console.log(window.localStorage.getItem("uid"));
// 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 != ""){
// Setup the loader
window.localStorage.setItem("username", $document[0].getElementById("user_name").value);
window.localStorage.setItem("password", $document[0].getElementById("user_pass").value);
$ionicLoading.show({
content: 'Loading',
animation: 'fade-in',
showBackdrop: true,
maxWidth: 200,
showDelay: 0
});
firebase.auth().signInWithEmailAndPassword(userLogin.username, userLogin.password).then(function() {
window.localStorage.setItem("uid", firebase.auth().currentUser.uid);
var userId = window.localStorage.getItem("uid");
firebase.database().ref('accounts/' + userId + '/currentBusiness/').update({
name: "No current business arround",
description: "Seems there's nothing arround...",
})
$state.go("tab.account");
}, function(error) {
// An error happened.
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode === 'auth/invalid-email') {
alert('Enter a valid email.');
$timeout(function () {
$ionicLoading.hide();
}, 1000);
return false;
}else if (errorCode === 'auth/wrong-password') {
alert('Incorrect password.');
$timeout(function () {
$ionicLoading.hide();
}, 1000);
return false;
}else if (errorCode === 'auth/argument-error') {
alert('Password must be string.');
$timeout(function () {
$ionicLoading.hide();
}, 1000);
return false;
}else if (errorCode === 'auth/user-not-found') {
alert('No such user found.');
$timeout(function () {
$ionicLoading.hide();
}, 1000);
return false;
}else if (errorCode === 'auth/too-many-requests') {
alert('Too many failed login attempts, please try after sometime.');
$timeout(function () {
$ionicLoading.hide();
}, 1000);
return false;
}else if (errorCode === 'auth/network-request-failed') {
alert('Request timed out, please try again.');
$timeout(function () {
$ionicLoading.hide();
}, 1000);
return false;
}else {
alert(errorMessage);
$timeout(function () {
$ionicLoading.hide();
}, 1000);
return false;
}
});
}else{
alert('Please enter email and password');
return false;
}//end check client username password
};// end $scope.doLogin()
// Create a callback which logs the current auth state
if (window.localStorage.getItem("username") !== null && window.localStorage.getItem("password") !== null) {
$state.go("tab.account");
} else {
console.log("wooooooo");
}
Any help to integrate both ?
Related
I have a function that creates a new user through Firebase Auth, and for awhile I had it working but now it's returning undefined. I tried using async await to wait for an input with no help, and I'm not really sure what could be going wrong. I can't include my Firebase auth code on here, but I put the rest of the code on CodePen:
https://codepen.io/TheNomadicAspie/pen/ZEKYwWJ
And here are the relevant function:
function newUserSubmitEmail() {
traceFunction()
new_user_dict['email'] = input_text.value.trim()
console.log('newUserSubmitEmail email is ', new_user_dict['email'])
question.innerText = "What password would you like to use?"
input_text.value = ''
right_button.onclick = newUserSubmitPassword
}
function newUserSubmitPassword() {
traceFunction()
new_user_dict['password'] = input_text.value.trim()
console.log('newUserSubmitPassword password is ', new_user_dict['password'])
question.innerText = "Ok, and enter it one more time just to make sure there's no typos."
input_text.value = ''
right_button.onclick = newUserVerifyPassword
}
function newUserVerifyPassword() {
traceFunction()
if (new_user_dict['password'] === input_text.value) {
newUserSubmitEmailAndPassword()
} else {
question.innerText = "Those passwords didn't match. Let's try again."
console.log('newUserVerifyPassword old password was ', new_user_dict['password'], ' new password is ', input_text.value)
input_text.value = ''
right_button.onclick = newUserSubmitPassword
}
}
async function newUserSubmitEmailAndPassword() {
traceFunction()
console.log('newUserSubmitEmailAndPassword email is ', new_user_dict['email'], ' password is ', new_user_dict['password'])
input_text.value = ''
firebase.auth().createUserWithEmailAndPassword(await new_user_dict['email'], await new_user_dict['password']).then((userCredential) => {
console.log('newUserSubmitEmailAndPassword User created successfully')
userCreatedSuccessfully()
})
.catch(async (error) => {
var errorCode = await error.code
var errorMessage = error.message
question.innerText = errorCode
console.log('newUserSubmitEmailAndPassword Error creating user. Error code: ', errorCode, ' ', errorMessage)
if (errorCode === 'auth/email-already-in-use') {
newUserEmailInUse()
} else if (errorCode === 'auth/invalid-email') {
newUserTryEmailAgain()
} else if (errorCode === 'auth/operation-not-allowed') {
errorPleaseRefresh()
} else if (errorCode === 'auth/weak-password') {
newUserTryPasswordAgain()
}
})
}
Any ideas?
Maybe it's because you use the await in the wrong place. The code is written with async/await like this:
try {
const userCredentials = await firebase
.auth()
.createUserWithEmailAndPassword(
new_user_dict["email"],
new_user_dict["password"]
);
console.log(
"newUserSubmitEmailAndPassword User created successfully",
userCredentials.user
);
// comment out this
//userCreatedSuccessfully();
} catch (error) {
var errorCode = await error.code;
var errorMessage = error.message;
question.innerText = errorCode;
console.log(
"newUserSubmitEmailAndPassword Error creating user. Error code: ",
errorCode,
" ",
errorMessage
);
if (errorCode === "auth/email-already-in-use") {
newUserEmailInUse();
} else if (errorCode === "auth/invalid-email") {
newUserTryEmailAgain();
} else if (errorCode === "auth/operation-not-allowed") {
errorPleaseRefresh();
} else if (errorCode === "auth/weak-password") {
newUserTryPasswordAgain();
}
}
error occur in second argument of signInWithPhoneNumber() and i am not able to fix this problem, in there is three method i used for send otp, verify otp and last on for captcha
methods:{
sendOTP(e){
e.preventDefault();
if(this.phoneNo.length!=10){
alert('Invalid No.');
}else{
let countryCode="+91"
let phoneNumber=countryCode+ this.phoneNo
let appVerifier=window.recaptchaVerifier
firebase.default.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
.then(function (confirmationResult){
console.log(confirmationResult);
window.confirmationResult=confirmationResult;
alert('SMS sent')
}).catch(function(err){
console.log(err);
alert('SMS not sent')
});
}
},
this method for verify OTP using firebase
verifyOTP(e){
e.preventDefault();
if(this.phoneNo.length!=10||this.otp.length!=6){
alert('Invalid format')
}
else{
let vm=this
let code=this.otp
//var user
window.confirmationResult.confirm(code).then(function (result){
console.log(result);
var user = user.result
vm.$router.push({path:'/home'})
})
}
},
here i initial the captcha method
initReCaptcha(){
setTimeout(()=>{
//let vm = this
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container', {
'size': 'invisible',
'callback': function() {
// reCAPTCHA solved, allow signInWithPhoneNumber.
// ...
},
'expired-callback': function() {
// Response expired. Ask user to solve reCAPTCHA again.
// ...
}
});
//
this.appVerifier = window.recaptchaVerifier
},1000)
},
here i created captcha
created(){
this.initReCaptcha()
}
Well, I am creating a news feed website. Each user will be able to upload its own events. I am trying to create a section in my firebase database of the users, but I am not able of send variables to the arguments.
firebase.auth().createUserWithEmailAndPassword(email, password).then(function(){
var user = firebase.auth().currentUser;
console.log(user);
if (user) {
// User is signed in.
user.updateProfile({displayName: document.getElementById("name").value});
var user_id = user.id;
var user_email = user.email;
var user_display_name = user.displayName;
//Saving info in the data base.
var database = firebase.database();
database.ref('users/' + user_id).set({
displayName: user_display_name,
id: user_id,
email: user_email
});
window.location = "index.html"
} else {
alert("Something went wrong.");
}
UPDATED VERSION:
window.onload = function(){
var createButton = document.getElementById("createButton");
var signin_button = document.getElementById("signin_button");
createButton.onclick = function(){
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
firebase.auth().createUserWithEmailAndPassword(email, password).then(function(result){
console.log('result', result);
if (result) {
// User is signed in.
result.updateProfile({displayName: document.getElementById("name").value});
var user_info = {id: result.uid, email: result.email, display_name: result.displayName};
console.log('user_info', user_info);
// Storing user info into database.
var database = firebase.database();
console.log('user id', user_info.id);
database.ref().child('usersss/' + user_info.id).push({
displayName: user_info.display_name,
id: user_info.id,
email: user_info.email
});
window.location = "index.html"
} else {
alert("Something went wrong.");
}
})
.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 if (errorCode == 'auth/email-already-in-use') {
alert('The email is already in use.');
} else if (errorCode == 'auth/invalid-email') {
alert('The email is not valid.');
}else if (errorCode == 'auth/operation-not-allowed') {
alert('This operation is not allowed.');
}else{
alert(errorMessage);
}
console.log(error);
})
}
signin_button.onclick = function(){
window.location = "login.html";
}
}
If nothing exists at 'users/' + user_id you need to use 'push' instead of 'set'. For example:
database.ref().child('/users/' + user_id).push({
//your code
try that.
Here's an action generator I use to log a user into firebase:
export var startLoginWithEmailAndPassword = (email, password) => {
firebase.auth().signInWithEmailAndPassword(email, password).then((result) => {
//handle success
console.log('worked', result);
}).catch((error) => {
//handle error
console.log('error', error);
});
}
In the above case, the 'result' object will have the user details.
My problem is to add data to the database by taking the information from a form.
I want to add the information as "name". I can add "email" correctly but not other data.
My code:
buttonsignup.addEventListener('click', error => {
var nameCompany = document.getElementById('nameCompany').value;
var email = document.getElementById('email').value;
});
function add(nameCompany,email) {
firebase.database().ref().child('users_company').push({
nameCompany: nameCompany,
email: email
});
}
function intFirebase () {
/*CURRENT USER*/
firebase.auth().onAuthStateChanged(function(user) {
if (user != null) {
console.log(user);
console.log('El UID es '+user.uid);
add(nameCompany,user.email);
} else {
console.log('No user is signed in.');
}
});
}
window.onload = function() {
intFirebase();
}
Okay, After turning the coffee into code. I found this solution. But ... Is it a good practice?
const database = firebase.database();
var user = firebase.auth().currentUser;
/* BOTON SIGNUP */
buttonsignup.addEventListener('click', error => {
var nameCompany = document.getElementById('nameCompany').value;
var email = document.getElementById('email').value;
var password_1 = document.getElementById('password_1').value;
var password_2 = document.getElementById('password_2').value;
if (password_1 == password_2) {
if (password_1.length < 8) {
console.log('ContraseƱa muy corta');
document.getElementById("errorPassword").innerHTML = "8 characters";
} else {
firebase.auth().createUserWithEmailAndPassword(email, password_1).then (function(result) {
add(nameCompany,email);
}).catch(function (error) {
var errorCode = error.code;
var errorMessage = error.message;
};
});
}
} else{
console.log('errorPassword');
}
});
function add(nameCompany,email) {
firebase.database().ref().child('users_company').push({
nameCompany: nameCompany,
emailCompany: email
});
}
function intFirebase () {
/*CURRENT USER*/
firebase.auth().onAuthStateChanged(function(user) {
if (user != null) {
console.log(user);
console.log('El UID es '+user.uid);
} else {
console.log('No user is signed in.');
}
});
}
window.onload = function() {
intFirebase();
}
And database rules
{
"rules": {
"users_company": {
"$uid": {
".read": "auth != null && auth.uid === $uid",
".write": true,
//Change this code to: I can not do scripts in the database. -> ".write": "auth != null && auth.uid === $uid",
"nameCompany" : {
".validate": "newData.isString() && newData.val().length < 100"
},
"emailCompany" :{
".validate": "newData.isString() && newData.val().length < 100"
}
}
}
}
}
In your intFirebase function you are only calling your database if there is a current user already logged in. The reason your email is working, is only because you are using 'user.email,' after it sees that a user is indeed logged in.
If you are trying to create a new user (which I think that is what your event listener at the top is trying to do), then you should move your add function to fire off when you submit the form.
I'm having quite a hard time understanding how to chain promises. I'm writing login function for my app, leverating Loopback's Angular SDK. The objective, upon validating a user's credentials, is to confirm that the user's account is active, then fetch some additional properties including the user's role and set a flag to true if the user has admin privileges.
Here's my code...
$scope.login = function (user) {
User.login(user).$promise.then(
function (data) {
$rootScope.activeUser = data;
$rootScope.user_id = $rootScope.activeUser.user.username;
console.log('Active User: ', $rootScope.activeUser.user.email);
console.log('Status: ', $rootScope.activeUser.user.status);
if ($rootScope.activeUser.user.status === 'Y') {
$scope.loginError = false;
function checkAdmin(eid) {
Se_user.findById({
id: eid
}).$promise.then(
function (data1) {
var user_properties = data1;
if (user_properties.role === 'Admin') {
$rootScope.isAdmin = true;
console.log('isAdminInside: ', $rootScope.isAdmin);
return true;
} else {
//$rootScope.isAdmin = false;
return false;
}
});
};
var isAdmin = checkAdmin($rootScope.user_id);
console.log('isAdminOutside: ', $rootScope.isAdmin);
$state.go('home');
} else {
$scope.loginError = true;
$scope.loginErrorMessage = "Your account has been disabled. Please contact BMT Support for assistance";
}
},
function (err) {
console.log('Error: ', err)
$scope.loginError = true;
$scope.loginErrorMessage = "You've entered an invalid User ID or Password. Please try again.";
});
};
I've been troubleshooting by writing to the console, here's a sample of the output...
Active User: user#email.com
Status: Y
isAdminOutside: undefined
isAdminInside: true
How should I restructure so that the result of checkAdmin is properly returned after a successful login of an active user?
Try changing this part of code :
function checkAdmin(eid) {
return Se_user.findById({
id: eid
}).$promise.then(
function(data1) {
var user_properties = data1;
if (user_properties.role === 'Admin') {
$rootScope.isAdmin = true;
console.log('isAdminInside: ', $rootScope.isAdmin);
return true;
} else {
//$rootScope.isAdmin = false;
return false;
}
});
};
var isAdmin = checkAdmin($rootScope.user_id)
.then(function(val) {
console.log('isAdminOutside: ', val);
$state.go('home');
});