How to tell whether Accounts.addEmail succeeded or failed, and if it failed, the reason why - api

I have a page where the user can type in a new email address and then this method attempts to add it to their account:
Meteor.methods({
add_new_email: function(address)
{
Accounts.addEmail(Meteor.userId(), address);
}
});
I'm using the accounts-password package in Meteor.
I'd like to give the user meaningful feedback after they try to add the new address, in particular if it failed why did it fail? I have looked at the docs but there doesn't seem to be any method to find out failure reason.
I know that I can count the user's email addresses before and after trying to add the new one, but that doesn't tell me if the address already belongs to another user, or if it's an existing address of the user's, or whatever is the failure reason.
Is there any way to find out the result of an API call like this?

You can read the information about what this method does here:
https://github.com/meteor/meteor/blob/master/packages/accounts-password/password_server.js#L847
As you can see, the method will fail only in one case:
The operation will fail if there is a different user with an email
only differing in case
Therefore if the method fails you can tell to the user that the email is already registered.

After experimenting some more, it seems that all I need to do is add a callback to my client when I call the method, and check there for an error. Any error is automatically returned to the callback.
Server:
Meteor.methods({
add_new_email: function(address)
{
Accounts.addEmail(Meteor.userId(), address);
}
});
Client:
Meteor.call('add_new_email', 'me#example.com', function(error){
if (error) console.log("got an error " + error.reason);
});
I had not realised that the error from the API would be passed up into my method. Meteor - it's always more clever than I expect!
Note also that you can use Meteor.Error in your methods to throw errors which will be passed up to client callbacks in exactly the same way, see the docs:
if (!Meteor.userId()) {
throw new Meteor.Error("not-authorized", "You must be signed in to write a new post");
}

I know I'm a bit late to the party but I ran into this problem today and found your post.
I needed to be able to tell on the server side whether it failed or not so what I did was put it in a try-catch like so:
let addSucceeded = false;
try{
Accounts.addEmail(user._id, newEmailAddress);
addSucceeded = true;
} catch(err) {}
console.log(addSucceeded);
Only if the Accounts.addEmail does not fail will addSucceeded be set to true. To make sure I don't run into the "fail because it replaced the same user's email address in a different case" scenario, I always toLowerCase() the email address when saving.

Related

Twilio mobile number verification - VerificationCheck was not found on Express

The requested resource /Services/serviceSSID/VerificationCheck was not found is the eroor showing in the console
my code is
otpLogin:async (req,res)=>{
console.log(req.body.otp);
try {
const isOTP = await client.verify.services(serviceSSID).verificationChecks.create({
to:`+91${req.body.phone}`,
code:req.body.otp
})
if(isOTP)console.log(isOTP);
return res.status(200).json({message:" mobile number verified"})
} catch (error) {
console.log(error.message)
return res.status(500).json({message:"something went wrong"})
}
}
Twilio developer evangelist here.
From the documentation:
Twilio deletes the verification SID once it’s:
expired (10 minutes)
approved
when the max attempts to check a code have been reached
If any of these occur, verification checks will return a 404 not found error like this:
Unable to create record: The requested resource /Services/VAXXXXXXXXXXXXX/VerificationCheck was not found
If you’d like to double check what happened with a given verification - please use the logs found in the Twilio Console under your Verification Service:
I've found that if you submit a form twice by clicking a submit button twice quickly, that the verification is successfully checked and then because it was a success deleted, then the second check fails with a 404 like this and that is the error result you see. To avoid this, you should stop users from being able to submit the form twice by disabling the submit button after the first attempt.
I can confirm that philnash 2nd statement is correct. However wouldn't it have been handled way better if instead we just get a response from client.verify.services(serviceSSID).verificationChecks that the 2nd (and so on checks) failed??

intermittent error from rally 'Not authorized to perform action: Invalid key' for POST request in chrome extension

I developed a chrome extension using Rally's WSAPI v2.0, and it basically does the following things:
get user and project, and store them
get current iteration everytime
send a post request to create a workitem
For the THIRD step, I sometimes get error ["Not authorized to perform action: Invalid key"] since end of last month.
[updated]Error can be reproduced everytime if I log in Rally website via SSO before using the extension to send requests via apikey.
What's the best practice to send subsequent requests via apikey in my extension since I can't control end users' habits?
I did see some similar posts but none of them is helpful... and in case it helps:
I'm adding ZSESSIONID:apikey in my request header, instead of user /
password to authenticate, so I believe no security token is needed
(https://comm.support.ca.com/kb/api-key-and-oauth-client-faq/kb000011568)
url starts with https://rally1.rallydev.com/slm/webservice/v2.0/
issue is fixed after clearing cookies for
https://rally1.rallydev.com/, but somehow it appears again some time
later
I checked the cookie when the issue was reproduced, and found one with name of ZSESSIONID and its value became something else rather than the apikey. Not sure if that matters though...
code for request:
function initXHR(method, url, apikey, cbFunc) {
let httpRequest = new XMLHttpRequest();
...
httpRequest.open(method, url);
httpRequest.setRequestHeader('Content-Type', ' application\/json');
httpRequest.setRequestHeader('Accept', ' application\/json');
httpRequest.setRequestHeader('ZSESSIONID', apikey);
httpRequest.onreadystatechange = function() {
...
};
return httpRequest;
}
...
usReq = initXHR ('POST', baseURL+'hierarchicalrequirement/create', apikey, function(){...});
Anyone has any idea / suggestion? Thanks a million!
I've seen this error when the API key had both read-only and full-access grants configured. I would start by making sure your key only has the full-access grant.

KeystoneJS: where are callHook hooks defined?

I want to add logic to the pre:signin and post:signin hooks, but can't find where they are defined. In admin/server/api/session/signin.js, I find the callHook()s for both, but can't find the actual hooks. Help greatly appreciated!
KeystoneJS is using grappling-hook . and thats why you can use callHook.
in node_modules/keystone/index.js you can see this code
var grappling = require('grappling-hook');
grappling.mixin(this).allowHooks('pre:static', 'pre:bodyparser', 'pre:session', 'pre:routes', 'pre:render', 'updates', 'signout', 'signin', 'pre:logger');
I am not sure but you are not finding the actual hooks because they really don't exist.
The methods are defined in keystone and grapple simply makes them hoockable. e.g signin is the method defined in keystone instance and grapple made it hoockable.
And here is the way you will just tell what to do after signing is completed.
keystone.callHook(user, 'post:signin', function (err) {
if (err) return res.json({ error: 'post:signin error', detail: err });
res.json({ success: true, user: user });
});
So in layman term you r saying.. Hay keystone, call my function after This user is signed in. and for that there is really no code inside keystone.
MY knowledge is limited here how the user is passed and how it happens that only when this user logged in. I think, we still need some experts light here.
I had a use-case that required a function be called every time a specific model was added to the database. I found out that you can use the Mongoose middleware specifically the post middleware to achieve such results. So in my case I had a Product schema in which I wanted a function to run everytime a new product was added or updated. It was as easy as adding the following:
keystone.lists.Product.schema.post('save',function(){
console.log('called after new item saved');});

Testing WCF with SoapUI

I need your help on one practical issue. I have created a WCF service with basic binding with two operation contact.
1- void StartRegistration - Anonymous member can fill the basic registration form and press submit. All the information will be stored into the database and one link with some random token will be send to user's email address.
2 - void CompleteRegistration - This method validates the token sent into the email address and if token is valid, user account will be activated.
Now I have issue here. Using SoapUI I can call StartRegistration method. Email is sent to destination but I want to pass the token to CompleteRegistration method.
Since it is a WCF service so can not do dependency injection to pass the SoapUI tests :).
Please help.
If I understand your question correctly, you have two WCF methods, one for creating a token and another for confirming it.
What I would do in this case is have the first method, StartRegistration, return the token. Then you could use that token to pass into the CompleteRegistration method quite easily in Soap UI.
Another, quite messy solution, would be to have a groovy script test step in Soap UI that actually connected to the mail account, read the link and parsed the contents.
Edited:
Here is part of the script you'll need. Place it in a groovy step, that will then return the token from your mail.
Note: This code assumes that mail is plain text, not multipart. It also assumes that the mail box only has a single mail. The API for JavaMail is pretty extensive, so if you want to do any magic with it, Google is your friend :) At least, this is somewhere to start.
import javax.mail.*;
import javax.mail.internet.*;
// setup connection
Properties props = new Properties();
def host = "pop3.live.com";
def username = "mymailadress#live.com";
def password = "myPassword";
def provider = "pop3s";
// Connect to the POP3 server
Session session = Session.getDefaultInstance props, null
Store store = session.getStore provider
Folder inbox = null
String content
try
{
store.connect host, username, password
// Open the folder
inbox = store.getFolder 'INBOX'
if (!inbox) {
println 'No INBOX'
System.exit 1
}
inbox.open(Folder.READ_ONLY)
Message[] messages = inbox.getMessages()
content = messages[0].getContent()
//Do some parsing of the content here, to find your token.
//Place the result in content
}
finally
{
inbox.close false
store.close()
}
return content; //return the parsed token

WCF WebApi, what is the correct way to handle IsThisTaken query?

I am in the process of writing a WCF webapi application and have a need to check whether an email address is taken or not. This needs to be a query the client-side code can do before attempting a PUT.
So, what I'm trying to do is use HEAD in conjunction with HTTP status codes. I am a little unsure how to go about doing that as it's a simple yes/no response which is required. So, I've used HttpResponseExceptions to return the relevant status code.
[WebInvoke(Method = "HEAD", UriTemplate = "{email}")]
[RequireAuthorisation]
public void IsEmailAddressTaken(string email)
{
if (!Regex.IsMatch(email, Regexes.EmailPattern))
{
throw new RestValidationFailureException("email", "invalid email address");
}
if (_repository.IsEmailAddressTaken(email))
{
throw new HttpResponseException(HttpStatusCode.OK);
}
throw new HttpResponseException(HttpStatusCode.NoContent);
}
This just doesn't "smell" right to me.
am I going about doing this kind of yes/no operation the right way?
My suggestion is to return a HttpResponseMessage instead of throwing exceptions.
Is your RestValidationFailureException being handled anywhere? If not, it will result in a 500 status code, which does not seem adequate.
I think it would be ok to just return OK for "exists" and 404 for "does not exist"