It looks like MQTTClient can be used to publish messages. That’d need some thought in any app that needed some sort of validation of messages (an online game, for example), to keep someone from tinkering with the client code to send valid but illegal messages. Maybe some sort of signing of messages sent by the server. That’d be app specific, of course.
I guess that brings up the question about why the sample app uses the server to send messages, rather than using MQTTClient’s publish method instead?
Very valid points. I had considered that too but decided that since I was going to share this I wanted to try and include everything. However, in my use cases, I plan to use the MQTT publish only on the server-side.
To increase security this is what I am planning to try:
Server has something new it want’s the client to know about. and it saves a token and name of the callable server function in a warehouse table.
Server function searches warehouse table to validate it is authorized to perform the work.
@anvil.server.callable
def my_server_func(token):
token_row = None
user = anvil.users.get_user()
if user != None:
user_id = user.get("user_id")
if user_id:
# to make this faster I'd likely put just the user id in a simple object as opposed to linking the row
token_row = app_tables.mqtt_tokens.get(token=token, used_by=q.none_of(["user_id"]))
if token_row != None:
# code to do work
Function logs user ID or some other identifiable variable in the token row of warehouse table to prevent the malicious calling of that token
I know this is a bit more traffic but it’s better than using a background task and constantly polling the server.
Concerning your question about not using the client to publish instead of the server. This is really twofold. One, I wanted to demonstrate how to use the MQTTServer class. Two, I personally intend to try and use the MQTT as little as possible as it becomes another service that needs to be paid for when used at scale. So the lower traffic on it and with Anvil, the lower the financial obligation.
Of course, I am open to any ideas anyone might have to improve this process!
Thank you for the great contribution! I am trying to implement this method currently and found a library we have access to if you are on the personal plan and above:
right, I guess I meant there is a paho-mqtt python library that is apart of anvil’s list of packages and the link above is a document on how to use that library that might have some extra functionality you want.