From b3b24b34c0e56d99331c55b075c10736e4050288 Mon Sep 17 00:00:00 2001 From: snehas-05 Date: Mon, 14 Oct 2024 17:19:49 +0000 Subject: [PATCH 1/5] commit changes --- .../FaceRecoginitionProject/__init__.py | 0 .../FaceRecoginitionProject/asgi.py | 16 +++ .../FaceRecoginitionProject/settings.py | 131 ++++++++++++++++++ .../FaceRecoginitionProject/urls.py | 31 +++++ .../FaceRecoginitionProject/wsgi.py | 16 +++ FaceRecoginitionProject/manage.py | 22 +++ user_authentication/forms.py | 9 ++ user_authentication/models.py | 15 ++ .../templates/admin_dashboard.html | 10 ++ user_authentication/templates/login.html | 17 +++ user_authentication/templates/profile.html | 10 ++ user_authentication/templates/register.html | 14 ++ user_authentication/urls.py | 8 ++ user_authentication/views.py | 45 ++++++ 14 files changed, 344 insertions(+) create mode 100644 FaceRecoginitionProject/FaceRecoginitionProject/__init__.py create mode 100644 FaceRecoginitionProject/FaceRecoginitionProject/asgi.py create mode 100644 FaceRecoginitionProject/FaceRecoginitionProject/settings.py create mode 100644 FaceRecoginitionProject/FaceRecoginitionProject/urls.py create mode 100644 FaceRecoginitionProject/FaceRecoginitionProject/wsgi.py create mode 100755 FaceRecoginitionProject/manage.py create mode 100644 user_authentication/forms.py create mode 100644 user_authentication/models.py create mode 100644 user_authentication/templates/admin_dashboard.html create mode 100644 user_authentication/templates/login.html create mode 100644 user_authentication/templates/profile.html create mode 100644 user_authentication/templates/register.html create mode 100644 user_authentication/urls.py create mode 100644 user_authentication/views.py diff --git a/FaceRecoginitionProject/FaceRecoginitionProject/__init__.py b/FaceRecoginitionProject/FaceRecoginitionProject/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/FaceRecoginitionProject/FaceRecoginitionProject/asgi.py b/FaceRecoginitionProject/FaceRecoginitionProject/asgi.py new file mode 100644 index 00000000..080aaf1e --- /dev/null +++ b/FaceRecoginitionProject/FaceRecoginitionProject/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for FaceRecoginitionProject 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/5.1/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "FaceRecoginitionProject.settings") + +application = get_asgi_application() diff --git a/FaceRecoginitionProject/FaceRecoginitionProject/settings.py b/FaceRecoginitionProject/FaceRecoginitionProject/settings.py new file mode 100644 index 00000000..b5f1c6b8 --- /dev/null +++ b/FaceRecoginitionProject/FaceRecoginitionProject/settings.py @@ -0,0 +1,131 @@ +""" +Django settings for FaceRecoginitionProject project. + +Generated by 'django-admin startproject' using Django 5.1.2. + +For more information on this file, see +https://docs.djangoproject.com/en/5.1/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/5.1/ref/settings/ +""" + +INSTALLED_APPS = [ + # other apps + 'authentication', +] + +AUTH_USER_MODEL = 'authentication.CustomUser' + + +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/5.1/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = "django-insecure-@=^f_qw1lz6wnv14xvzr%v_nvr7=7(gi5bsa)_t6s(()=p76#l" + +# 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", +] + +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", +] + +ROOT_URLCONF = "FaceRecoginitionProject.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 = "FaceRecoginitionProject.wsgi.application" + + +# Database +# https://docs.djangoproject.com/en/5.1/ref/settings/#databases + +DATABASES = { + "default": { + "ENGINE": "django.db.backends.sqlite3", + "NAME": BASE_DIR / "db.sqlite3", + } +} + + +# Password validation +# https://docs.djangoproject.com/en/5.1/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/5.1/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/5.1/howto/static-files/ + +STATIC_URL = "static/" + +# Default primary key field type +# https://docs.djangoproject.com/en/5.1/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" diff --git a/FaceRecoginitionProject/FaceRecoginitionProject/urls.py b/FaceRecoginitionProject/FaceRecoginitionProject/urls.py new file mode 100644 index 00000000..961df3aa --- /dev/null +++ b/FaceRecoginitionProject/FaceRecoginitionProject/urls.py @@ -0,0 +1,31 @@ +""" +URL configuration for FaceRecoginitionProject project. + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/5.1/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 + +urlpatterns = [ + path("admin/", admin.site.urls), +] + +from django.urls import path, include + +urlpatterns = [ + path('authentication/', include('authentication.urls')), + path('', home_view, name='home'), +] + diff --git a/FaceRecoginitionProject/FaceRecoginitionProject/wsgi.py b/FaceRecoginitionProject/FaceRecoginitionProject/wsgi.py new file mode 100644 index 00000000..5a6ac889 --- /dev/null +++ b/FaceRecoginitionProject/FaceRecoginitionProject/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for FaceRecoginitionProject 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/5.1/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "FaceRecoginitionProject.settings") + +application = get_wsgi_application() diff --git a/FaceRecoginitionProject/manage.py b/FaceRecoginitionProject/manage.py new file mode 100755 index 00000000..7436055f --- /dev/null +++ b/FaceRecoginitionProject/manage.py @@ -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", "FaceRecoginitionProject.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() diff --git a/user_authentication/forms.py b/user_authentication/forms.py new file mode 100644 index 00000000..44c3c13a --- /dev/null +++ b/user_authentication/forms.py @@ -0,0 +1,9 @@ +from django import forms +from django.contrib.auth.forms import UserCreationForm +from .models import CustomUser + +# Form for user registration +class CustomUserCreationForm(UserCreationForm): + class Meta(UserCreationForm.Meta): + model = CustomUser + fields = UserCreationForm.Meta.fields + ('role',) # Add role field diff --git a/user_authentication/models.py b/user_authentication/models.py new file mode 100644 index 00000000..13a5076f --- /dev/null +++ b/user_authentication/models.py @@ -0,0 +1,15 @@ +from django.contrib.auth.models import AbstractUser +from django.db import models + +# Choices for roles +ROLE_CHOICES = ( + ('admin', 'Admin'), + ('user', 'User'), +) + +# Custom user model with roles +class CustomUser(AbstractUser): + role = models.CharField(max_length=10, choices=ROLE_CHOICES, default='user') + + def __str__(self): + return self.username diff --git a/user_authentication/templates/admin_dashboard.html b/user_authentication/templates/admin_dashboard.html new file mode 100644 index 00000000..e2c9ae80 --- /dev/null +++ b/user_authentication/templates/admin_dashboard.html @@ -0,0 +1,10 @@ + + + + Admin Dashboard + + +

Admin Dashboard

+

Manage users and system settings.

+ + diff --git a/user_authentication/templates/login.html b/user_authentication/templates/login.html new file mode 100644 index 00000000..8c16d565 --- /dev/null +++ b/user_authentication/templates/login.html @@ -0,0 +1,17 @@ + + + + Login + + +

Login

+ {% if error %} +

{{ error }}

+ {% endif %} +
+ {% csrf_token %} + {{ form.as_p }} + +
+ + diff --git a/user_authentication/templates/profile.html b/user_authentication/templates/profile.html new file mode 100644 index 00000000..25a0cb30 --- /dev/null +++ b/user_authentication/templates/profile.html @@ -0,0 +1,10 @@ + + + + Profile + + +

Welcome {{ user.username }}

+

Your role: {{ user.role }}

+ + diff --git a/user_authentication/templates/register.html b/user_authentication/templates/register.html new file mode 100644 index 00000000..66b4c517 --- /dev/null +++ b/user_authentication/templates/register.html @@ -0,0 +1,14 @@ + + + + Register + + +

Register

+
+ {% csrf_token %} + {{ form.as_p }} + +
+ + diff --git a/user_authentication/urls.py b/user_authentication/urls.py new file mode 100644 index 00000000..074933cd --- /dev/null +++ b/user_authentication/urls.py @@ -0,0 +1,8 @@ +from django.urls import path +from .views import register, user_login, profile + +urlpatterns = [ + path('register/', register, name='register'), + path('login/', user_login, name='login'), + path('profile/', profile, name='profile'), +] diff --git a/user_authentication/views.py b/user_authentication/views.py new file mode 100644 index 00000000..3b2968a5 --- /dev/null +++ b/user_authentication/views.py @@ -0,0 +1,45 @@ +from django.contrib.auth.decorators import user_passes_test +def is_admin(user): + return user.role == 'admin' +@user_passes_test(is_admin) +def admin_dashboard(request): + return render(request, 'authentication/admin_dashboard.html') + + + + +from django.shortcuts import render, redirect +from django.contrib.auth import login, authenticate, logout +from django.contrib.auth.decorators import login_required +from .forms import CustomUserCreationForm, LoginForm + +def register(request): + if request.method == 'POST': + form = CustomUserCreationForm(request.POST) + if form.is_valid(): + user = form.save() + login(request, user) + return redirect('home') + else: + form = CustomUserCreationForm() + return render(request, 'authentication/register.html', {'form': form}) + +def user_login(request): + if request.method == 'POST': + form = LoginForm(request.POST) + if form.is_valid(): + username = form.cleaned_data.get('username') + password = form.cleaned_data.get('password') + user = authenticate(request, username=username, password=password) + if user is not None: + login(request, user) + return redirect('home') + else: + return render(request, 'authentication/login.html', {'error': 'Invalid credentials'}) + else: + form = LoginForm() + return render(request, 'authentication/login.html', {'form': form}) + +@login_required +def profile(request): + return render(request, 'authentication/profile.html', {'user': request.user}) From 7d57c90342728600bae451b3f053222bf30cad0d Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 14 Oct 2024 17:28:50 +0000 Subject: [PATCH 2/5] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- .../FaceRecoginitionProject/asgi.py | 3 +- .../FaceRecoginitionProject/settings.py | 7 ++- .../FaceRecoginitionProject/urls.py | 7 ++- .../FaceRecoginitionProject/wsgi.py | 3 +- FaceRecoginitionProject/manage.py | 3 +- user_authentication/forms.py | 4 +- user_authentication/models.py | 8 ++-- user_authentication/urls.py | 9 ++-- user_authentication/views.py | 45 +++++++++++-------- 9 files changed, 51 insertions(+), 38 deletions(-) diff --git a/FaceRecoginitionProject/FaceRecoginitionProject/asgi.py b/FaceRecoginitionProject/FaceRecoginitionProject/asgi.py index 080aaf1e..083e633e 100644 --- a/FaceRecoginitionProject/FaceRecoginitionProject/asgi.py +++ b/FaceRecoginitionProject/FaceRecoginitionProject/asgi.py @@ -11,6 +11,7 @@ from django.core.asgi import get_asgi_application -os.environ.setdefault("DJANGO_SETTINGS_MODULE", "FaceRecoginitionProject.settings") +os.environ.setdefault("DJANGO_SETTINGS_MODULE", + "FaceRecoginitionProject.settings") application = get_asgi_application() diff --git a/FaceRecoginitionProject/FaceRecoginitionProject/settings.py b/FaceRecoginitionProject/FaceRecoginitionProject/settings.py index b5f1c6b8..e0de0de8 100644 --- a/FaceRecoginitionProject/FaceRecoginitionProject/settings.py +++ b/FaceRecoginitionProject/FaceRecoginitionProject/settings.py @@ -10,15 +10,14 @@ https://docs.djangoproject.com/en/5.1/ref/settings/ """ +from pathlib import Path INSTALLED_APPS = [ # other apps - 'authentication', + "authentication", ] -AUTH_USER_MODEL = 'authentication.CustomUser' - +AUTH_USER_MODEL = "authentication.CustomUser" -from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent diff --git a/FaceRecoginitionProject/FaceRecoginitionProject/urls.py b/FaceRecoginitionProject/FaceRecoginitionProject/urls.py index 961df3aa..83f9b7be 100644 --- a/FaceRecoginitionProject/FaceRecoginitionProject/urls.py +++ b/FaceRecoginitionProject/FaceRecoginitionProject/urls.py @@ -15,6 +15,7 @@ 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ +from django.urls import include, path from django.contrib import admin from django.urls import path @@ -22,10 +23,8 @@ path("admin/", admin.site.urls), ] -from django.urls import path, include urlpatterns = [ - path('authentication/', include('authentication.urls')), - path('', home_view, name='home'), + path("authentication/", include("authentication.urls")), + path("", home_view, name="home"), ] - diff --git a/FaceRecoginitionProject/FaceRecoginitionProject/wsgi.py b/FaceRecoginitionProject/FaceRecoginitionProject/wsgi.py index 5a6ac889..11cbf0c7 100644 --- a/FaceRecoginitionProject/FaceRecoginitionProject/wsgi.py +++ b/FaceRecoginitionProject/FaceRecoginitionProject/wsgi.py @@ -11,6 +11,7 @@ from django.core.wsgi import get_wsgi_application -os.environ.setdefault("DJANGO_SETTINGS_MODULE", "FaceRecoginitionProject.settings") +os.environ.setdefault("DJANGO_SETTINGS_MODULE", + "FaceRecoginitionProject.settings") application = get_wsgi_application() diff --git a/FaceRecoginitionProject/manage.py b/FaceRecoginitionProject/manage.py index 7436055f..a02a0a0b 100755 --- a/FaceRecoginitionProject/manage.py +++ b/FaceRecoginitionProject/manage.py @@ -6,7 +6,8 @@ def main(): """Run administrative tasks.""" - os.environ.setdefault("DJANGO_SETTINGS_MODULE", "FaceRecoginitionProject.settings") + os.environ.setdefault("DJANGO_SETTINGS_MODULE", + "FaceRecoginitionProject.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: diff --git a/user_authentication/forms.py b/user_authentication/forms.py index 44c3c13a..3e94218f 100644 --- a/user_authentication/forms.py +++ b/user_authentication/forms.py @@ -1,9 +1,11 @@ from django import forms from django.contrib.auth.forms import UserCreationForm + from .models import CustomUser + # Form for user registration class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = CustomUser - fields = UserCreationForm.Meta.fields + ('role',) # Add role field + fields = UserCreationForm.Meta.fields + ("role",) # Add role field diff --git a/user_authentication/models.py b/user_authentication/models.py index 13a5076f..a615845b 100644 --- a/user_authentication/models.py +++ b/user_authentication/models.py @@ -3,13 +3,15 @@ # Choices for roles ROLE_CHOICES = ( - ('admin', 'Admin'), - ('user', 'User'), + ("admin", "Admin"), + ("user", "User"), ) + # Custom user model with roles class CustomUser(AbstractUser): - role = models.CharField(max_length=10, choices=ROLE_CHOICES, default='user') + role = models.CharField( + max_length=10, choices=ROLE_CHOICES, default="user") def __str__(self): return self.username diff --git a/user_authentication/urls.py b/user_authentication/urls.py index 074933cd..a0435ef1 100644 --- a/user_authentication/urls.py +++ b/user_authentication/urls.py @@ -1,8 +1,9 @@ from django.urls import path -from .views import register, user_login, profile + +from .views import profile, register, user_login urlpatterns = [ - path('register/', register, name='register'), - path('login/', user_login, name='login'), - path('profile/', profile, name='profile'), + path("register/", register, name="register"), + path("login/", user_login, name="login"), + path("profile/", profile, name="profile"), ] diff --git a/user_authentication/views.py b/user_authentication/views.py index 3b2968a5..85836f2f 100644 --- a/user_authentication/views.py +++ b/user_authentication/views.py @@ -1,45 +1,52 @@ +from .forms import CustomUserCreationForm, LoginForm +from django.shortcuts import redirect, render +from django.contrib.auth.decorators import login_required +from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import user_passes_test -def is_admin(user): - return user.role == 'admin' -@user_passes_test(is_admin) -def admin_dashboard(request): - return render(request, 'authentication/admin_dashboard.html') +def is_admin(user): + return user.role == "admin" -from django.shortcuts import render, redirect -from django.contrib.auth import login, authenticate, logout -from django.contrib.auth.decorators import login_required -from .forms import CustomUserCreationForm, LoginForm +@user_passes_test(is_admin) +def admin_dashboard(request): + return render(request, "authentication/admin_dashboard.html") + def register(request): - if request.method == 'POST': + if request.method == "POST": form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save() login(request, user) - return redirect('home') + return redirect("home") else: form = CustomUserCreationForm() - return render(request, 'authentication/register.html', {'form': form}) + return render(request, "authentication/register.html", {"form": form}) + def user_login(request): - if request.method == 'POST': + if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): - username = form.cleaned_data.get('username') - password = form.cleaned_data.get('password') + username = form.cleaned_data.get("username") + password = form.cleaned_data.get("password") user = authenticate(request, username=username, password=password) if user is not None: login(request, user) - return redirect('home') + return redirect("home") else: - return render(request, 'authentication/login.html', {'error': 'Invalid credentials'}) + return render( + request, + "authentication/login.html", + {"error": "Invalid credentials"}, + ) else: form = LoginForm() - return render(request, 'authentication/login.html', {'form': form}) + return render(request, "authentication/login.html", {"form": form}) + @login_required def profile(request): - return render(request, 'authentication/profile.html', {'user': request.user}) + return render(request, "authentication/profile.html", {"user": request.user}) From 02353b0da809a8d2f3f47d3dbb7d4199b68a643e Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 15 Oct 2024 18:27:42 +0000 Subject: [PATCH 3/5] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- .../FaceRecoginitionProject/settings.py | 1 + FaceRecoginitionProject/FaceRecoginitionProject/urls.py | 3 +-- user_authentication/views.py | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/FaceRecoginitionProject/FaceRecoginitionProject/settings.py b/FaceRecoginitionProject/FaceRecoginitionProject/settings.py index e0de0de8..87c44ffd 100644 --- a/FaceRecoginitionProject/FaceRecoginitionProject/settings.py +++ b/FaceRecoginitionProject/FaceRecoginitionProject/settings.py @@ -11,6 +11,7 @@ """ from pathlib import Path + INSTALLED_APPS = [ # other apps "authentication", diff --git a/FaceRecoginitionProject/FaceRecoginitionProject/urls.py b/FaceRecoginitionProject/FaceRecoginitionProject/urls.py index 83f9b7be..2521ca42 100644 --- a/FaceRecoginitionProject/FaceRecoginitionProject/urls.py +++ b/FaceRecoginitionProject/FaceRecoginitionProject/urls.py @@ -15,9 +15,8 @@ 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ -from django.urls import include, path from django.contrib import admin -from django.urls import path +from django.urls import include, path urlpatterns = [ path("admin/", admin.site.urls), diff --git a/user_authentication/views.py b/user_authentication/views.py index 85836f2f..257e1fa4 100644 --- a/user_authentication/views.py +++ b/user_authentication/views.py @@ -1,8 +1,8 @@ -from .forms import CustomUserCreationForm, LoginForm -from django.shortcuts import redirect, render -from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate, login, logout -from django.contrib.auth.decorators import user_passes_test +from django.contrib.auth.decorators import login_required, user_passes_test +from django.shortcuts import redirect, render + +from .forms import CustomUserCreationForm, LoginForm def is_admin(user): From 316d23de95905a4b8ebd2dba269c5c318539e817 Mon Sep 17 00:00:00 2001 From: snehas-05 Date: Thu, 17 Oct 2024 09:53:03 +0000 Subject: [PATCH 4/5] commit changes --- .../api/__init__.py | 10 +++ authentication_and_rolemanagement/api/auth.py | 24 +++++++ authentication_and_rolemanagement/api/main.py | 5 ++ .../api/models.py | 14 ++++ .../app/__init__.py | 30 +++++++++ authentication_and_rolemanagement/app/auth.py | 66 +++++++++++++++++++ .../app/database.py | 11 ++++ .../app/models.py | 16 +++++ .../app/routes.py | 24 +++++++ .../app/security.py | 10 +++ .../requirements.txt | 10 +++ authentication_and_rolemanagement/run.py | 9 +++ user_authentication/forms.py | 11 ---- user_authentication/models.py | 17 ----- .../templates/admin_dashboard.html | 10 --- user_authentication/templates/login.html | 17 ----- user_authentication/templates/profile.html | 10 --- user_authentication/templates/register.html | 14 ---- user_authentication/urls.py | 9 --- user_authentication/views.py | 52 --------------- 20 files changed, 229 insertions(+), 140 deletions(-) create mode 100644 authentication_and_rolemanagement/api/__init__.py create mode 100644 authentication_and_rolemanagement/api/auth.py create mode 100644 authentication_and_rolemanagement/api/main.py create mode 100644 authentication_and_rolemanagement/api/models.py create mode 100644 authentication_and_rolemanagement/app/__init__.py create mode 100644 authentication_and_rolemanagement/app/auth.py create mode 100644 authentication_and_rolemanagement/app/database.py create mode 100644 authentication_and_rolemanagement/app/models.py create mode 100644 authentication_and_rolemanagement/app/routes.py create mode 100644 authentication_and_rolemanagement/app/security.py create mode 100644 authentication_and_rolemanagement/requirements.txt create mode 100644 authentication_and_rolemanagement/run.py delete mode 100644 user_authentication/forms.py delete mode 100644 user_authentication/models.py delete mode 100644 user_authentication/templates/admin_dashboard.html delete mode 100644 user_authentication/templates/login.html delete mode 100644 user_authentication/templates/profile.html delete mode 100644 user_authentication/templates/register.html delete mode 100644 user_authentication/urls.py delete mode 100644 user_authentication/views.py diff --git a/authentication_and_rolemanagement/api/__init__.py b/authentication_and_rolemanagement/api/__init__.py new file mode 100644 index 00000000..ac5a9f73 --- /dev/null +++ b/authentication_and_rolemanagement/api/__init__.py @@ -0,0 +1,10 @@ +from fastapi import FastAPI + +# Initialize FastAPI +app = FastAPI() + +# Import routes to register them +from .auth import router as auth_router + +# Include the auth router +app.include_router(auth_router, prefix="/api/auth", tags=["auth"]) diff --git a/authentication_and_rolemanagement/api/auth.py b/authentication_and_rolemanagement/api/auth.py new file mode 100644 index 00000000..97d1094d --- /dev/null +++ b/authentication_and_rolemanagement/api/auth.py @@ -0,0 +1,24 @@ +from fastapi import APIRouter, Depends, HTTPException +from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm +from sqlalchemy.orm import Session +from app.database import db +from app.models import User # Make sure you have User model defined in models.py +from app.security import verify_password, create_access_token + +router = APIRouter() +oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") + +@router.post("/token") +async def login(form_data: OAuth2PasswordRequestForm = Depends()): + user = db.session.query(User).filter(User.username == form_data.username).first() + + if not user or not verify_password(form_data.password, user.password): + raise HTTPException(status_code=400, detail="Incorrect username or password") + + access_token = create_access_token(data={"sub": user.username}) + return {"access_token": access_token, "token_type": "bearer"} + +@router.get("/users/me") +async def read_users_me(token: str = Depends(oauth2_scheme)): + user = db.session.query(User).filter(User.username == token).first() # Add logic to decode token and fetch user + return user diff --git a/authentication_and_rolemanagement/api/main.py b/authentication_and_rolemanagement/api/main.py new file mode 100644 index 00000000..5a167da7 --- /dev/null +++ b/authentication_and_rolemanagement/api/main.py @@ -0,0 +1,5 @@ +import uvicorn +from . import app + +if __name__ == "__main__": + uvicorn.run(app, host="0.0.0.0", port=8000) diff --git a/authentication_and_rolemanagement/api/models.py b/authentication_and_rolemanagement/api/models.py new file mode 100644 index 00000000..39527f1f --- /dev/null +++ b/authentication_and_rolemanagement/api/models.py @@ -0,0 +1,14 @@ +from pydantic import BaseModel + +class UserBase(BaseModel): + username: str + email: str + +class UserCreate(UserBase): + password: str + +class User(UserBase): + id: int + + class Config: + orm_mode = True diff --git a/authentication_and_rolemanagement/app/__init__.py b/authentication_and_rolemanagement/app/__init__.py new file mode 100644 index 00000000..06820db1 --- /dev/null +++ b/authentication_and_rolemanagement/app/__init__.py @@ -0,0 +1,30 @@ +from flask import Flask +from flask_sqlalchemy import SQLAlchemy +from flask_jwt_extended import JWTManager +from flask_migrate import Migrate +from flask_limiter import Limiter +from flask_limiter.util import get_remote_address +from datetime import timedelta + +# Initialize the app and config +app = Flask(__name__) +app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db' +app.config['SECRET_KEY'] = 'super-secret' +app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(minutes=30) +app.config['JWT_REFRESH_TOKEN_EXPIRES'] = timedelta(days=30) + +# Initialize database, JWT, migrations, rate limiting +db = SQLAlchemy(app) +jwt = JWTManager(app) +migrate = Migrate(app, db) +limiter = Limiter(app, key_func=get_remote_address) + +# Blacklist for revoked tokens +blacklist = set() + +@jwt.token_in_blocklist_loader +def check_if_token_is_revoked(jwt_header, jwt_payload): + return jwt_payload['jti'] in blacklist + +# Import routes +from app import routes, auth diff --git a/authentication_and_rolemanagement/app/auth.py b/authentication_and_rolemanagement/app/auth.py new file mode 100644 index 00000000..b484986d --- /dev/null +++ b/authentication_and_rolemanagement/app/auth.py @@ -0,0 +1,66 @@ +from flask import Blueprint, request, jsonify +from werkzeug.security import generate_password_hash, check_password_hash +from flask_jwt_extended import ( + create_access_token, create_refresh_token, jwt_required, + get_jwt_identity, get_jwt +) +from app.models import User, db +from app.security import generate_captcha, verify_captcha + +auth_blueprint = Blueprint('auth', __name__) + +# User registration route +@auth_blueprint.route('/register', methods=['POST']) +def register(): + data = request.json + username = data.get('username') + password = data.get('password') + captcha = data.get('captcha') + actual_captcha = data.get('actual_captcha') + + if not verify_captcha(captcha, actual_captcha): + return jsonify({"error": "Invalid CAPTCHA"}), 400 + + if User.query.filter_by(username=username).first(): + return jsonify({"error": "User already exists"}), 400 + + new_user = User(username=username) + new_user.set_password(password) + db.session.add(new_user) + db.session.commit() + + return jsonify({"message": "User registered successfully"}), 201 + +# Login route +@auth_blueprint.route('/login', methods=['POST']) +@limiter.limit("5 per minute") +def login(): + data = request.json + username = data.get('username') + password = data.get('password') + + user = User.query.filter_by(username=username).first() + + if not user or not user.check_password(password): + return jsonify({"error": "Invalid credentials"}), 401 + + access_token = create_access_token(identity={"username": user.username, "role": user.role}) + refresh_token = create_refresh_token(identity={"username": user.username, "role": user.role}) + + return jsonify(access_token=access_token, refresh_token=refresh_token), 200 + +# Logout route +@auth_blueprint.route('/logout', methods=['POST']) +@jwt_required() +def logout(): + jti = get_jwt()["jti"] + blacklist.add(jti) + return jsonify({"message": "Successfully logged out"}), 200 + +# Token refresh route +@auth_blueprint.route('/refresh', methods=['POST']) +@jwt_required(refresh=True) +def refresh_token(): + current_user = get_jwt_identity() + access_token = create_access_token(identity=current_user) + return jsonify(access_token=access_token), 200 diff --git a/authentication_and_rolemanagement/app/database.py b/authentication_and_rolemanagement/app/database.py new file mode 100644 index 00000000..00d4e304 --- /dev/null +++ b/authentication_and_rolemanagement/app/database.py @@ -0,0 +1,11 @@ +from flask_sqlalchemy import SQLAlchemy +from flask_migrate import Migrate + +# Initialize SQLAlchemy and Migrate +db = SQLAlchemy() +migrate = Migrate() + +def init_db(app): + """Initialize the database with the Flask app.""" + db.init_app(app) + migrate.init_app(app, db) diff --git a/authentication_and_rolemanagement/app/models.py b/authentication_and_rolemanagement/app/models.py new file mode 100644 index 00000000..14c26be9 --- /dev/null +++ b/authentication_and_rolemanagement/app/models.py @@ -0,0 +1,16 @@ +from flask_sqlalchemy import SQLAlchemy +from werkzeug.security import generate_password_hash, check_password_hash + +db = SQLAlchemy() + +class User(db.Model): + id = db.Column(db.Integer, primary_key=True) + username = db.Column(db.String(150), nullable=False, unique=True) + password_hash = db.Column(db.String(128), nullable=False) + role = db.Column(db.String(10), default='user') # Roles: 'admin', 'user' + + def set_password(self, password): + self.password_hash = generate_password_hash(password) + + def check_password(self, password): + return check_password_hash(self.password_hash, password) diff --git a/authentication_and_rolemanagement/app/routes.py b/authentication_and_rolemanagement/app/routes.py new file mode 100644 index 00000000..f7986eab --- /dev/null +++ b/authentication_and_rolemanagement/app/routes.py @@ -0,0 +1,24 @@ +from flask import request, jsonify +from flask_jwt_extended import jwt_required, get_jwt_identity +from app.models import User, db + +# Update user profile route +@auth_blueprint.route('/update-profile', methods=['PUT']) +@jwt_required() +def update_profile(): + current_user_data = get_jwt_identity() + data = request.json + + user = User.query.filter_by(username=current_user_data['username']).first() + + if not user: + return jsonify({"error": "User not found"}), 404 + + user.username = data.get('username', user.username) + + if data.get('password'): + user.set_password(data['password']) + + db.session.commit() + + return jsonify({"message": "Profile updated successfully"}), 200 diff --git a/authentication_and_rolemanagement/app/security.py b/authentication_and_rolemanagement/app/security.py new file mode 100644 index 00000000..9ad398c1 --- /dev/null +++ b/authentication_and_rolemanagement/app/security.py @@ -0,0 +1,10 @@ +import random +import string + +def generate_captcha(): + letters = string.ascii_letters + captcha_text = ''.join(random.choice(letters) for i in range(6)) + return captcha_text + +def verify_captcha(user_input, actual_captcha): + return user_input == actual_captcha diff --git a/authentication_and_rolemanagement/requirements.txt b/authentication_and_rolemanagement/requirements.txt new file mode 100644 index 00000000..74be940f --- /dev/null +++ b/authentication_and_rolemanagement/requirements.txt @@ -0,0 +1,10 @@ +Flask==2.0.3 +Flask-SQLAlchemy==2.5.1 +Flask-JWT-Extended==4.4.4 +Flask-Migrate==3.1.0 +Flask-Limiter==2.3.1 +FastAPI==0.65.1 +uvicorn==0.14.0 +python-dotenv==0.19.1 +Werkzeug==2.0.3 + diff --git a/authentication_and_rolemanagement/run.py b/authentication_and_rolemanagement/run.py new file mode 100644 index 00000000..45db384a --- /dev/null +++ b/authentication_and_rolemanagement/run.py @@ -0,0 +1,9 @@ +from app import create_app +from app.database import db + +app = create_app() + +if __name__ == '__main__': + with app.app_context(): + db.create_all() # Create tables + app.run(debug=True) diff --git a/user_authentication/forms.py b/user_authentication/forms.py deleted file mode 100644 index 3e94218f..00000000 --- a/user_authentication/forms.py +++ /dev/null @@ -1,11 +0,0 @@ -from django import forms -from django.contrib.auth.forms import UserCreationForm - -from .models import CustomUser - - -# Form for user registration -class CustomUserCreationForm(UserCreationForm): - class Meta(UserCreationForm.Meta): - model = CustomUser - fields = UserCreationForm.Meta.fields + ("role",) # Add role field diff --git a/user_authentication/models.py b/user_authentication/models.py deleted file mode 100644 index a615845b..00000000 --- a/user_authentication/models.py +++ /dev/null @@ -1,17 +0,0 @@ -from django.contrib.auth.models import AbstractUser -from django.db import models - -# Choices for roles -ROLE_CHOICES = ( - ("admin", "Admin"), - ("user", "User"), -) - - -# Custom user model with roles -class CustomUser(AbstractUser): - role = models.CharField( - max_length=10, choices=ROLE_CHOICES, default="user") - - def __str__(self): - return self.username diff --git a/user_authentication/templates/admin_dashboard.html b/user_authentication/templates/admin_dashboard.html deleted file mode 100644 index e2c9ae80..00000000 --- a/user_authentication/templates/admin_dashboard.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - Admin Dashboard - - -

Admin Dashboard

-

Manage users and system settings.

- - diff --git a/user_authentication/templates/login.html b/user_authentication/templates/login.html deleted file mode 100644 index 8c16d565..00000000 --- a/user_authentication/templates/login.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - Login - - -

Login

- {% if error %} -

{{ error }}

- {% endif %} -
- {% csrf_token %} - {{ form.as_p }} - -
- - diff --git a/user_authentication/templates/profile.html b/user_authentication/templates/profile.html deleted file mode 100644 index 25a0cb30..00000000 --- a/user_authentication/templates/profile.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - Profile - - -

Welcome {{ user.username }}

-

Your role: {{ user.role }}

- - diff --git a/user_authentication/templates/register.html b/user_authentication/templates/register.html deleted file mode 100644 index 66b4c517..00000000 --- a/user_authentication/templates/register.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - Register - - -

Register

-
- {% csrf_token %} - {{ form.as_p }} - -
- - diff --git a/user_authentication/urls.py b/user_authentication/urls.py deleted file mode 100644 index a0435ef1..00000000 --- a/user_authentication/urls.py +++ /dev/null @@ -1,9 +0,0 @@ -from django.urls import path - -from .views import profile, register, user_login - -urlpatterns = [ - path("register/", register, name="register"), - path("login/", user_login, name="login"), - path("profile/", profile, name="profile"), -] diff --git a/user_authentication/views.py b/user_authentication/views.py deleted file mode 100644 index 257e1fa4..00000000 --- a/user_authentication/views.py +++ /dev/null @@ -1,52 +0,0 @@ -from django.contrib.auth import authenticate, login, logout -from django.contrib.auth.decorators import login_required, user_passes_test -from django.shortcuts import redirect, render - -from .forms import CustomUserCreationForm, LoginForm - - -def is_admin(user): - return user.role == "admin" - - -@user_passes_test(is_admin) -def admin_dashboard(request): - return render(request, "authentication/admin_dashboard.html") - - -def register(request): - if request.method == "POST": - form = CustomUserCreationForm(request.POST) - if form.is_valid(): - user = form.save() - login(request, user) - return redirect("home") - else: - form = CustomUserCreationForm() - return render(request, "authentication/register.html", {"form": form}) - - -def user_login(request): - if request.method == "POST": - form = LoginForm(request.POST) - if form.is_valid(): - username = form.cleaned_data.get("username") - password = form.cleaned_data.get("password") - user = authenticate(request, username=username, password=password) - if user is not None: - login(request, user) - return redirect("home") - else: - return render( - request, - "authentication/login.html", - {"error": "Invalid credentials"}, - ) - else: - form = LoginForm() - return render(request, "authentication/login.html", {"form": form}) - - -@login_required -def profile(request): - return render(request, "authentication/profile.html", {"user": request.user}) From a3879271164e75faa37c02fc0a0d5ecefe197009 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Thu, 17 Oct 2024 09:53:50 +0000 Subject: [PATCH 5/5] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- .../api/__init__.py | 2 +- authentication_and_rolemanagement/api/auth.py | 21 ++++++--- authentication_and_rolemanagement/api/main.py | 1 + .../api/models.py | 3 ++ .../app/__init__.py | 21 +++++---- authentication_and_rolemanagement/app/auth.py | 44 +++++++++++-------- .../app/database.py | 3 +- .../app/models.py | 5 ++- .../app/routes.py | 17 +++---- .../app/security.py | 4 +- authentication_and_rolemanagement/run.py | 2 +- 11 files changed, 74 insertions(+), 49 deletions(-) diff --git a/authentication_and_rolemanagement/api/__init__.py b/authentication_and_rolemanagement/api/__init__.py index ac5a9f73..57df6df2 100644 --- a/authentication_and_rolemanagement/api/__init__.py +++ b/authentication_and_rolemanagement/api/__init__.py @@ -1,10 +1,10 @@ +from .auth import router as auth_router from fastapi import FastAPI # Initialize FastAPI app = FastAPI() # Import routes to register them -from .auth import router as auth_router # Include the auth router app.include_router(auth_router, prefix="/api/auth", tags=["auth"]) diff --git a/authentication_and_rolemanagement/api/auth.py b/authentication_and_rolemanagement/api/auth.py index 97d1094d..32a5506c 100644 --- a/authentication_and_rolemanagement/api/auth.py +++ b/authentication_and_rolemanagement/api/auth.py @@ -1,24 +1,31 @@ +from app.database import db +from app.models import \ + User # Make sure you have User model defined in models.py +from app.security import create_access_token, verify_password from fastapi import APIRouter, Depends, HTTPException from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from sqlalchemy.orm import Session -from app.database import db -from app.models import User # Make sure you have User model defined in models.py -from app.security import verify_password, create_access_token router = APIRouter() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") + @router.post("/token") async def login(form_data: OAuth2PasswordRequestForm = Depends()): - user = db.session.query(User).filter(User.username == form_data.username).first() - + user = db.session.query(User).filter( + User.username == form_data.username).first() + if not user or not verify_password(form_data.password, user.password): - raise HTTPException(status_code=400, detail="Incorrect username or password") + raise HTTPException( + status_code=400, detail="Incorrect username or password") access_token = create_access_token(data={"sub": user.username}) return {"access_token": access_token, "token_type": "bearer"} + @router.get("/users/me") async def read_users_me(token: str = Depends(oauth2_scheme)): - user = db.session.query(User).filter(User.username == token).first() # Add logic to decode token and fetch user + user = ( + db.session.query(User).filter(User.username == token).first() + ) # Add logic to decode token and fetch user return user diff --git a/authentication_and_rolemanagement/api/main.py b/authentication_and_rolemanagement/api/main.py index 5a167da7..9744c43e 100644 --- a/authentication_and_rolemanagement/api/main.py +++ b/authentication_and_rolemanagement/api/main.py @@ -1,4 +1,5 @@ import uvicorn + from . import app if __name__ == "__main__": diff --git a/authentication_and_rolemanagement/api/models.py b/authentication_and_rolemanagement/api/models.py index 39527f1f..bbd70e00 100644 --- a/authentication_and_rolemanagement/api/models.py +++ b/authentication_and_rolemanagement/api/models.py @@ -1,12 +1,15 @@ from pydantic import BaseModel + class UserBase(BaseModel): username: str email: str + class UserCreate(UserBase): password: str + class User(UserBase): id: int diff --git a/authentication_and_rolemanagement/app/__init__.py b/authentication_and_rolemanagement/app/__init__.py index 06820db1..66abe0b6 100644 --- a/authentication_and_rolemanagement/app/__init__.py +++ b/authentication_and_rolemanagement/app/__init__.py @@ -1,17 +1,19 @@ +from app import auth, routes +from datetime import timedelta + from flask import Flask -from flask_sqlalchemy import SQLAlchemy from flask_jwt_extended import JWTManager -from flask_migrate import Migrate from flask_limiter import Limiter from flask_limiter.util import get_remote_address -from datetime import timedelta +from flask_migrate import Migrate +from flask_sqlalchemy import SQLAlchemy # Initialize the app and config app = Flask(__name__) -app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db' -app.config['SECRET_KEY'] = 'super-secret' -app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(minutes=30) -app.config['JWT_REFRESH_TOKEN_EXPIRES'] = timedelta(days=30) +app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///users.db" +app.config["SECRET_KEY"] = "super-secret" +app.config["JWT_ACCESS_TOKEN_EXPIRES"] = timedelta(minutes=30) +app.config["JWT_REFRESH_TOKEN_EXPIRES"] = timedelta(days=30) # Initialize database, JWT, migrations, rate limiting db = SQLAlchemy(app) @@ -22,9 +24,10 @@ # Blacklist for revoked tokens blacklist = set() + @jwt.token_in_blocklist_loader def check_if_token_is_revoked(jwt_header, jwt_payload): - return jwt_payload['jti'] in blacklist + return jwt_payload["jti"] in blacklist + # Import routes -from app import routes, auth diff --git a/authentication_and_rolemanagement/app/auth.py b/authentication_and_rolemanagement/app/auth.py index b484986d..de362ff5 100644 --- a/authentication_and_rolemanagement/app/auth.py +++ b/authentication_and_rolemanagement/app/auth.py @@ -1,22 +1,21 @@ -from flask import Blueprint, request, jsonify -from werkzeug.security import generate_password_hash, check_password_hash -from flask_jwt_extended import ( - create_access_token, create_refresh_token, jwt_required, - get_jwt_identity, get_jwt -) from app.models import User, db from app.security import generate_captcha, verify_captcha +from flask import Blueprint, jsonify, request +from flask_jwt_extended import (create_access_token, create_refresh_token, + get_jwt, get_jwt_identity, jwt_required) +from werkzeug.security import check_password_hash, generate_password_hash + +auth_blueprint = Blueprint("auth", __name__) -auth_blueprint = Blueprint('auth', __name__) # User registration route -@auth_blueprint.route('/register', methods=['POST']) +@auth_blueprint.route("/register", methods=["POST"]) def register(): data = request.json - username = data.get('username') - password = data.get('password') - captcha = data.get('captcha') - actual_captcha = data.get('actual_captcha') + username = data.get("username") + password = data.get("password") + captcha = data.get("captcha") + actual_captcha = data.get("actual_captcha") if not verify_captcha(captcha, actual_captcha): return jsonify({"error": "Invalid CAPTCHA"}), 400 @@ -31,34 +30,41 @@ def register(): return jsonify({"message": "User registered successfully"}), 201 + # Login route -@auth_blueprint.route('/login', methods=['POST']) +@auth_blueprint.route("/login", methods=["POST"]) @limiter.limit("5 per minute") def login(): data = request.json - username = data.get('username') - password = data.get('password') + username = data.get("username") + password = data.get("password") user = User.query.filter_by(username=username).first() if not user or not user.check_password(password): return jsonify({"error": "Invalid credentials"}), 401 - access_token = create_access_token(identity={"username": user.username, "role": user.role}) - refresh_token = create_refresh_token(identity={"username": user.username, "role": user.role}) + access_token = create_access_token( + identity={"username": user.username, "role": user.role} + ) + refresh_token = create_refresh_token( + identity={"username": user.username, "role": user.role} + ) return jsonify(access_token=access_token, refresh_token=refresh_token), 200 + # Logout route -@auth_blueprint.route('/logout', methods=['POST']) +@auth_blueprint.route("/logout", methods=["POST"]) @jwt_required() def logout(): jti = get_jwt()["jti"] blacklist.add(jti) return jsonify({"message": "Successfully logged out"}), 200 + # Token refresh route -@auth_blueprint.route('/refresh', methods=['POST']) +@auth_blueprint.route("/refresh", methods=["POST"]) @jwt_required(refresh=True) def refresh_token(): current_user = get_jwt_identity() diff --git a/authentication_and_rolemanagement/app/database.py b/authentication_and_rolemanagement/app/database.py index 00d4e304..3bc07ad0 100644 --- a/authentication_and_rolemanagement/app/database.py +++ b/authentication_and_rolemanagement/app/database.py @@ -1,10 +1,11 @@ -from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate +from flask_sqlalchemy import SQLAlchemy # Initialize SQLAlchemy and Migrate db = SQLAlchemy() migrate = Migrate() + def init_db(app): """Initialize the database with the Flask app.""" db.init_app(app) diff --git a/authentication_and_rolemanagement/app/models.py b/authentication_and_rolemanagement/app/models.py index 14c26be9..90931fbb 100644 --- a/authentication_and_rolemanagement/app/models.py +++ b/authentication_and_rolemanagement/app/models.py @@ -1,13 +1,14 @@ from flask_sqlalchemy import SQLAlchemy -from werkzeug.security import generate_password_hash, check_password_hash +from werkzeug.security import check_password_hash, generate_password_hash db = SQLAlchemy() + class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(150), nullable=False, unique=True) password_hash = db.Column(db.String(128), nullable=False) - role = db.Column(db.String(10), default='user') # Roles: 'admin', 'user' + role = db.Column(db.String(10), default="user") # Roles: 'admin', 'user' def set_password(self, password): self.password_hash = generate_password_hash(password) diff --git a/authentication_and_rolemanagement/app/routes.py b/authentication_and_rolemanagement/app/routes.py index f7986eab..84c5ab44 100644 --- a/authentication_and_rolemanagement/app/routes.py +++ b/authentication_and_rolemanagement/app/routes.py @@ -1,23 +1,24 @@ -from flask import request, jsonify -from flask_jwt_extended import jwt_required, get_jwt_identity from app.models import User, db +from flask import jsonify, request +from flask_jwt_extended import get_jwt_identity, jwt_required + # Update user profile route -@auth_blueprint.route('/update-profile', methods=['PUT']) +@auth_blueprint.route("/update-profile", methods=["PUT"]) @jwt_required() def update_profile(): current_user_data = get_jwt_identity() data = request.json - user = User.query.filter_by(username=current_user_data['username']).first() + user = User.query.filter_by(username=current_user_data["username"]).first() if not user: return jsonify({"error": "User not found"}), 404 - user.username = data.get('username', user.username) - - if data.get('password'): - user.set_password(data['password']) + user.username = data.get("username", user.username) + + if data.get("password"): + user.set_password(data["password"]) db.session.commit() diff --git a/authentication_and_rolemanagement/app/security.py b/authentication_and_rolemanagement/app/security.py index 9ad398c1..807a85c7 100644 --- a/authentication_and_rolemanagement/app/security.py +++ b/authentication_and_rolemanagement/app/security.py @@ -1,10 +1,12 @@ import random import string + def generate_captcha(): letters = string.ascii_letters - captcha_text = ''.join(random.choice(letters) for i in range(6)) + captcha_text = "".join(random.choice(letters) for i in range(6)) return captcha_text + def verify_captcha(user_input, actual_captcha): return user_input == actual_captcha diff --git a/authentication_and_rolemanagement/run.py b/authentication_and_rolemanagement/run.py index 45db384a..5d85f357 100644 --- a/authentication_and_rolemanagement/run.py +++ b/authentication_and_rolemanagement/run.py @@ -3,7 +3,7 @@ app = create_app() -if __name__ == '__main__': +if __name__ == "__main__": with app.app_context(): db.create_all() # Create tables app.run(debug=True)