Meteor : wait for a callback - asynchronous

WHen I create an account on my Meteor app, I check in several time the validity of each element. Then I create the user. If no error appeared, I show a success div, and an error one on the other case.
Accounts.createUser(options ,function(err){
if(err){
console.log("rorororororroro");
if(err.message == "Email already exists. [403]"){
Session.set('error', regAlert("This email adress already exists", tmpl));
}else{
Session.set('error', regAlert("Sorry, but an unidentified error occured. Please retry later. If the error persists, contact the support"));
}
}else if(Meteor.call('talknameIsAvailable', talkname)){
Session.set('error', regAlert("A user with this talkname already exists", tmpl));
}
});
if(!Session.get('error')){
$('#register-success').show("slow");
//console.log("[SUCCESS] Account created");
//document.location.href="/";
}else{
$('#register-error').show("slow");
}
The problem is that I always show the success div, as the last if / else is computed before the callback set the error session var when the email is already used.
What's the best way in Meteor to handle this case ?
Thanks you

When Session.get("error") is undefined, (!Session.get("error")) returns true.
try:
if (Session.get("error") !== void 0) {
}

I added .wait() at the end of the createUser function :
Accounts.createUser(options ,function(err){
if(err){
console.log("rorororororroro");
if(err.message == "Email already exists. [403]"){
Session.set('error', regAlert("This email adress already exists", tmpl));
}else{
Session.set('error', regAlert("Sorry, but an unidentified error occured. Please retry later. If the error persists, contact the support"));
}
}else if(Meteor.call('talknameIsAvailable', talkname)){
Session.set('error', regAlert("A user with this talkname already exists", tmpl));
}
}).wait();

Related

Disabling auth/user-not-found functionality

I have a React application with email & password sign in method available (implemented with firebase). In the log in form, if you enter incorrect email, you will get auth/user-not-found error as expected.
What are my options to disable this kind of behaviour? To me it seems to be a security risk where malicious user could query email addresses and see if the user exists on my platform or not.
You cannot disable what firebase would respond with, but you should handle the error in your client to show a less specific response.
try {
...
} catch (err) {
if (err.code === 'auth/user-not-found') {
alert("Invalid email address and/or password")
} else {
console.log("Other error handling method")
}
}

How to print user readable section of PlatformException from Firebase Login with Flutter?

While working on my Login Page, I want to show a login error. I'm successfully printing the following as error...
PlatformException(sign_in_failed, FIRAuthErrorDomain, The email
address is badly formatted.)
How can I only print/show
The email address is badly formatted
?
I'm not saying this is the best way to implement or I don't know whether this is the only way to do , but this is how I implemented it. Right now it works perfectly.
void showErrorToast(String error) {
//I call this method if I got any error message from firebase authentication
if (error.contains('email address is badly formatted')) {
error = 'Check your email once..';
}
if (error.contains('no user record corresponding to this identifier')) {
error = 'Hmm... no user found with this email.';
}
if (error.contains('password is invalid')) {
error = 'oho... seems like your password is wrong';
}
Fluttertoast.showToast(
msg: error,
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIos: 1,
backgroundColor: Colors.black,
textColor: Colors.white);
}
you can print out all the error message as below:
Eg error:
PlatformException(ERROR_EMAIL_ALREADY_IN_USE, The email address is already in use by another account., null)
print(e);//as in above
print(e.code); //ERROR_EMAIL_ALREADY_IN_USE
print(e.message);//The email address is already in use by another account.
print(e.details);//null

Getting the error: "No such email address for user." when calling Accounts.sendVerificationEmail( userId ) in meteor

I am getting an error when I try to send an email verification link to the user. I have used the email feature of Meteor in other projects without any issues. But in the current project, I am getting this error and I have no idea what could be causing it.
The user.emails[0].address does have an email address.
Exception while invoking method 'sendVerificationLink' Error: No such email address for user.
at AccountsServer.Accounts.sendVerificationEmail (packages/accounts password/password_server.js:745:11)
at [object Object].sendVerificationLink(server/user/users_methods.js:25:23)
I am using METEOR#1.3-beta.11 and my code is as follows:
**Client:**
let user = { email: signupEmail,password: password }
Accounts.createUser(user, (err) => {
if(!err) {
Meteor.call('sendVerificationLink');
}
})
**Server:**
Meteor.startup(function () {
process.env.MAIL_URL = 'smtp://postmaster%40sandboxd9...7.mailgun.org:<pwrd>#smtp.mailgun.org:587';
});
...
Meteor.methods({
sendVerificationLink() {
let userId = Meteor.userId();
if ( userId ) {
return Accounts.sendVerificationEmail( userId );
}
}
});
process.env.MAIL_URL and mailgun is set correctly. I have tested it from server using the following server code and the email was delivered correctly.
Email.send({
to: "xxxxx#gmail.com",
from: "xxxxx#gmail.com",
subject: "Example Email",
text: "This is a test email."
});
I found the error after a day of wasted debugging. There is nothing wrong in the code I posted above in my original question. There was an error in the schema definition for User collection with another package that I had installed - jagi:astronomy. The validation rule for 'Verified' (email verified flag) was set to string. It should have been boolean. I still don't understand why that would prevent from sending out the verification email though. Email field validation itself was correct and email was saved. But once I changed the validation rule to Boolean for 'Verified' field to boolean, the error went away.

Meteor - get email address of attempted login

I need to get the email address that a user was using in a failed login attempt to check if they registered outside of the application.
Here is my code;
Accounts.validateLoginAttempt(function(info){
if (!info.allowed)
{
console.log("we don't have that user " + info.user.emails[0]['address']);
return false;
} else {
var user = info.user;
console.log("created " + user.createdAt);
console.log("emails is " + user.emails[0]['address']);
return true;
}
});
If the login is not allowed I get this Cannot read property 'emails' of undefined because obviously the user is not in the users collection. My question is, is the email and password of the attempted login somehow available to see?
Try this:
Accounts.validateLoginAttempt(function(info) {
console.log("user");
console.dir(info.methodArguments[0].user);
console.log("password");
console.dir(info.methodArguments[0].password);
});
EDIT: Also, I wrote a Meteor package to solve this problem, available on Atmosphere at https://atmospherejs.com/chipcastledotcom/accounts-email.

Apigee 401 Unauthorized with token_expired

I'm trying to create a user account through the apigee JS API. This worked just fine when I was last doing this before the holidays in mid December. Now, however, I get a 401 Unauthorized error reading token_expired.
Is there a way to refresh the token? I don't know why it would have expired.
This is what I'm trying. First I instantiate the data client. No problems here:
var dataClient;
var client_creds = {
orgName: '*******',
appName: '*******'
}
dataClient = new Apigee.Client(client_creds);
Later, when trying to create a new user, I get the token_expired error:
dataClient.request(options, function (error, response) {
if (error) {
console.log(response);
alert("Something went wrong when trying to create the user. " + response.error)
// Error
} else {
// Success - the user has been created, now login.
dataClient.login(user.email, user.password,
function (err) {
if (err) {
//error - could not log user in
console.log("There was an error logging in " + user.name);
} else {
//success - user has been logged in
}
}
);
}
});
I've also tried dataClient.signup, but same error.
There are no refresh tokens within App Services; you'll need to follow the login flow in order to retrieve a new token. Note that you can specify the ttl parameter, like so, so you don't need to do this as frequently:
https://api.usergrid.com/{org}/{app}/token?ttl=604800
By default, this is set to 7 days, but you can change the default app max ttl to 0 (non-expiring) or something else like 31104000000 (365 days).
To do that, you make a PUT request:
https://api.usergrid.com/{org}/{app}/?client_id={app_client_id}&client_secret={app_client_secret}
With JSON payload:
{
"accesstokenttl":0
}
Or for 1 year:
{
"accesstokenttl":31104000000
}
If that doesn't work for you, the authorization tokens for the JavaScript SDK are kept in your browser's local storage. In Chrome, use the Developer Tools. In the Resources tab on the left hand side expand the Local Storage entry. You should see something like "http://usergrid.dev" or something similar. Choose that and on the right hand side you should see an entry for accessToken. Delete that and it should solve your problem.

Resources