Configuracion final de back con serve
This commit is contained in:
48
Back_comercial_iko/core/Auth.py
Normal file
48
Back_comercial_iko/core/Auth.py
Normal file
@@ -0,0 +1,48 @@
|
||||
import jwt
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Dict, Any
|
||||
from core.Config import settings
|
||||
|
||||
|
||||
class TokenManager:
|
||||
"""
|
||||
Handles token generation and validation
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def generate(cls, payload: Dict[str, Any]) -> str:
|
||||
data = cls._add_expiration(payload)
|
||||
|
||||
return jwt.encode(
|
||||
data,
|
||||
settings.token_secret_key,
|
||||
algorithm=settings.token_algorithm
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def verify(cls, token: str) -> Dict[str, Any]:
|
||||
|
||||
try:
|
||||
return jwt.decode(
|
||||
token,
|
||||
settings.token_secret_key,
|
||||
algorithms=[settings.token_algorithm]
|
||||
)
|
||||
|
||||
except jwt.ExpiredSignatureError:
|
||||
raise ValueError("Token expired")
|
||||
|
||||
except jwt.InvalidTokenError:
|
||||
raise ValueError("Invalid token")
|
||||
|
||||
@classmethod
|
||||
def _add_expiration(cls, payload: Dict[str, Any]) -> Dict[str, Any]:
|
||||
|
||||
expiration = datetime.utcnow() + timedelta(
|
||||
minutes=settings.token_expire_minutes
|
||||
)
|
||||
|
||||
data = payload.copy()
|
||||
data["exp"] = expiration
|
||||
|
||||
return data
|
||||
15
Back_comercial_iko/core/Config.py
Normal file
15
Back_comercial_iko/core/Config.py
Normal file
@@ -0,0 +1,15 @@
|
||||
from pydantic_settings import BaseSettings
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
|
||||
token_secret_key: str
|
||||
token_algorithm: str
|
||||
token_expire_minutes: int
|
||||
|
||||
class Config:
|
||||
env_file = ".env"
|
||||
extra = "ignore"
|
||||
|
||||
|
||||
settings = Settings()
|
||||
16
Back_comercial_iko/core/ExceptionHandler.py
Normal file
16
Back_comercial_iko/core/ExceptionHandler.py
Normal file
@@ -0,0 +1,16 @@
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi import Request
|
||||
from Back_comercial_iko.core.HttpStatus import HttpStatus
|
||||
|
||||
|
||||
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
||||
|
||||
return JSONResponse(
|
||||
status_code=HttpStatus.BAD_REQUEST,
|
||||
content={
|
||||
"success": False,
|
||||
"message": "Formato de request inválido",
|
||||
"error_code": "INVALID_JSON"
|
||||
}
|
||||
)
|
||||
14
Back_comercial_iko/core/HttpStatus.py
Normal file
14
Back_comercial_iko/core/HttpStatus.py
Normal file
@@ -0,0 +1,14 @@
|
||||
class HttpStatus:
|
||||
"""
|
||||
Common HTTP status codes used in the API
|
||||
"""
|
||||
OK = 200
|
||||
CREATED = 201
|
||||
NO_CONTENT = 204
|
||||
BAD_REQUEST = 400
|
||||
UNAUTHORIZED = 401
|
||||
FORBIDDEN = 403
|
||||
NOT_FOUND = 404
|
||||
CONFLICT = 409
|
||||
UNPROCESSABLE_ENTITY = 422
|
||||
INTERNAL_SERVER_ERROR = 500
|
||||
53
Back_comercial_iko/core/Response.py
Normal file
53
Back_comercial_iko/core/Response.py
Normal file
@@ -0,0 +1,53 @@
|
||||
from fastapi.responses import JSONResponse
|
||||
from typing import Any, Optional
|
||||
from Back_comercial_iko.core.HttpStatus import HttpStatus
|
||||
|
||||
|
||||
class ApiResponse:
|
||||
|
||||
@staticmethod
|
||||
def success(
|
||||
data: Optional[Any] = None,
|
||||
message: str = "Success",
|
||||
status_code: int = HttpStatus.OK
|
||||
):
|
||||
|
||||
return JSONResponse(
|
||||
status_code=status_code,
|
||||
content={
|
||||
"success": True,
|
||||
"message": message,
|
||||
"data": data
|
||||
}
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def error(
|
||||
message: str,
|
||||
status_code: int = HttpStatus.BAD_REQUEST,
|
||||
data: Optional[Any] = None
|
||||
):
|
||||
|
||||
return JSONResponse(
|
||||
status_code=status_code,
|
||||
content={
|
||||
"success": False,
|
||||
"message": message,
|
||||
"data": data
|
||||
}
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def exception(
|
||||
exception: Exception,
|
||||
status_code: int = HttpStatus.INTERNAL_SERVER_ERROR
|
||||
):
|
||||
|
||||
return JSONResponse(
|
||||
status_code=status_code,
|
||||
content={
|
||||
"success": False,
|
||||
"message": str(exception),
|
||||
"data": None
|
||||
}
|
||||
)
|
||||
10
Back_comercial_iko/core/SocieteNotFoundException.py
Normal file
10
Back_comercial_iko/core/SocieteNotFoundException.py
Normal file
@@ -0,0 +1,10 @@
|
||||
class SocieteNotFoundException(Exception):
|
||||
def __init__(self, societe_name=None, extra_msg=None):
|
||||
base_message = "Societe not found"
|
||||
if societe_name:
|
||||
base_message += f": '{societe_name}'"
|
||||
if extra_msg:
|
||||
base_message += f" - {extra_msg}"
|
||||
|
||||
self.message = base_message
|
||||
super().__init__(self.message)
|
||||
13
Back_comercial_iko/core/validators/Email_validator.py
Normal file
13
Back_comercial_iko/core/validators/Email_validator.py
Normal file
@@ -0,0 +1,13 @@
|
||||
import re
|
||||
|
||||
class EmailValidator:
|
||||
|
||||
EMAIL_REGEX = r"^[\w\.-]+@[\w\.-]+\.\w+$"
|
||||
|
||||
@staticmethod
|
||||
def validate(email: str) -> bool:
|
||||
|
||||
if not email:
|
||||
return False
|
||||
|
||||
return re.match(EmailValidator.EMAIL_REGEX, email) is not None
|
||||
7
Back_comercial_iko/core/validators/Field_validator.py
Normal file
7
Back_comercial_iko/core/validators/Field_validator.py
Normal file
@@ -0,0 +1,7 @@
|
||||
class FieldValidator:
|
||||
|
||||
@staticmethod
|
||||
def required(value, field_name: str):
|
||||
|
||||
if value is None or value == "":
|
||||
raise ValueError(f"{field_name} es obligatorio")
|
||||
Reference in New Issue
Block a user