Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Main #91

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open

Main #91

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file.
17 changes: 17 additions & 0 deletions FaceRecoginitionProject/FaceRecoginitionProject/asgi.py
Original file line number Diff line number Diff line change
@@ -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()
131 changes: 131 additions & 0 deletions FaceRecoginitionProject/FaceRecoginitionProject/settings.py
Original file line number Diff line number Diff line change
@@ -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"
29 changes: 29 additions & 0 deletions FaceRecoginitionProject/FaceRecoginitionProject/urls.py
Original file line number Diff line number Diff line change
@@ -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"),
]
17 changes: 17 additions & 0 deletions FaceRecoginitionProject/FaceRecoginitionProject/wsgi.py
Original file line number Diff line number Diff line change
@@ -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()
23 changes: 23 additions & 0 deletions FaceRecoginitionProject/manage.py
Original file line number Diff line number Diff line change
@@ -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()
10 changes: 10 additions & 0 deletions authentication_and_rolemanagement/api/__init__.py
Original file line number Diff line number Diff line change
@@ -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"])
31 changes: 31 additions & 0 deletions authentication_and_rolemanagement/api/auth.py
Original file line number Diff line number Diff line change
@@ -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
6 changes: 6 additions & 0 deletions authentication_and_rolemanagement/api/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import uvicorn

from . import app

if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
17 changes: 17 additions & 0 deletions authentication_and_rolemanagement/api/models.py
Original file line number Diff line number Diff line change
@@ -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
33 changes: 33 additions & 0 deletions authentication_and_rolemanagement/app/__init__.py
Original file line number Diff line number Diff line change
@@ -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
72 changes: 72 additions & 0 deletions authentication_and_rolemanagement/app/auth.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading