Firebase setting user data on registration - angularjs

I want to create an new user in my firebase. This is the code I´m using:
function createUser(email, password, username) {
ref.createUser({
email: email,
password: password
}, function(error) {
if (error === null) {
$activityIndicator.stopAnimating();
$scope.padding_error = null;
$scope.error = null;
logUserIn(email, password);
} else {
$activityIndicator.stopAnimating();
console.log(error.code);
switch (error.code) {
case "INVALID_EMAIL":
$scope.padding_error = "10";
$scope.error = "Falsche E-Mail Adresse oder falsches Passwort";
$scope.$apply();
case "INVALID_PASSWORD":
$scope.padding_error = "10";
$scope.error = "Falsche E-Mail Adresse oder falsches Passwort";
$scope.$apply();
case "EMAIL_TAKEN":
$scope.padding_error = "10";
$scope.error = "Diese E-Mail Adresse ist schon registriert";
$scope.$apply();
}
}
});
}
I want to store the username in addition to email and password somewhere in my firebase. How is this possible instantly after user registration?

If the registration is succesful you can simply push the email and password variables to firebase. See code below.
function createUser(email, password, username) {
ref.createUser({
email: email,
password: password
}, function(error) {
if (error === null) {
... Registration successful
$activityIndicator.stopAnimating();
$scope.padding_error = null;
$scope.error = null;
##NEWCODE HERE##
emailRef = new Firebase("<YOURFIREBASEURL>/accounts/"+username+"/email")
passRef = new Firebase("<YOURFIREBASEURL>/accounts/"+username+"/password")
emailRef.set(email)
passRef.set(password)
logUserIn(email, password);
} else {
... Something went wrong at registration
}
}
});
}

Related

Save data to firebase realtime database if OTP verification is done

enter code here
Submit=e=>{
e.preventDefault();
let data="";
this.setUpRecaptcha();
// window.alert("Appointment Done Successfully at time "+this.state.curTime+" ! Go to the home page");
var phoneNumber = this.state.contact;
console.log(phoneNumber)
var appVerifier = window.recaptchaVerifier;
firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
.then(function (confirmationResult) {
// SMS sent. Prompt user to type the code from the message, then sign the
// user in with confirmationResult.confirm(code).
window.confirmationResult = confirmationResult;
var code = window.prompt("enter OTP")
confirmationResult.confirm(code).then(function (result) {
// User signed in successfully.
var user = result.user;
alert("OTP is verified!!!");
this.data="doneit";
// ...
}).catch(function (error) {
// User couldn't sign in (bad verification code?)
// ...
alert("OTP verification failed");
});
}).catch(function (error) {
// Error; SMS not sent
// ...
alert("cann't send OTP use another Contact number")
});
//Data storage code
if(this.data=='doneit'){
firebase.database().ref("appoinment").push(
{
name:this.state.name,
email:this.state.email,
contact:this.state.contact,
age:this.state.age,
gender:this.state.gender,
Appointdate:this.state.Appointdate,
Description:this.state.Description,
date:this.state.curTime
}
);
alert(" Data saved successfully");
window.location.reload(false);
}
else{
alert("failed");
}
};
My code is as shown above. I want execution in such a way that if after submitting form Submit() will be called. Then it will check for OTP verification. If it is successful then only data will be stored at firebase realtime database
List item
Why don't you put the logic to save the data after the confirmation promise:
Submit=e=>{
e.preventDefault();
let data="";
this.setUpRecaptcha();
// window.alert("Appointment Done Successfully at time "+this.state.curTime+" ! Go to the home page");
var phoneNumber = this.state.contact;
console.log(phoneNumber)
var appVerifier = window.recaptchaVerifier;
firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
.then(function (confirmationResult) {
// SMS sent. Prompt user to type the code from the message, then sign the
// user in with confirmationResult.confirm(code).
window.confirmationResult = confirmationResult;
var code = window.prompt("enter OTP")
confirmationResult.confirm(code).then(function (result) {
// User signed in successfully.
var user = result.user;
alert("OTP is verified!!!");
this.data="doneit";
firebase.database().ref("appoinment").push({
name:this.state.name,
email:this.state.email,
contact:this.state.contact,
age:this.state.age,
gender:this.state.gender,
Appointdate:this.state.Appointdate,
Description:this.state.Description,
date:this.state.curTime
});
alert(" Data saved successfully");
window.location.reload(false);
// ...
}).catch(function (error) {
// User couldn't sign in (bad verification code?)
// ...
alert("OTP verification failed");
});
}).catch(function (error) {
// Error; SMS not sent
// ...
alert("cann't send OTP use another Contact number")
});
};

How to know user is already login at another browser in firebase

I have reactjs admin panel for my project admin module. I have requirement that is if 2 user have same userId and password then both of them can not login in same time. If User1 already has logged into admin panel then User2 should not be login. I have get Id token of logged in user and saved it into database now I wanted to check whether the user is already login or not.
I dont have any idea how to prevent user to login in admin panel if other user is already logged in.
Please show some light on code and suggest me right path to fulfill my requirement
Here is my code:
//AUTHENTICATION
var loggedIn = false;
var activeSession = true;
if (Config.firebaseConfig.apiKey) {
firebase.auth().onAuthStateChanged(function (user) {
// Retriving ID Token
var Auth = firebase.auth();
var idToken = Auth.currentUser.getToken();
firebase.database().ref('activeSession').push({
idToken:idToken,
userEmail : user.email,
userId: user.uid,
isUserLoggedIn : activeSession
});
firebase.auth().verifyIdToken(idToken).then(function(decodedToken) {
console.log(decodedToken);
var uid = decodedToken.uid;
console.log(uid);
// ...
}).catch(function(error) {
// Handle error
});
}).catch(function(error) {
// Handle error
console.log(error);
});
if (user) {
// User is signed in.
console.log("User is signed in " + user.email);
if (Config.adminConfig.allowedUsers != null && Config.adminConfig.allowedUsers.indexOf(user.email) == -1) {
//Error, this user is not allowed anyway
alert("The user " + user.email + " doens't have access to this admin panel!");
firebase.auth().signOut();
} else {
loggedIn = true;
displayApp();
}
} else {
// No user is signed in.
console.log("No user is signed in ");
loggedIn = false;
displayApp();
if (window.display) {
window.display();
}
}
} else {
// No user is signed in.
console.log("No user is signed in, step 1 ");
loggedIn = false;
displayApp();
if (window.display) {
window.display();
}
}
function displayApp() {
if (loggedIn) {
ReactDOM.render(
<Admin />,
document.getElementById('root')
);
} else {
ReactDOM.render(
<Login />,
document.getElementById('root')
);
}
}
displayApp();

undefined is not an object (evaluating 'storeDataFactory.createUser(user).then

the function runs and console.log shows the user object on the backend. I don't understand why it's telling me there is an issue here, and really need some guidance.
vm.register = function() {
//check that passwords match
if(vm.password != vm.passwordRepeat) {
vm.registerError = "Passwords must match.";
return;
} else {
var username = vm.username;
// console.log("Valid form. Checking for existing user",username);
storeDataFactory.userExists(username).then(function(response){
//if user exists, return error
if(response.data.length > 0) {
vm.registerError = "A user with email " + username + " already exists. Please login.";
return;
} else {
//if no user exists
if(response.data.length == 0) {
// console.log("No user exists. Continue with registration.");
}
//assign info to user object
var user = {
username: vm.username,
password: vm.password,
name: vm.name,
phone: vm.phone
};
**storeDataFactory.createUser(user).then(function(response){**
vm.user = response.data;
console.log("Created user", vm.user);
if(response.data.length > 0) {
console.log("Created user", vm.user);
vm.registerMessage = "Successful registration, please login";
vm.registerError = null;
vm.user = response.data;
}
}).catch(function(error){
console.log(error);
vm.registerError = "There was an error creating your account.";
vm.registerMessage = null;
});
}
});
}
};
The backend code:
module.exports.register = function(req, res) {
console.log('registering user', req.body);
//create the user object with hashed pass
User
.create({
username: req.body.username,
name: req.body.name,
phone: req.body.phone,
password: bcrypt.hashSync(req.body.password, bcrypt.genSaltSync(10))
}, function(err, user) {
if (err) {
console.log("Error creating account");
res
.status(400)
.json(err);
} else {
console.log("Account created!", user);
res
.status(201)
.json(user);
}
});
};
Account created! and the user object are logged on the backend. It just won't display that damn Successful Registration! Please login. message.
storeDataFactory code:
/* global angular */ angular.module('rumbleApp').factory('storeDataFactory', storeDataFactory);
function storeDataFactory($http) {
return {
userExists: userExists,
createUser: createUser
};
function userExists(username) {
return $http.get('/api/users/userExists/' + username).then(complete).catch(failed);
}
function createUser(user) {
$http.post('/api/users/register', user).then(complete).catch(failed);
}
function complete(response) {
return response;
}
function failed(error) {
console.log(error.statusText);
return "There was an error with the API call.";
}
}
Are you sure you're returning from storeDataFactory.createUser()? Can you post the code for that method?
Sounds like the code is executing, but you're not returning anything from it (hence why it thinks it's undefined)

Firebase.child() Fails

For some reason it gives me the error
Uncaught Error: Firebase.set failed:
First argument contains undefined in property
'User Info.fcd90e70-3774-4098-8615-cedd85759757.Username'
I dont know what the reason is...
Here is registrationController.js:
NOTE: Ref is a Factory that gets my Ref for firebase..
app.controller('regController', ["$scope","AuthService","Ref", function($scope, AuthService, Ref){
//////////CHECKING FOR EMPTYNESS OF A VALUE/////////
function isEmpty(value){
return (value == null || value.length === 0);
}
/////////////////////////////////////////////////////
$scope.createUser = function(){
var username = $scope.usernameModel;
var email = $scope.emailModel;
var password = $scope.passwordModel
if(isEmpty(username) == false && isEmpty(email)== false && isEmpty(password)==false){
Ref.createUser({
email: email,
password: password
}, function(error, userData) {
if (error) {
switch (error.code) {
case 'EMAIL_TAKEN':
sweetAlert("Oops...", "This User is Already Created. Try Logging In", "error");
break;
case 'INVALID_EMAIL':
sweetAlert("Oops...", "The Email You Entered is Invalid", "error");
break;
case 'INVALID_PASSWORD':
sweetAlert("Oops...", "The Password You Entered is Invalid", "error");
break;
default:
sweetAlert("Oops...", "Error Creating this user : " + error, "error");
break;
}
}
else{
AuthService.User.email = $scope.emailModel;
AuthService.User.password = $scope.passwordModel;
AuthService.User.uid = userData.uid;
AuthService.User.username = $scope.usernameModel;
Ref.child("User Info").child(AuthService.User.uid).set({
Username: $scope.username,
Email: AuthService.User.email,
Password: AuthService.User.password,
UID: AuthService.User.uid
});
swal("Congratz!", "You are sucessfully authenticated", "success")
}
})
}
else{
if(true)
return false
else
return true;
}
}
}])

express res.send http code and text catch up by backbone.js

i try to programming a register with express and backbone.js. the express part looks like that
app.post('/signup', function (req, res) {
var name = req.param("name", null);
var country = req.param("country", null);
var email = req.param("email", null);
var cemail = req.param("cemail", null);
var password = req.param("password", null);
if (email !== cemail ||
!validate.Email(email) ||
email == null) {
console.log("There is something wrong with email address");
res.send(400, "Please check your email address.");
return;
};
if (password == null || !validate.Password(password)) {
console.log("There is something wrong with password");
res.send(400, "Password doesn't match security requirements");
return;
};
if (name == null || country == null) {
console.log("Some fields is not filled with value.");
res.send(400);
return;
};
signup(name, country, email, password);
res.send(200);
});
if an user give invalid email address, then it gonna respond with http code 400 and some text. Now my question is, how can i catch up this text, on the backbone.js site. it is possible or not. Frontend backbone.js code
$.post('/signup', {
name: $('input[name=name]').val(),
country: $('input[name=country]').val(),
email: $('input[name=email]').val(),
cemail: $('input[name=cemail]').val(),
password: $('input[name=password]').val()
}, function(data) {
console.log(data);
}).error(function(){
console.log("Sign up error");
});
return false;
the $.post error callback will be passed the response object and that will contain the text error message.
.error(function(response){
console.log("Sign up error", response.responseText);
});

Resources