parse.com user.signup fails with error - javascript

Below is my code to signup for a new user
var Account = Parse.Object.extend('Account');
account = new Account();
account.set("serviceTax", TAX.SERVICE_TAX);
account.set("educationCess", TAX.EDUCATION_CESS);
account.set("name", accountName);
var user = new Parse.User();
user.set(USER.USER_NAME, username);
user.set(USER.PASSWORD, password);
user.set(USER.EMAIL, username);
user.set(USER.FIRST_NAME, firstName);
user.set(USER.LAST_NAME, lastName);
user.set(USER.PHONE_NUMBER, phoneNumber);
user.set(USER.COMPANY_NAME, companyName);
user.set(USER.ACCOUNT_NAME, accountName);
user.set(USER.ACCOUNT, account);
user.signUp(null, {
success : function(user) {
$('.gifload').toggle();
bootstrap_alert.info("alert_placeholder", "User created successfully");
},
error : function(user, error) {
$('.gifload').toggle();
bootstrap_alert.error("alert_placeholder", error.message);
}
});
I am getting the following error in this signup "user objects cannot allow writes from other users"
Now as far i can tell, we are not updating any user, just creating one with an account object. Why am i getting this error? Any help on this will be deeply appreciated.

Related

Is it possible to retrieve user attributes from aws cognito in javascript on page load (Before login)?

I am using AWS cognito and successfully fulfilling all my requirements. However, there is a scenario is which I am struggling. I have an Auth code field along with username and password on login page and my requirement is to populate that auth code field before logging in.
I am successfully retrieving user attributes after login but in this case, I need to retrieve a user attribute before login to populate the input field.
My question is that is it possible to fetch a specific user attribute (Auth Code) before even login?
Below is the code for your reference that I am using to retrieve user attributes on clicking login button. Please have a look.
function signInButton() {
var authcode = document.getElementById("authcode").value;
var authenticationData = {
Username : document.getElementById("inputUsername").value,
Password : document.getElementById("inputPassword").value,
Authcode : document.getElementById("authcode").value,
};
var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);
var poolData = {
UserPoolId : _config.cognito.userPoolId, // Your user pool id here
ClientId : _config.cognito.clientId, // Your client id here
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var userData = {
Username : document.getElementById("inputUsername").value,
Pool : userPool,
};
var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
var userid = document.getElementById("inputUsername").value;
console.log('userid: ',userid)
if(authcode=='1234'){
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
var accessToken = result.getAccessToken().getJwtToken();
/////Getting User Attributes//////
AWS.config.update({region:'us-east-1'});
var params = {
AccessToken: accessToken
};
var cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
cognitoidentityserviceprovider.getUser(params, function(err, data) {
if (err) {
console.log(err, err.stack);
} // an error occurred
else{
console.log(data);
} // successful response
})
/////// End /////////
if(accessToken!=null || accessToken!=''){
$.post("testapi.php", {userid: userid}, function(result){
console.log('result: ',result);
if(result.includes("accept")){
window.open("landing.php?status=Logged In","_self");
}else{
alert('Unauthorized User ID. Please try again with correct ID!')
}
});
}
console.log(accessToken);
},
onFailure: function(err) {
alert(err.message || JSON.stringify(err));
window.open("landing.php?status=Not Logged In","_self");
},
});
}else{
alert('Incorrect Authentication Code. Please try again');
}
}
Please suggest a possible solution.
Thank you

How to add username with email and password in Firebase?

I'm using Firebase and I'm trying to add a username to the database with the email and password.
Is there a way to do it or is createUserWithEmailAndPassword() function only for email and password?
signUp.addEventListener("click", function(user)
{
var username = usernameTxt.value;
var email = emailTxt.value;
var password = passwordTxt.value;
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error)
{
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode == 'auth/email-already-in-use')
{
alert('email-already-in-use.');
}
else
{
alert(errorMessage);
}
console.log(error);
});
});
The solution that i found to how to add username with the createUserWithEmailAndPassword() function:
firebase.auth().onAuthStateChanged(function(user) {
var username = usernameTxt.value;
if (user) {
firebaseDataBase.ref('users/' + user.uid).set({
email: user.email,
uid : user.uid,
username: username
});
console.log("User is signed in.");
} else {
console.log("No user is signed in.");
}
});
You need to create that database users child node yourself ;-)
The createUserWithEmailAndPassword function only creates a new user in Firebase authentication service. The database itself isn't changed at all as a result.
To add this new user to the database as well, try:
firebase.database().ref("users").child(user.uid).set(...)
This cannot be done through createUserWithEmailAndPassword() but there is a firebase method for this . You will need to listen for when authentication state is changed , get the user , then update the profile info . See Below
This code would come after createUserWithEmailAndPassword()
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// Updates the user attributes:
user.updateProfile({ // <-- Update Method here
displayName: "NEW USER NAME",
photoURL: "https://example.com/jane-q-user/profile.jpg"
}).then(function() {
// Profile updated successfully!
// "NEW USER NAME"
var displayName = user.displayName;
// "https://example.com/jane-q-user/profile.jpg"
var photoURL = user.photoURL;
}, function(error) {
// An error happened.
});
}
});
As stated in firebase User Api here : https://firebase.google.com/docs/reference/js/firebase.User#updateProfile
Hope this helps
You can create a users endpoint and store custom user data in there.
function writeUserData(userId, name, email, imageUrl) {
firebase.database().ref('users/' + userId).set({
username: name,
email: email,
profile_picture : imageUrl,
// Add more stuff here
});
}
Have a look to https://firebase.google.com/docs/database/web/read-and-write

How to sign up user and then keep them signed in and access current user Parse Server?

I am trying to get a user to sign up, I have the HTML form working etc. I just need to handle the sign up itself.
The user is successfully created BUT I'm not sure how to keep the user logged in or access the current user logged in as a Parse.User object.
app.post("/sign-up", function (req, res) {
var userObject = new Parse.User();
userObject.set("username", username);
userObject.set("password", password);
userObject.set("email", email);
userObject.set("supportEmail", email);
userObject.signUp(null, {success: function(user) {
//success
res.redirect('/admin');
},
error: function(user, error) {
//show error
console.log(error.message);
res.render('sign-up', {success:false, errorMessage:error.message});
}
});
});
Not sure what to do in order to keep them logged in and to acess the Parse.User object for the current user.
you can save in global variable in your application. also you can export user object to use in other files. There is another way to store in database or one other way is to app.locals.user = userObject
var userObject = new Parse.User();
app.post("/sign-up", function (req, res) {
userObject.set("username", username);
userObject.set("password", password);
userObject.set("email", email);
userObject.set("supportEmail", email);
app.locals.user = userObject;
userObject.signUp(null, {success: function(user) {
//success
res.redirect('/admin');
},
error: function(user, error) {
//show error
console.log(error.message);
res.render('sign-up', {success:false, errorMessage:error.message});
}
});
module.exports.userObject = userObjetct;
The signup promise resolves in an authentication object along with the session token.
Then you can use it and call Parse.User.become to retrieve the user class.
Parse.User.become("session-token-here").then(function (user) {
// The current user is now set to user.
}, function (error) {
// The token could not be validated.
});
Source: http://parseplatform.github.io/docs/js/guide/#setting-the-current-user

Cloud Code Not Updating User's Username Properly

For some reason Cloud Code isn't updating the current user's username, even though it is updating the email field. I'm using the master key, and although everything returns success, the username doesn't update (even on the data browser).
Here's my code:
//Get Current User
var user = Parse.User.current();
//Update username
user.set("email", request.params.email);
user.set("username", request.params.username);
user.save(null, {
//Success
success: function(user) {
//Done
response.success("Username saved! 🎉");
},
//Error
error: function(user, error) {
// Execute any logic that should take place if the save fails.
response.error("Aww man. Something went wrong. Please try again. 😅");
}
});
I've made sure that the parameters are being passed correctly, and that there isn't a mistake with the name etc on my iOS app.
My guess is that there is an issue with getting the calling user.
Use request.user to get the calling user and try the following.
// Get the requesting user
var user = request.user;
if (user) {
user.set("email", request.params.email);
user.set("username", request.params.username);
user.save(null, {
success: function(user) {
response.success("Username saved! 🎉");
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
} else {
response.error("Aww man. Something went wrong. Please try again. 😅");
}

Can't write user data to firebase

I'm new at this so bear with me. I'm trying to use the fire base simple login with the email and password. I have that working with this:
var authClient = new FirebaseAuthClient(fireRef, function(error, user) {
if (error) {
// an error occurred while attempting login
if(error.code === "INVALID_EMAIL"){
$('#log_email_error').hide();
$('#log_pass_error').hide();
$('#log_email_error').html("Invalid email specified.").fadeIn();
$('.login_button').removeClass('login_button_success').attr('value','Log in');
}
if (error.code === "INVALID_PASSWORD") {
$('#log_email_error').hide();
$('#log_pass_error').hide();
$('#log_pass_error').html("The specified password is incorrect..").fadeIn();
$('.login_button').removeClass('login_button_success').attr('value','Log in');
}
console.log(error);
} else if (user) {
// user authenticated with Firebase
hideLogin();
$('.userInfo_cont').show();
$('.userInfo').html('<div> '+ user.email + ' <span class="grey">| </span> </div>');
$('.logout').on('click',function(){
authClient.logout();
});
console.log('User ID: ' + user.id + ', Provider: ' + user.provider);
} else {
// user is logged out
$('.userInfo_cont').hide();
showLogin();
}
});
But when the user registers I want to store some additional info in a firebase/users area
which I can do with this in the registration:
$('#submit_reg').on('click',function(){
var firstName = $('#regFirstname').val();
var lastName = $('#regLastname').val();
var email = $('#regUsername').val();
var password = $('#regPassword').val();
authClient.createUser(email, password, function(error, user) {
if (!error) {
console.log('User Id: ' + user.id + ', Email: ' + user.email);
authClient.login('password', {
email: email,
password: password,
rememberMe: false
});
hideLogin();
userInfo = {
userId : user.id,
firstName : firstName,
lastName : lastName,
email : user.email
}
var url = USERS_LOCATION + "/" + user.id;
var userRef = new Firebase(url);
console.log(userInfo);
userRef.set(userInfo);
}else{
//display error
alert(error);
}
});
});
My Problem is when I implement the read write rules like the documentation has:
{
"rules": {
"users":{
"$userid": {
".read": "auth.id == $userid",
".write": "auth.id == $userid"
}
}
}
}
I get a permission denied when the user registers. So it registers the user just fine but won't write the additional data to the /users/id area.
Any help would be much appreciated.
Craig
In the snippet above, you're calling login(), and then immediately calling set() afterwards. This is problematic because the login() method is asynchronous, and you are almost always guaranteed to have called set() method prior to the return of the login attempt method, since login() is non-blocking yet makes a network call to the Firebase servers.
This means that even though you're calling login() with the correct email and password, you're trying to set the data before the authentication process has completed.
I would recommend moving your set() logic into a block that will only be executed when you are certain that the user has already authenticated, such as in the callback you passed when calling new FirebaseAuthClient() and detected a logged in user.

Categories

Resources