Server working

This commit is contained in:
Chris Proctor
2024-05-19 19:26:23 -04:00
parent b5950eeb28
commit 780c1e581a
7 changed files with 361 additions and 19 deletions

View File

@@ -7,7 +7,7 @@ from banjo.models import (
class User(Model):
name = StringField(unique=True)
public_key = StringField(unique=True)
public_key = StringField()
def to_dict(self):
return {
@@ -20,3 +20,10 @@ class Message(Model):
recipient = ForeignKey(User, related_name="messages_received")
ciphertext = StringField()
read = BooleanField()
def to_dict(self):
return {
'sender': self.sender.name,
'recipient': self.recipient.name,
'ciphertext': self.ciphertext,
}

View File

@@ -2,7 +2,10 @@ 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
from cryptography.exceptions import InvalidSignature
import sys
sys.path.insert(0, "..")
from encryption import PrivateKey, PublicKey
@route_post("users/new", args={'name': str, 'public_key': str})
def create_user(params):
@@ -27,14 +30,14 @@ def get_user(params):
def get_messages(params):
"Return all the messages for a user"
try:
user = User.objects.get(name=params['name'])
recipient = 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)
messages = Message.objects.filter(recipient=recipient)
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})
'time_sent': str, 'time_sent_signature': str})
def send_message(params):
"""Securely sends an encrypted message from `sender` to `recipient`
Sender and recipient should be recognized usernames.
@@ -44,18 +47,28 @@ def send_message(params):
"""
try:
sender = User.objects.get(name=params['sender'])
recipient = User.objects.get(name=['recipient'])
recipient = User.objects.get(name=params['recipient'])
except User.DoesNotExist:
raise NotFound(f"There is no user named {params['name']}")
raise NotFound(f"User not found.")
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:
now = datetime.utcnow()
if (now - time_sent).seconds > 10:
raise NotAllowed(f"The message is too old. Time sent must be within ten seconds")
if not
sender_public_key = PublicKey.load(sender.public_key)
try:
sender_public_key.verify_signature(params['time_sent'], params['time_sent_signature'])
except InvalidSignature:
raise NotAllowed("Invalid signature.")
message = Message(
sender=sender,
recipient=recipient,
ciphertext=params['ciphertext'],
)
message.save()
return message.to_dict()