Merge branch 'main' into alexa-auth-frontend

This commit is contained in:
afazio1
2024-03-27 16:15:16 -04:00
20 changed files with 539 additions and 0 deletions

0
backend/api/__init__.py Normal file
View File

5
backend/api/admin.py Normal file
View File

@@ -0,0 +1,5 @@
from django.contrib import admin
from api.models import PeerUser
# Register your models here.
admin.site.register(PeerUser)

6
backend/api/apps.py Normal file
View File

@@ -0,0 +1,6 @@
from django.apps import AppConfig
class ApiConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "api"

View File

@@ -0,0 +1,133 @@
# Generated by Django 4.2.11 on 2024-03-25 17:37
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
("auth", "0012_alter_user_first_name_max_length"),
]
operations = [
migrations.CreateModel(
name="PeerUser",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("password", models.CharField(max_length=128, verbose_name="password")),
(
"last_login",
models.DateTimeField(
blank=True, null=True, verbose_name="last login"
),
),
(
"is_superuser",
models.BooleanField(
default=False,
help_text="Designates that this user has all permissions without explicitly assigning them.",
verbose_name="superuser status",
),
),
(
"username",
models.CharField(
error_messages={
"unique": "A user with that username already exists."
},
help_text="Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.",
max_length=150,
unique=True,
validators=[
django.contrib.auth.validators.UnicodeUsernameValidator()
],
verbose_name="username",
),
),
(
"first_name",
models.CharField(
blank=True, max_length=150, verbose_name="first name"
),
),
(
"last_name",
models.CharField(
blank=True, max_length=150, verbose_name="last name"
),
),
(
"email",
models.EmailField(
blank=True, max_length=254, verbose_name="email address"
),
),
(
"is_staff",
models.BooleanField(
default=False,
help_text="Designates whether the user can log into this admin site.",
verbose_name="staff status",
),
),
(
"is_active",
models.BooleanField(
default=True,
help_text="Designates whether this user should be treated as active. Unselect this instead of deleting accounts.",
verbose_name="active",
),
),
(
"date_joined",
models.DateTimeField(
default=django.utils.timezone.now, verbose_name="date joined"
),
),
("ip_address", models.GenericIPAddressField(blank=True, null=True)),
(
"groups",
models.ManyToManyField(
blank=True,
help_text="The groups this user belongs to. A user will get all permissions granted to each of their groups.",
related_name="user_set",
related_query_name="user",
to="auth.group",
verbose_name="groups",
),
),
(
"user_permissions",
models.ManyToManyField(
blank=True,
help_text="Specific permissions for this user.",
related_name="user_set",
related_query_name="user",
to="auth.permission",
verbose_name="user permissions",
),
),
],
options={
"verbose_name": "user",
"verbose_name_plural": "users",
"abstract": False,
},
managers=[
("objects", django.contrib.auth.models.UserManager()),
],
),
]

View File

7
backend/api/models.py Normal file
View File

@@ -0,0 +1,7 @@
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.db import models
class PeerUser(AbstractUser):
ip_address = models.GenericIPAddressField(blank=True, null=True)

View File

@@ -0,0 +1,13 @@
from rest_framework import serializers
from .models import PeerUser
class LoginSerializer(serializers.Serializer):
username = serializers.CharField()
password = serializers.CharField()
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = PeerUser
fields = ["id", "username", "email", "ip_address"]

3
backend/api/tests.py Normal file
View File

@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

24
backend/api/urls.py Normal file
View File

@@ -0,0 +1,24 @@
"""
URL configuration for peer_notes project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.urls import path
from api.user_login import LoginView, SignupView
urlpatterns = [
path("api/login/", LoginView.as_view(), name="login"),
path("api/signup/", SignupView.as_view(), name="signup"),
]

61
backend/api/user_login.py Normal file
View File

@@ -0,0 +1,61 @@
from api.serializers import LoginSerializer, UserSerializer
from django.contrib.auth import authenticate, get_user_model
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from rest_framework.views import APIView
def get_client_ip(request):
x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
if x_forwarded_for:
ip = x_forwarded_for.split(",")[0]
else:
ip = request.META.get("REMOTE_ADDR")
return ip
class LoginView(APIView):
def post(self, request):
serializer = LoginSerializer(data=request.data)
if serializer.is_valid():
username = serializer.validated_data["username"]
password = serializer.validated_data["password"]
user = authenticate(username=username, password=password)
if user:
token, _ = Token.objects.get_or_create(user=user)
return Response({"token": token.key})
else:
return Response(
{"error": "Invalid credentials"},
status=status.HTTP_401_UNAUTHORIZED,
)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class SignupView(APIView):
def post(self, request):
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
print(serializer.validated_data)
username = serializer.validated_data["username"]
email = serializer.validated_data["email"]
password = request.data["password"]
ip_address = get_client_ip(request)
print(email, username, password)
if get_user_model().objects.filter(username=username).exists():
return Response(
{"error": "Username already exists"},
status=status.HTTP_400_BAD_REQUEST,
)
user = get_user_model().objects.create_user(
username=username, email=email, password=password, ip_address=ip_address
)
return Response(
{"message": "User created successfully"}, status=status.HTTP_201_CREATED
)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

6
backend/api/views.py Normal file
View File

@@ -0,0 +1,6 @@
from rest_framework.views import APIView
from rest_framework.response import Response
from api.serializers import LoginSerializer
from django.contrib.auth import authenticate
from rest_framework.authtoken.models import Token
from rest_framework import status

22
backend/manage.py Executable file
View File

@@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "peer_notes.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == "__main__":
main()

View File

View File

@@ -0,0 +1,16 @@
"""
ASGI config for peer_notes project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "peer_notes.settings")
application = get_asgi_application()

View File

@@ -0,0 +1,136 @@
"""
Django settings for peer_notes project.
Generated by 'django-admin startproject' using Django 4.2.11.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-rh0s*u8&#4$uugtt10cxbifjriaz%@&p1w!)c2=y^undd2*nx5"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"rest_framework",
"api.apps.ApiConfig",
"rest_framework.authtoken",
"corsheaders",
]
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": [
"rest_framework.authentication.TokenAuthentication",
],
}
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"corsheaders.middleware.CorsMiddleware",
]
ROOT_URLCONF = "peer_notes.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
WSGI_APPLICATION = "peer_notes.wsgi.application"
# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}
# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/
STATIC_URL = "static/"
# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
AUTH_USER_MODEL = "api.PeerUser"
CORS_ALLOW_ALL_ORIGINS = True

View File

@@ -0,0 +1,24 @@
"""
URL configuration for peer_notes project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("api.urls")),
]

View File

View File

@@ -0,0 +1,16 @@
"""
WSGI config for peer_notes project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "peer_notes.settings")
application = get_wsgi_application()

21
backend/requirements.txt Normal file
View File

@@ -0,0 +1,21 @@
asgiref==3.8.1
black==24.2.0
blinker==1.7.0
click==8.1.7
Django==4.2.11
django-cors-headers==4.3.1
djangorestframework==3.15.1
Flask==3.0.2
importlib-metadata==7.0.1
itsdangerous==2.1.2
Jinja2==3.1.3
MarkupSafe==2.1.5
mypy-extensions==1.0.0
packaging==23.2
pathspec==0.12.1
platformdirs==4.2.0
sqlparse==0.4.4
tomli==2.0.1
typing_extensions==4.10.0
Werkzeug==3.0.1
zipp==3.17.0

46
backend/server.py Normal file
View File

@@ -0,0 +1,46 @@
from flask import Flask, request
import signal
app = Flask(__name__)
file_index = {}
def shutdown_server(signal, frame):
print("Shutting down server...")
# Close the Flask app context
ctx = app.app_context()
ctx.push()
# Shutdown the Flask server
app.shutdown()
ctx.pop()
# Register the signal handler for SIGINT (keyboard interrupt)
signal.signal(signal.SIGINT, shutdown_server)
@app.route("/register", methods=["POST"])
def register_node():
data = request.json
node_ip = data["ip"]
files = data["files"]
for file in files:
if file not in file_index:
file_index[file] = []
file_index[file].append(node_ip)
print(file_index)
return "Node registered successfully", 200
@app.route("/query", methods=["GET"])
def query_file():
file_name = request.args.get("file")
print("Requested File Name: ", file_name)
if file_name in file_index:
return {"nodes": file_index[file_name]}, 200
else:
return "File not found", 404
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000)