How to validate data input via channels? is_number does not work

I want to be sure to receive only integers via a channel. is_number does not work (always false).
From the docs I understand that input that comes via channels is of type “term” - what is that?

How can I be sure to only get integers before putting that data into e.g. a map and trying to do some math with it?

Thank you for your attention!

The type term does mean, that there can be anything. In fact, it is a synonym to the type any.

And how to check what you get, does depend on your client as well. So to actually give you an answer we need to see some code.

Until then I’d try to check for integers, then for a parsable string and then fail.

Ah, thank you very much about the term enlightment - I found something about erlang terms, but “anything” is a much simpler explanation. But what does this mean for the channel input - of what actual datatype is the payload that comes in from channels? Is there some conversion taking place behind the scenes?

I am just working with the default phoenix example, added some JavaScript that sends me some values (int), and the phoenix site just broadcasts what comes in. Of course I would like to do some more with the data that comes in, like e.g. put in a map and do some simple calculations (sum). Ecto not needed right now.

I do want to have this checks server-site, of course, to be sure that I do not broadcast anything back to connected clients.

So in the channels handle_in I would like to make sure that only integers are accepted.

Baiscally it is just the second thought you get after playing with the official channels guide - how to secure that kind of data? How to prevent flooding (different thread here)? Is there a max_upload_size? Etc. I can not find answers to these important questions in the docs, unfortunately.

It would be great to improve the docs with answering these important security related things!

Thank you very much for attention!

Phoenix channels by default use Poison to convert JSON into erlang terms. Thus what you get depends on what the client sends via JSON. If you are unsure what you are getting then (for now) add a catch-all cases that just 'inspect’s it to your log to see how it actually looks. :slight_smile:


Thank you very much for this important peace of informaton! Should be written in the channel guide!

1 Like

You should submit a PR to do that! :smiley:

While we aren’t quite there yet, stay tuned for what GraphQL via can offer for your channels. Strongly typed inputs make a lot of this stuff much easier.

1 Like