Access tokens 0.1.0
This commit is contained in:
26
src/database/users/crud.py
Normal file
26
src/database/users/crud.py
Normal file
@@ -0,0 +1,26 @@
|
||||
from sqlalchemy import select
|
||||
from src.models.database_models.model import User, engine
|
||||
from src.models.pydantic_models.model import UserOutDB
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from uuid import UUID
|
||||
class UsersCrudActions:
|
||||
def __init__(self) -> None:
|
||||
self.Session=sessionmaker(bind=engine)
|
||||
|
||||
def get_user_by_email(self, email:str)->UserOutDB|None:
|
||||
with self.Session() as session:
|
||||
with session.begin():
|
||||
query=select(User).where(User.email==email)
|
||||
response=session.scalars(query).one_or_none()
|
||||
if response is None:
|
||||
return None
|
||||
return UserOutDB.model_validate(response)
|
||||
|
||||
def get_user_by_id(self, id:UUID)->UserOutDB|None:
|
||||
with self.Session() as session:
|
||||
with session.begin():
|
||||
query=select(User).where(User.id==id)
|
||||
response=session.scalars(query).one_or_none()
|
||||
if response is None:
|
||||
return None
|
||||
return UserOutDB.model_validate(response)
|
||||
32
src/migrations/versions/2f92088cdce4_.py
Normal file
32
src/migrations/versions/2f92088cdce4_.py
Normal file
@@ -0,0 +1,32 @@
|
||||
"""empty message
|
||||
|
||||
Revision ID: 2f92088cdce4
|
||||
Revises: 75074097a2a3
|
||||
Create Date: 2026-07-23 11:05:02.409697
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = '2f92088cdce4'
|
||||
down_revision: Union[str, Sequence[str], None] = '75074097a2a3'
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Upgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
pass
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Downgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
pass
|
||||
# ### end Alembic commands ###
|
||||
@@ -1,4 +1,4 @@
|
||||
from sqlalchemy import TIMESTAMP, Table, create_engine, String, Boolean, MetaData, Column, ForeignKey, func
|
||||
from sqlalchemy import TIMESTAMP, Table, create_engine, String, Boolean, MetaData, Column, ForeignKey, func, Uuid
|
||||
from sqlalchemy.orm import Mapped, mapped_column, DeclarativeBase, relationship
|
||||
from uuid import UUID, uuid4
|
||||
from datetime import datetime
|
||||
@@ -17,7 +17,7 @@ class Model(DeclarativeBase):
|
||||
class User(Model):
|
||||
__tablename__ = "users"
|
||||
|
||||
id:Mapped[UUID] = mapped_column(default=uuid4,primary_key=True)
|
||||
id:Mapped[UUID] = mapped_column(Uuid(as_uuid=True),default=uuid4,primary_key=True)
|
||||
first_name:Mapped[str] = mapped_column(String(64), index=True)
|
||||
last_name:Mapped[str]=mapped_column(String(64), index=True)
|
||||
middle_name:Mapped[str]=mapped_column(String(64), index=True)
|
||||
|
||||
@@ -20,15 +20,18 @@ class UserCreate(Base):
|
||||
|
||||
class UserOut(Base):
|
||||
|
||||
id:Annotated[UUID, Field(..., description="Id of the user")]
|
||||
first_name:Annotated[str, Field(..., max_length=64,description="first name of the user")]
|
||||
last_name:Annotated[str, Field(..., max_length=64,description="last name of the user")]
|
||||
middle_name:Annotated[str, Field(..., max_length=64, description="middle name of the user")]
|
||||
email:Annotated[EmailStr, Field(...,min_length=5, max_length=255, description="email of the user")]
|
||||
status:Annotated[bool, Field(..., description="status of the user")]
|
||||
permissions:Annotated[list[str], Field(..., description="permissions of the user")]
|
||||
permission_groups:Annotated[list[str], Field(..., description="permissions groups of the user")]
|
||||
|
||||
# permissions:Annotated[list[str], Field(..., description="permissions of the user")]
|
||||
# permission_groups:Annotated[list[str], Field(..., description="permissions groups of the user")]
|
||||
|
||||
class UserOutDB(UserOut):
|
||||
id:Annotated[UUID, Field(..., description="Id of the user")]
|
||||
status:Annotated[bool, Field(..., description="status of the user")]
|
||||
hashed_password:Annotated[str, Field(..., description="hashed password of the user")]
|
||||
|
||||
class UserUpdate(Base):
|
||||
|
||||
|
||||
51
src/service/auth/auth.py
Normal file
51
src/service/auth/auth.py
Normal file
@@ -0,0 +1,51 @@
|
||||
from uuid import UUID
|
||||
from .jwt import Jwt, Hashes
|
||||
from src.database.users.crud import UsersCrudActions
|
||||
from src.errors.http_errors.errors import Errors
|
||||
|
||||
from src.models.pydantic_models.model import UserOut
|
||||
class CurrentUser:
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.jwt_service=Jwt()
|
||||
self.hash=Hashes()
|
||||
self.crud_actions=UsersCrudActions()
|
||||
self.error=Errors()
|
||||
|
||||
|
||||
def get_current_user(self, token:str)->UserOut:
|
||||
|
||||
payload=self.jwt_service.jwt_decode(token)
|
||||
sub=payload.get("sub")
|
||||
print(sub)
|
||||
if sub is None:
|
||||
raise self.error.credentials_error(detail="Jwt token is incorrect")
|
||||
try:
|
||||
UUID(sub)
|
||||
except (ValueError, TypeError):
|
||||
raise self.error.credentials_error(detail="Jwt token is incorrect")
|
||||
|
||||
user=self.crud_actions.get_user_by_id(UUID(sub))
|
||||
|
||||
if user is None:
|
||||
raise self.error.not_found_error(detail="User with this email address not found")
|
||||
|
||||
return UserOut.model_validate(user)
|
||||
|
||||
|
||||
def create_token(self, form_data_email:str, form_data_password:str)->dict:
|
||||
|
||||
user=self.crud_actions.get_user_by_email(form_data_email)
|
||||
|
||||
if user is None:
|
||||
raise self.error.credentials_error(detail="Wrong credentials")
|
||||
|
||||
if not self.hash.verify_password(plain_password=form_data_password, hashed_password=user.hashed_password):
|
||||
raise self.error.credentials_error(detail="Wrong credentials")
|
||||
|
||||
if user.status is False:
|
||||
raise self.error.credentials_error(detail="This user is deactivated")
|
||||
|
||||
return {"access_token":self.jwt_service.create_token({"sub":str(user.id)}), "token_type":"bearer"}
|
||||
|
||||
auth=CurrentUser()
|
||||
46
src/service/auth/jwt.py
Normal file
46
src/service/auth/jwt.py
Normal file
@@ -0,0 +1,46 @@
|
||||
from jose import JWTError, jwt
|
||||
import bcrypt
|
||||
from src.errors.http_errors.errors import Errors
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from src.models.configs_read.env import env_settings
|
||||
'''Hash/Check hash'''
|
||||
class Hashes:
|
||||
|
||||
def __init__(self) -> None:
|
||||
pass
|
||||
|
||||
def plain_to_hash(self, plain_password:str)->str:
|
||||
return bcrypt.hashpw(plain_password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
|
||||
|
||||
def verify_password(self, plain_password:str, hashed_password:str)->bool:
|
||||
return bcrypt.checkpw(plain_password.encode("utf-8"), hashed_password.encode("utf-8"))
|
||||
|
||||
|
||||
'''jwt'''
|
||||
class Jwt:
|
||||
def __init__(self) -> None:
|
||||
self.error=Errors()
|
||||
|
||||
def create_token(self, data:dict)->str:
|
||||
|
||||
user_info=data.copy()
|
||||
user_info.update({"exp": datetime.now(timezone.utc)+timedelta(minutes=env_settings.ACCESS_TOKEN_EXPIRE_MINUTES)})
|
||||
|
||||
return jwt.encode(user_info, env_settings.SECRET_KEY, env_settings.ALGORITHM)
|
||||
|
||||
|
||||
def jwt_decode(self, token:str)->dict:
|
||||
|
||||
try:
|
||||
|
||||
payload=jwt.decode(token, env_settings.SECRET_KEY, algorithms=[env_settings.ALGORITHM])
|
||||
|
||||
if (payload.get("sub")) is None:
|
||||
raise self.error.credentials_error(detail="Sub block is missing")
|
||||
|
||||
except JWTError as e:
|
||||
|
||||
raise self.error.credentials_error(detail="JWTerror") from e
|
||||
|
||||
return payload
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
from fastapi import APIRouter
|
||||
from fastapi import APIRouter, Depends
|
||||
from fastapi.security import OAuth2PasswordRequestForm, OAuth2PasswordBearer
|
||||
|
||||
from src.models.pydantic_models.model import UserOut
|
||||
|
||||
from src.service.auth.auth import auth
|
||||
|
||||
router=APIRouter(prefix="/protected")
|
||||
oauth2_scheme=OAuth2PasswordBearer(tokenUrl="/protected/token")
|
||||
oauth2_schema=OAuth2PasswordBearer(tokenUrl="/protected/token")
|
||||
|
||||
@router.post("/token")
|
||||
async def get_access_token(form_data:OAuth2PasswordRequestForm=Depends())->dict:
|
||||
return auth.create_token(form_data_email=form_data.username, form_data_password=form_data.password)
|
||||
|
||||
def get_current_user(token:str = Depends(oauth2_schema)) -> UserOut:
|
||||
return UserOut.model_validate(auth.get_current_user(token))
|
||||
|
||||
@router.get("")
|
||||
def protected()->dict:
|
||||
return {"protected router": "Hello, this is a protected router"}
|
||||
async def protected(current_user:UserOut=Depends(get_current_user))->dict:
|
||||
return {"protected router": "Hello, this is a protected router"}
|
||||
|
||||
Reference in New Issue
Block a user