This question already has an answer here:
How come Angular doesn't update with scope here?
(1 answer)
Closed 8 years ago.
I'm writing my first angularjs app, and it's beginning to make sense. However, I have a sign up form that isn't getting the messages in some cases to alert users to problems. I'm using Firebase to authenticate, which works fine. But I'm storing users by a unique username as the key. So before I run the $createUser function, I do a quick query to see if there's already a user object with this key-- if not, I create the user.
The problem is when there is an existing user with this username. The console log value prints fine, but the error message (bound to $scope.authMsg) doesn't show up the first time-- but if I click the "register" button again, then the message shows up in the expected message div.
Any hints on the message issue (or suggestions for this code) would be appreciated!
$scope.register = function() {
$scope.authMsg = '';
var ref = new Firebase(FIREBASE_URL);
$scope.authObj = $firebaseAuth(ref);
// check if the username is taken
ref.child("/users/"+$scope.account.username).on("value", function(snapshot) {
if (snapshot.val()) {
//
// PROBLEM HERE!!
//
$scope.authMsg = 'Username exists-- did you forget your password?'; // doesn't show on page until second submit
console.log('Username exists-- did you forget your password?'); // prints to console as expected
} else {
$scope.authObj.$createUser({ email: $scope.account.email, password: $scope.account.password })
.then(function(userData) {
console.dir(userData);
return $scope.authObj.$authWithPassword({
email: $scope.account.email,
password: $scope.account.password
});
}).then(function(authData) {
// we created a user and are now logged in-- store user info
var userdata = {};
userdata[$scope.account.username] = {
uid: authData.uid,
first_name: $scope.account.first_name,
last_name: $scope.account.last_name,
email: $scope.account.email,
full_name: $scope.account.first_name+' '+$scope.account.last_name
};
var usersRef = ref.child("users");
// save the userdata
usersRef.set(userdata);
console.log("Logged in as:", authData.uid);
$state.go('app.dashboard');
}).catch(function(error) {
$scope.authMsg = error;
console.error("Error: ", error);
});
}
}, function (errorObject) {
$scope.authMsg = 'The read failed: ' + errorObject.code;
console.log('The read failed: ' + errorObject.code);
});
};
I'm assuming, the Firebase callback does not involve an angular digest cycle.
To handle this, write
if (snapshot.val()) {
$scope.$apply(function() {
$scope.authMsg = 'Username exists— did you forget your password?';
});
A useful reading about the topic: http://jimhoskins.com/2012/12/17/angularjs-and-apply.html
Related
I want to get some parameters and use them to reset password function from firebase.
This is how my link looks like:
http://localhost:8080/passwordreset?mode=resetPassword&oobCode=y6FIOAtRUKYf88Rt5OlEwxUuTyEmb3M4gquZSIseX2UAAAFevpj-gw&apiKey=AIzaSyBaCCvq-ZEfQmdrL7fmElXDjZF_J-tku2I
I want to get mode, oobCode and apiKey.
Here is what I have for now:
export default {
data: function() {
return {
passwordNew: '',
passwordConfirm: '',
mode:'',
actionCode: '',
continueUrl: '',
}
},
methods: {
handleResetPassword: function() {
var accountEmail;
firebase.auth().verifyPasswordResetCode(actionCode).then(function(email) {
var accountEmail = email;
firebase.auth().confirmPasswordReset(this.actionCode, this.passwordNew).then(function(resp) {
alert("Password reset success");
this.$router.push('hello')
}).catch(function(error) {
// Error occurred during confirmation. The code might have expired or the
// password is too weak.
console.log("error 1")
});
}).catch(function(error) {
// Invalid or expired action code. Ask user to try to reset the password
// again.
console.log("error 2")
});
},
}
}
From Firebase documentation:
Some user management actions, such as updating a user's email address
and resetting a user's password, result in emails being sent to the
user. These emails contain links that recipients can open to complete
or cancel the user management action. By default, user management
emails link to the default action handler, which is a web page hosted
at a URL in your project's Firebase Hosting domain.
link: https://firebase.google.com/docs/auth/custom-email-handler
You need to get those parameters and store them on variables, from firebase documentation i got those snippets and just wrote the getParameterByName function:
function getParameterByName( name ){
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
// Get the action to complete.
var mode = getParameterByName('mode');
// Get the one-time code from the query parameter.
var actionCode = getParameterByName('oobCode');
// (Optional) Get the continue URL from the query parameter if available.
var continueUrl = getParameterByName('continueUrl');
You need to get those parameters first and verify the actioncode on the verifyPasswordResetCode method, then you can change the password and store it along with the action code to the method.
In your export default :
data: function() {
return {
passwordNew: '',
passwordConfirm: '',
mode: mode,
actionCode: actionCode,
continueUrl: continueUrl,
}
},
methods: {
handleResetPassword: function() {
var passwordNew = this.passwordNew
var actionCode = this.actionCode
firebase.auth().verifyPasswordResetCode(actionCode).then(function(email) {
console.log("ActionCode: "+ actionCode);
firebase.auth().confirmPasswordReset(actionCode, passwordNew).then(function(resp) {
alert("Password reset success");
this.$router.push('hello')
}).catch(function(error) {
console.log("error 1"+ error)
});
}).catch(function(error) {
console.log("Action code is invalid"+ error)
});
},
}
I am developing application based on Parse-server and I want to offer social login. I found this guide in the documentation http://docs.parseplatform.org/js/guide/#linking-users.
I started to implement the social login by google. I did following steps:
1) I added following lines to the ParseServer settings
var api = new ParseServer({
...
auth:{
google: {}
},
...
});
2) I did the authentication by hello.js on the client side (call user._linkWith function on login)
hello.init({
google: 'My Google id'
});
hello.on('auth.login', function(auth) {
// Call user information, for the given network
hello(auth.network).api('me').then(function(r) {
const user = new Parse.User();
user._linkWith(auth.network, auth.authResponse).then(function(user){
console.log('You are logged in successfully.');
});
});
});
When I debugged it, I found that it fails in _linkWith() function, when provider object is preparing. Object AuthProviders, which should store all providers, is empty. Because of it the statement provider = authProviders['google']; leads to undefined. Invoking provider.authenticate(...); leads to error "Cannot read property 'authenticate' of undefined"
What am I missing or what am I doing wrong?
Thanks for all your answers.
Honza
Did you register the authenticationProvider? You can find examples in our unit tests on how to do so:
https://github.com/parse-community/parse-server/blob/5813fd0bf8350a97d529e5e608e7620b2b65fd0c/spec/AuthenticationAdapters.spec.js#L139
I also got this error and looked at the _linkWith(provider, options) source code. It checks if options has an authData field (which in turn should contain id and credentials). If so, it uses options.authData. Otherwise it falls back on looking up a previously registered authentication provider mentioned in the previous answer.
This is a fragment of the code I'm using:
const authData = {
"id": profile.getId(),
"id_token": id_token
}
const options = {
"authData": authData
}
const user = new Parse.User();
user._linkWith('google', options).then(function(user) {
console.log('Successful user._linkWith(). returned user=' + JSON.stringify(user))
}, function(error) {
console.log('Error linking/creating user: ' + error)
alert('Error linking/creating user: ' + error)
// TODO handle error
})
I have the following object:
var user = {
firstName: req.body.first_name,
lastName: req.body.last_name,
email: req.body.email,
password: "",
id: "",
};
Now what I'm trying to do is post a request to the API and if the user is successfully saved in the database, it will return a user id as well as a password (Which can then be emailed to the person)..
request.post({
url: process.env.API_SIGNEDIN_ENDPOINT + "users/store",
form: user,
headers: {
Authorization: "Bearer " + req.session.authorization
}
}, function(error, response, body) {
// Check the response
var theResponse = JSON.parse(response.body);
if(theResponse.code == 400)
{
var error = [
{param: "email", msg: "This email address has already been taken!", value: ""}
];
res.render("create", {
errors: error,
});
}else{
var theUser = JSON.parse(body);
user.password = theUser.password;
user.id = theUser.id;
}
});
This is working fine, however, whenever I try to output user it's not updating the user object outside of this post. The user object is fine and it's working, the issue seems to be from when I try and access the user from this result callback. Any ideas?
EDIT:
Let's say I have "address1" (This is the persons main address) and I have "address2" (This is the persons second address).. The person might only have 1 address and therefore I only need to save one address. However using the logic that place everything in the .then() means I cannot do this because the user might not have 2 addresses but I still need to access the main address, for example:
mainAddress.save().then(function(addressData) {
var theAddressLicenceTick = req.body.address_licence;
if(theAddressLicenceTick)
{
var subAddress = models.addresses.build({
address_1: "asasfasf",
city: "asfafsaf",
postcode: "asfasf",
created_at: new Date(),
updated_at: new Date();
});
subAddress.save().then(function(subAddress) {
// continue integration
// would I have to do the functionality again?
});
}else{
// The user only has one address
}
});
Essentially, I have a customer table which can have multiple addresses through a link table. But I believe that there is an easier way instead of writing all of this code?
I'm making an app that allows user to like and comment on other user post. I'm using Parse as my backend. I'm able to notified user everytime their post liked or commented. However if current user like or comment on their own post this current user still notified. How can I prevent this?
Here is the js code that I use:
Parse.Cloud.afterSave('Likes', function(request) {
// read pointer async
request.object.get("likedPost").fetch().then(function(like){
// 'post' is the commentedPost object here
var liker = like.get('createdBy');
// proceed with the rest of your code - unchanged
var query = new Parse.Query(Parse.Installation);
query.equalTo('jooveUser', liker);
Parse.Push.send({
where: query, // Set our Installation query.
data: {
alert: message = request.user.get('username') + ' liked your post',
badge: "Increment",
sound: "facebook_pop.mp3",
t : "l",
lid : request.object.id,
pid: request.object.get('likedPostId'),
lu : request.user.get('username'),
ca : request.object.createdAt,
pf : request.user.get('profilePicture')
}
}, {
success: function() {
console.log("push sent")
},
error: function(err) {
console.log("push not sent");
}
});
});
});
If I understand the context of where this code is correctly,
I recommend checking
if request.user.get("username") != Parse.CurrentUser.get("username")
Before sending out the push notification
Where is your cloud function being called from? If you're calling it from your ios code, then before you call the cloud code function, just prelude it with something like this:
if (PFUser.currentUser?.valueForKey("userName") as! String) != (parseUser.valueForKey("userName") as! String)
Below is a snippet of my code where I begin by searching the collection of notes to see if any of them contain the username that I am changing my current session's username to. If the username has not yet been used, it may be changed to that so I change the current session's username and then I update every note to be under this new username then display a changesuccess.jade file. However, when I run the code everything appears to run fine exept the username for each note doesn't change. I feel like it's due to the find() method on the 5th line. Any help would be greatly appreciated!
router.post('/changeusername',function(req, res) {
var newUsername = req.body.username;
var user = req.session.username;
var userFound = notesCollection.find( { owner: newUsername } )
var results = function(infoInput) {
res.render("changedUser.jade", {title: "Username Change",
info: infoInput});
}
var checkChange = function(err) {
if (err) {
results("Username change failed!");
} else {
results("Username changed!");
}
}
console.log(userFound);
if (!userFound.length) {
notesCollection.update({ owner: user },
{ owner: newUsername},
{ multi: true },
checkChange);
} else {
res.render("changedUser.jade", {title: "Username Change",
info: "Username change failed!"});
}
});
If i understand your problem correctly, you are trying to update a collection in mongodb and it is not getting updated.
So the problem is with the way you are calling mongoose#update.
Since you want to update 'owner', you should use mongodb#$set
Mongoose supports the same $set operator in the conditions too.
So just a little correction for your case:
var conditions = { owner: user }
, update = { $set: { owner: newUsername }}
, options = { multi: true };
notesCollection.update(conditions, update, options, callback);
function callback (err, numAffected) {
// numAffected is the number of updated documents
})
So try this now.