diff --git a/FaceRecoginitionProject/FaceRecoginitionProject/__init__.py b/FaceRecoginitionProject/FaceRecoginitionProject/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/FaceRecoginitionProject/FaceRecoginitionProject/asgi.py b/FaceRecoginitionProject/FaceRecoginitionProject/asgi.py new file mode 100644 index 0000000..083e633 --- /dev/null +++ b/FaceRecoginitionProject/FaceRecoginitionProject/asgi.py @@ -0,0 +1,17 @@ +""" +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 0000000..87c44ff --- /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/ +""" + +from pathlib import Path + +INSTALLED_APPS = [ + # other apps + "authentication", +] + +AUTH_USER_MODEL = "authentication.CustomUser" + + +# 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 0000000..2521ca4 --- /dev/null +++ b/FaceRecoginitionProject/FaceRecoginitionProject/urls.py @@ -0,0 +1,29 @@ +""" +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 include, path + +urlpatterns = [ + path("admin/", admin.site.urls), +] + + +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 0000000..11cbf0c --- /dev/null +++ b/FaceRecoginitionProject/FaceRecoginitionProject/wsgi.py @@ -0,0 +1,17 @@ +""" +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 0000000..a02a0a0 --- /dev/null +++ b/FaceRecoginitionProject/manage.py @@ -0,0 +1,23 @@ +#!/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/authentication_and_rolemanagement/api/__init__.py b/authentication_and_rolemanagement/api/__init__.py new file mode 100644 index 0000000..57df6df --- /dev/null +++ b/authentication_and_rolemanagement/api/__init__.py @@ -0,0 +1,10 @@ +from .auth import router as auth_router +from fastapi import FastAPI + +# Initialize FastAPI +app = FastAPI() + +# Import routes to register them + +# 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 0000000..32a5506 --- /dev/null +++ b/authentication_and_rolemanagement/api/auth.py @@ -0,0 +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 + +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 0000000..9744c43 --- /dev/null +++ b/authentication_and_rolemanagement/api/main.py @@ -0,0 +1,6 @@ +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 0000000..bbd70e0 --- /dev/null +++ b/authentication_and_rolemanagement/api/models.py @@ -0,0 +1,17 @@ +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 0000000..66abe0b --- /dev/null +++ b/authentication_and_rolemanagement/app/__init__.py @@ -0,0 +1,33 @@ +from app import auth, routes +from datetime import timedelta + +from flask import Flask +from flask_jwt_extended import JWTManager +from flask_limiter import Limiter +from flask_limiter.util import get_remote_address +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) + +# 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 diff --git a/authentication_and_rolemanagement/app/auth.py b/authentication_and_rolemanagement/app/auth.py new file mode 100644 index 0000000..de362ff --- /dev/null +++ b/authentication_and_rolemanagement/app/auth.py @@ -0,0 +1,72 @@ +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__) + + +# 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 0000000..3bc07ad --- /dev/null +++ b/authentication_and_rolemanagement/app/database.py @@ -0,0 +1,12 @@ +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) + 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 0000000..90931fb --- /dev/null +++ b/authentication_and_rolemanagement/app/models.py @@ -0,0 +1,17 @@ +from flask_sqlalchemy import SQLAlchemy +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' + + 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 0000000..84c5ab4 --- /dev/null +++ b/authentication_and_rolemanagement/app/routes.py @@ -0,0 +1,25 @@ +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"]) +@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 0000000..807a85c --- /dev/null +++ b/authentication_and_rolemanagement/app/security.py @@ -0,0 +1,12 @@ +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 0000000..74be940 --- /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 0000000..5d85f35 --- /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)