Skip to content

Commit

Permalink
[pre-commit.ci] auto fixes from pre-commit.com hooks
Browse files Browse the repository at this point in the history
for more information, see https://pre-commit.ci
  • Loading branch information
pre-commit-ci[bot] committed Oct 17, 2024
1 parent 316d23d commit a387927
Show file tree
Hide file tree
Showing 11 changed files with 74 additions and 49 deletions.
2 changes: 1 addition & 1 deletion authentication_and_rolemanagement/api/__init__.py
Original file line number Diff line number Diff line change
@@ -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"])
21 changes: 14 additions & 7 deletions authentication_and_rolemanagement/api/auth.py
Original file line number Diff line number Diff line change
@@ -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
1 change: 1 addition & 0 deletions authentication_and_rolemanagement/api/main.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import uvicorn

from . import app

if __name__ == "__main__":
Expand Down
3 changes: 3 additions & 0 deletions authentication_and_rolemanagement/api/models.py
Original file line number Diff line number Diff line change
@@ -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

Expand Down
21 changes: 12 additions & 9 deletions authentication_and_rolemanagement/app/__init__.py
Original file line number Diff line number Diff line change
@@ -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)
Expand All @@ -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
44 changes: 25 additions & 19 deletions authentication_and_rolemanagement/app/auth.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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()
Expand Down
3 changes: 2 additions & 1 deletion authentication_and_rolemanagement/app/database.py
Original file line number Diff line number Diff line change
@@ -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)
Expand Down
5 changes: 3 additions & 2 deletions authentication_and_rolemanagement/app/models.py
Original file line number Diff line number Diff line change
@@ -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)
Expand Down
17 changes: 9 additions & 8 deletions authentication_and_rolemanagement/app/routes.py
Original file line number Diff line number Diff line change
@@ -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()

Expand Down
4 changes: 3 additions & 1 deletion authentication_and_rolemanagement/app/security.py
Original file line number Diff line number Diff line change
@@ -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
2 changes: 1 addition & 1 deletion authentication_and_rolemanagement/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

0 comments on commit a387927

Please sign in to comment.