Parse.com on Signup User name already exists, code 142 - javascript

Update: Solved, happens to be incorrect Cloud Code I wrote, see update #3
I am trying to make a signup for user using Parse.com API in Javascript.
Still with no success.
Basically I have a user field and a password field, and when hit signup button, tries to login but always I have the "Error Code: 142 :User name already exists, try login error from Parse api.
What is wrong with the code? (I previously used c# code and it was success)
Thanks in response.
function onSignupButtonClicked(button) {
event.preventDefault();
game_username = $("#loginUserText").val();
game_password = $("#loginPasswordText").val();
parseLogout(); // tried both logout earlier or put here..
var user = new Parse.User();
user.set("username", game_username);
user.set("password", game_password);
var progressCircle = showProgressCircle(); //some fullscreen progress
//also tried user.signup(null, {.. with no luck
Parse.User.signUp(game_username, game_password, {}, {
success: function(user) {
// Hooray! Let them use the app now.
//NOW LOGIN
login(game_username, game_password).then(function(result) {
console.log(result); // "Stuff worked!"
hideProgressCircle(progressCircle);
$("#loginButton").attr("disabled", true);
$("#logoutButton").attr("disabled", false);
$("#signupButton").attr("disabled", true);
game_manualLogin = true;
isLoggedIn = true;
}, function(err) {
hideProgressCircle(progressCircle);
console.log("loginPromise: " + err.message + " code: " + err.code); // Error: "It broke"
handleParseError(err);
});
},
error: function(user, error) {
// Show the error message somewhere and let the user try again.
hideProgressCircle(progressCircle);
handleParseError(error);
}
});
}
update:
Even basic Parse.com javascript returns 142.. here is the code, and my location is Istanbul/Turkey
function register() {
var user = new Parse.User();
user.set("username", "testop");
user.set("password", "testop");
user.set("email", "email#example.com");
// other fields can be set just like with Parse.Object
user.set("phone", "415-392-0202");
user.signUp(null, {
success: function(user) {
// Hooray! Let them use the app now.
console.log("testop register ok!");
},
error: function(user, error) {
// Show the error message somewhere and let the user try again.
alert("Error: " + error.code + " " + error.message);
}
});
}
This is the error I get to above updated code
Error:code: 142 :User name already exists, try login (Code is from Parse Javascript Signup
Update #2:
Even Rest API gives same error:
MacBook-Pro:~ gg$ curl -X POST \
> -H "X-Parse-Application-Id: MYAPPID" \
> -H "X-Parse-REST-API-Key: MYRESTAPIKET" \
> -H "X-Parse-Revocable-Session: 1" \
> -H "Content-Type: application/json" \
> -d '{"username":"testdude","password":"tesdude","phone":"415-392-0202"}' \
> https://api.parse.com/1/users
{"code":142,"error":"User name already exists, try login"}
MacBook-Pro:~ gg$
UPDATE #3:
After checking with 3 apis, found that problem was my fault.
I forgot a Cloud Code on user save, which was faulty as it did not check length of query length..
Parse.Cloud.beforeSave(Parse.User, function(request, response) {
var username = request.object.get("username");
var usernamequery = new Parse.Query(Parse.User);
usernamequery.equalTo("username", username);
usernamequery.find({
success: function()
{
--->>>should be checking length of query here <<<---
console.log("same user name found");
response.error("User name already exists, try login");
},
error: function(error)
{
console.log("ok unique user name continue save");
response.success("OK saving user");
}
});
});

You need two forms, one for signing up (as a new user) which calls Parse.User.signUp and a second form (for returning users) that calls Parse.User.logIn.
The problem is that you can only 'sign up' once with a username and password, after which you should 'login'. Also when you have got a success callback from Parse.User.signUp then the user is logged in and you don't have to call 'login'.
Something like this (where the two event listeners are triggered by two different buttons).
SIGNUP
function onSignupButtonClicked(button) {
event.preventDefault();
game_username = $("#loginUserText").val();
game_password = $("#loginPasswordText").val();
Parse.User.signUp(game_username, game_password, {}, {
success: function(user) {
// A new user has signed up and is now the Parse.User.current() user
// Do something
},
error: function(user, error) {
// Show the error message somewhere and let the user try again.
}
});
}
LOGIN
function onLoginButtonClicked(button) {
event.preventDefault();
game_username = $("#loginUserText").val();
game_password = $("#loginPasswordText").val();
Parse.User.logIn(game_username, game_password, {}, {
success: function(user) {
// An existing user has logged in and is now the Parse.User.current() user
// Do something
},
error: function(user, error) {
// Show the error message somewhere and let the user try again.
}
});
}
More info here: https://parse.com/docs/js_guide#users-signup

Related

Console says onsubmit function doesn't exist for register form, even though it clearly does

So I have a register form, as thus:
<form name="register" action="" method="POST" onsubmit="register()" autocomplete="off">
...
</form>
And I know that every child of this form is functioning.
Then, below in a <script> tag I have my main function which is called when the above form is submitted. And I know that everything outside of the register function is running. However, when I input random values into each field of my form, and press submit, the console shows that the register() function called in the onsubmit attribute of my form does not exist. I can't seem to find the problem here:
//Global Vars
var firebaseConfig = { ...
};
firebase.initializeApp(firebaseConfig);
var db = firebase.firestore();
var registerButton = document.querySelector("#registerButton");
//Main Register Function
function register() {
event.preventDefault();
//Locally Global Variables
var fullName = document.forms["register"]["fullName"].value;
var username = document.forms["register"]["username"].value.toLowerCase();
//The MD5 is a way to hash the password, that way the real password is safe and only the hash is used
var password = md5(document.forms["register"]["password"].value);
var serviceProvider = document.forms["register"]["serviceProvider"].value;
//Simple If Statement that adds appropriate email suffix based on Service Provider
if (serviceProvider === "Verizon") {
serviceProvider = "#vtext.com";
} else if (serviceProvider === "ATT") {
serviceProvider = "#txt.att.net";
} else if (serviceProvider === "TMobile") {
serviceProvider = "#tmomail.net";
} else if (serviceProvider === "Sprint") {
serviceProvider = "#messaging.sprintpcs.com";
}
var phoneNumber = document.forms["register"]["phoneNumber"].value + serviceProvider;
var emailAddress = document.forms["register"]["emailAddress"].value;
//Checks The Database If The Username Is Already Taken Or Not
db.collection("Users").where("username", "==", username).get()
.then(function(querySnapshot) {
//Checks Each Individual Result -- If there are no results, than this code will not run
try {
querySnapshot.forEach(function(doc) {
//If any result exists, stop here
if (doc.data()) {
alert("I'm sorry but this username is already taken!! Please Try Another One");
throw "Error";
}
});
} catch (error) {
if (error === "Error") {
return;
}
}
//If not
//Add All Of The User Info To The Database
db.collection("Users").doc(username).set({
fullName: fullName,
username: username,
password: password,
phoneNumber: phoneNumber,
emailAddress: emailAddress,
chatsInvolvedIn: []
})
.then(function() {
//If it succeeds, give user the heads up and then take them to their new homepage
alert("Your account under the username " + username + " has been sucessfully created. You will now be redirected to your homepage.");
//Place Code Underneath to Handle Keeping user Logged In For Present and Future Visits, along with redirecting to a homepage
//Code Goes Here
db.collection("Users").doc(username).get().then(function(doc) {
if (doc.exists) {
localStorage.setItem("loggedIn", JSON.stringify(doc.data()));
}
alert(localStorage.getItem("loggedIn"));
//window.location.replace("index.html");
});
})
.catch(function(error) {
//If it fails, tell user to try again later (we don't care about the error message during production, because it is unlikely after our many tests)
alert("I'm sorry but your account was not successfully created due to an unexpected error. Please try again later.");
});
})
.catch(function(error) {
//If checking the database originally for duplicate usernames fails, then give the user the same warning as above
alert("I'm sorry but your account was not successfully created due to an unexpected error. Please try again later.");
});
}
I know that my programming practices above aren't the best. if you could help me out, that would be great, thank you!

Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist. when using message passing API

I am trying to build a password manager extension for Google Chrome. I want my background script to check for URLs matching with the login URLs of different websites and when it does match, I want to send the credentials of the user to the content script which will autofill the username and password fields. But I am getting the "Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist." error
I have seen similar questions and the major answer was to disable the other extensions and try again. I disabled all the extensions and tried, but still getting the same error. I also saw that long-lived connections solve this error, but I don't want to use a long-lived connection as this is a one time message
background.js
/*Listen for changes in URL */
chrome.tabs.onUpdated.addListener(function(tabId,changeInfo,tab){
if(changeInfo.url){
console.log(changeInfo.url);
chrome.storage.local.get(null,function(ans){
console.log("local storage",ans);
});
chrome.storage.local.get(['loggedIn'],function(answer){
console.log('logged in answer is',answer);
console.log('logged in answer is',answer.loggedIn);
if(answer.loggedIn===true){
console.log("user logged in")
/* Check whether the user is logged in and the url is in the user credential urls*/
chrome.storage.local.get(['urls'],function(result){
console.log("stored urls",result.urls,"current url",changeInfo.url);
if(result.urls.includes(changeInfo.url)){
console.log("matching url");
console.log("matching url",changeInfo.url);
var urlIndex = result.urls.indexOf(changeInfo.url);
console.log('index',urlIndex);
console.log("main tab id is",tabId)
console.log("tab is",tab);
chrome.storage.local.get(['credentials'],function(result){
console.log(result);
var username = result.credentials[urlIndex].username;
var password = result.credentials[urlIndex].password;
console.log('username',username,password)
var msg = {
username : username,
password : password
}
/* Get the credentials for that site and send it to the content script autoFill.js */
chrome.tabs.sendMessage(tabId,{args: msg},function(response) {
console.log(tabId,tab.url);
console.log(response);
});
});
}
});
}
else{
console.log("user not logged in");
}
});
}
})
content_script.js
console.log("content script is running");
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
console.log("message recieved");
console.log(request.args);
var args=request.args;
console.log('args',args);
var forms = document.getElementsByTagName("form");
console.log(forms);
for(let form of forms){
console.log(form);
for (let index = 0; index < form.length; index++) {
const element = form.elements[index];
//console.log(element);
if(element.type==='password'){
element.value=args.password;
console.log(element.value);
for (let reverseIndex = index-1; reverseIndex >= 0; reverseIndex--) {
const element = form.elements[reverseIndex];
if(element.type==='text'){
element.value=args.username;
break;
}
}
}
else{
continue;
}
}
}
sendResponse("success");
return true;
});
I am expecting the content script to receive the message and make the parameters available in the current tab. So any help about how to fix this error is much appreciated.
Thanks

Link Multiple accounts in Firebase

I have been stuck with this problem for a long time and i decided to post my problem here.
My problem is to merge the accounts (Facebook and Google) in Firebase. Independently sign-up with either one of them works fine.
At first when the user Sign-up with google and later with Facebook (that has the same email address with google) it throws and error. I managed to handle the error as you see on my code below but i don't know how to merge both accounts.
Here is what i have done so far:
facebookSignin: function() {
var self = this
firebase.auth().signInWithPopup(facebookProvider).then(function(result) {
var token = result.credential.accessToken;
var user = result.user;
self.registerProfile()
}).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
console.log("ERROR:" + error)
console.log("email is : " + error.email)
if (errorCode == 'auth/account-exists-with-different-credential') {
firebase.auth().fetchProvidersForEmail(error.email).then(providers => {
//providers returns this array -> ["google.com"]
console.log("Providers:" + providers)
console.log("Credential: " + JSON.stringify(error.credential))
firebase.auth().currentUser.link(error.credential).then(function(user) {
console.log("Account linking success", user);
});
}).catch(function(error){
console.log("error:" + error)
})
}
console.log("error code:" + error.code+ "error msg:" + error.message)
});
First i already Signed up with google
Now i want to login with Facebook with the same email address
I get the current-user null obviously because the user is not signed in, this is the error: error:TypeError: __WEBPACK_IMPORTED_MODULE_1_firebase___default.a.auth(...).currentUser is null .
I read the documentation about the merge part but still could not figure this out. https://firebase.google.com/docs/auth/web/account-linking#link-federated-auth-provider-credentials-to-a-user-account
I really appreciate the help.
After you fetchProvidersForEmail and figure out the existing Google user, you have to first login to that existing account:
firebase.auth().signInWithPopup(new firebase.auth.GoogleAuthProvider().setCustomParameters({login_hint: error.email})...
After that completes, you then:
firebase.auth().currentUser.linkWithCredential(error.credential)
So the user first has to verify ownership of the existing account before linking the Facebook account.

Regularly signed out when using firebase authWithPassword

I have a phonegap app on iOS using firebase for authentication. Logging in is done like so:
var afterLogin = function(error, authData) {
if (error) {
console.log(error);
messenger.error(error.message);
return;
}
$scope.loggedIn = $auth.check();
$scope.$apply();
$sync.sync();
messenger.success('Logged in');
};
$scope.doLogin = function() {
mixpanel.track('login');
if (!$scope.loginForm.email && !$scope.loginForm.password) {
messenger.error('Enter email and password then tap login');
return;
} else if (!$scope.loginForm.email) {
messenger.error('Enter your email then tap login');
return;
} else if (!$scope.loginForm.password) {
messenger.error('Enter your password then tap login');
return;
}
ref.authWithPassword({
email : $scope.loginForm.email,
password : $scope.loginForm.password
}, afterLogin);
}
I check a user's status like this:
check: function() {
var authData = ref.getAuth();
if (authData) {
mixpanel.identify(authData.uid);
mixpanel.people.set({
"$email": authData.password.email
});
}
return !!authData;
}
It works fine initially, but users get signed out and have to log in again after 12-24 hours of not using the app. Perhaps when the app is shunted out of memory? Obviously this is pretty frustrating, not sure what's causing this. The session length is set to 24 weeks, still having the problem.
Firebase version: 2.1.2
Angular: 1.3.6
Log of localStorage after authenticating with username and password:
Coming back a day later after being logged out:
Contents of the cookie (same logged in or not, no firebase stuff in there):
It's a parameter in Firebase.
Go on the Dashboard of the Firebase.
Click on "Login & Auth".
Then in the first paragraph, there is an input and select for the Session Length. You can choose how many hours/weekks, etc you want.

Parse JS add user with role

I am trying to basically have a sign up form that will sign up a user and also add that user that just signed up to a certan role. I got the app signing up the user fine but it isnt creating the role and adding the user to that role. Here is what I had
<script type="text/javascript">
Parse.initialize("key", "key");
//set the user
var user = new Parse.User();
$( "form" ).submit(function( event ) {
//get the input data
var username = $('#username').val();
var email = $('#email').val();
var password = $('#password').val();
var facility = $('#facility').val();
//Set the user info
user.set("facility", "" + facility + "");
user.set("username", "" + username + "");
user.set("email", "" + email + "");
user.set("password", "" + password + "");
//Sign them up
user.signUp(null, {
success: function(user) {
// Hooray! Let them use the app now.
//Make the role
var roleACL = new Parse.ACL();
roleACL.setPublicReadAccess(true);
var role = new Parse.Role("Pro", roleACL);
role.getUsers().add(username);
role.save();
//Show and Hide the alert
$('#successModal').modal('show');
setTimeout(function(){
$('#successModal').modal('hide')
}, 4000);
//Clear the form
$( 'form' ).each(function(){
this.reset();
});
},
error: function(user, error) {
// Show the error message somewhere and let the user try again.
alert("Error: " + error.code + " " + error.message);
}
});
return false
});
</script>
My thought was create the user then on successful user creation create the role and add the user to that role. Seems not to be working though.
code the querys a user
querys a role
then adds the user to the role
var qu = new Parse.Query(Parse.User);
var qr = new Parse.Query(Parse.Role);
qr.get(roleId, {
success: function(role) {
_role = role;
qu.get(userId, {
success: function(user) {
_role.getACL().setRoleReadAccess(_role, true);
_role.getUsers().add(user);
_role.save();
response.success(_role.toJSON());
},
error: function(object, error) {
console.log('got role, failed on get user');
}
});
The aim is to add the newly saved user to an existing role, so that role must be queried, not created when the user is saved.
Since you must the save of a user, query a role, and save that role -- three asynch operations that must be performed in sequence -- it's advisable to use promises, lest the code become unreadably indented, so...
// prepare the user as you have it, then
user.signUp().then(function(user) {
// query the role, you can get it with the role name
var roleQuery = new Parse.Query(Parse.Role);
roleQuery.equalTo("name", "Pro");
return roleQuery.first();
}).then(function(role) {
role.getUsers().add(user);
return role.save();
}).then(function() {
// no need to set a timer. with the promise, we know exactly when we are done
$('#successModal').modal('hide');
}, function(error) {
alert("Error: " + error.code + " " + error.message);
});
Be sure to first create the "Pro" role manually using the data browser. Read through the security section in the programming guide.
Also note, if this happens for every user, the role code is a good candidate to be part of an afterSave cloud function on PFUser.

Categories