63 lines
2.2 KiB
Python
63 lines
2.2 KiB
Python
from banjo.urls import route_get, route_post
|
|
from app.models import User, Message
|
|
from banjo.http import NotFound, NotAllowed
|
|
from datetime import datetime
|
|
import rsa
|
|
|
|
@route_post("users/new", args={'name': str, 'public_key': str})
|
|
def create_user(params):
|
|
"Creates a new user"
|
|
try:
|
|
new_user = User.from_dict(params)
|
|
new_user.save()
|
|
return new_user.to_dict()
|
|
except:
|
|
raise NotAllowed("Username and public key must be unique.")
|
|
|
|
@route_get("users", args={'name': str})
|
|
def get_user(params):
|
|
"Get a user's public key"
|
|
try:
|
|
user = User.objects.get(name=params['name'])
|
|
return user.to_dict()
|
|
except User.DoesNotExist:
|
|
raise NotFound(f"There is no user named {params['name']}")
|
|
|
|
@route_get("messages", args={'name': str})
|
|
def get_messages(params):
|
|
"Return all the messages for a user"
|
|
try:
|
|
user = User.objects.get(name=params['name'])
|
|
except User.DoesNotExist:
|
|
raise NotFound(f"There is no user named {params['name']}")
|
|
messages = Message.objects.filter(user=user)
|
|
return {'messages': [m.to_dict() for m in messages]}
|
|
|
|
@route_get("messages/send", args={'sender': str, 'recipient': str, 'ciphertext': str,
|
|
'time_sent': str, 'auth': str})
|
|
def send_message(params):
|
|
"""Securely sends an encrypted message from `sender` to `recipient`
|
|
Sender and recipient should be recognized usernames.
|
|
Time sent should be the time the message was sent in isoformat.
|
|
Auth should be the time sent, encrypted with the sender's private key.
|
|
The ciphertext should be encrypted with the recipient's public key.
|
|
"""
|
|
try:
|
|
sender = User.objects.get(name=params['sender'])
|
|
recipient = User.objects.get(name=['recipient'])
|
|
except User.DoesNotExist:
|
|
raise NotFound(f"There is no user named {params['name']}")
|
|
try:
|
|
time_sent = datetime.fromisoformat(params['time_sent'])
|
|
except ValueError:
|
|
raise NotAllowed(f"Time sent ({params['time_sent']}) must be in isoformat")
|
|
if (datetime.now() - time_sent).seconds > 10:
|
|
raise NotAllowed(f"The message is too old. Time sent must be within ten seconds")
|
|
if not
|
|
|
|
|
|
|
|
|
|
|
|
|