403Webshell
Server IP : 185.11.201.71  /  Your IP : 192.168.7.18
Web Server : Apache/2.4.29 (Ubuntu)
System : Linux tech-virtual-machine 4.15.0-213-generic #224-Ubuntu SMP Mon Jun 19 13:30:12 UTC 2023 x86_64
User : tech ( 1000)
PHP Version : 7.4.28
Disable Function : pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
MySQL : OFF  |  cURL : OFF  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : ON  |  Pkexec : ON
Directory :  /comunica/app_ojos/app/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /comunica/app_ojos/app/auth.py
# from base64 import decode
import logging
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer, OAuth2PasswordBearer
import jwt.algorithms
import jwt.utils
from sqlalchemy.orm import Session
from passlib.context import CryptContext
from jose import JWTError
from jwt import decode
from fastapi import APIRouter, Depends, HTTPException, status
from datetime import datetime, timedelta

from models import User  # Importa el modelo de usuario real
from database import get_db  # Importa la función para obtener la sesión de la DB
from config import DEBUG

# Configuración de JWT
SECRET_KEY = "your_secret_key"  # Debe ser una clave segura y mantenida en secreto
ALGORITHM = "HS256"
if DEBUG:
    ACCESS_TOKEN_EXPIRE_MINUTES = 180
else: 
    ACCESS_TOKEN_EXPIRE_MINUTES = 30

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

# Aquí se define oauth2_scheme
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

security = HTTPBearer()

def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)

def get_password_hash(password):
    return pwd_context.hash(password)

def get_user(db: Session, username: str):
    return db.query(User).filter(User.username == username).first()

def authenticate_user(db: Session, username: str, password: str):
    user = get_user(db, username)
    if not user:
        return False
    if not verify_password(password, user.hashed_password):
        return False
    return user

def create_access_token(data: dict, expires_delta: timedelta = None):
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + timedelta(minutes=15)
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt


def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
    token = credentials.credentials
    # Lógica para validar el token
    return is_token_valid(token)


def is_token_valid(token: str):
    try:
        # Decoding the JWT token
        if DEBUG: return "True"
        payload = decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username = payload.get("sub")
        if username is None:
            # Username is expected as part of the payload, raise an exception if not found
            raise HTTPException(status_code=401, detail="Could not validate credentials")
        return username  # Or return payload if you need the whole object
    except JWTError:
        # Handle specific jwt errors or a general invalid token error
        raise HTTPException(status_code=401, detail="Invalid token or expired token")
    except Exception as e:
        # A general catch-all for unexpected errors, not typically recommended without logging
        raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")


async def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)):
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    
    # Llamada a la función separada
    payload = verify_token(token, credentials_exception)
    
    # Recuperar el username desde el payload
    username: str = payload.get("sub")
    
    # Buscar el usuario en la base de datos
    user = get_user(db, username)
    if user is None:
        raise credentials_exception
    
    return user


async def get_current_active_user(current_user: User = Depends(get_current_user)):
    if not current_user.is_active:
        raise HTTPException(status_code=400, detail="Inactive user")
    return current_user


if __name__ == '__main__':
    print(get_password_hash("password"))

Youez - 2016 - github.com/yon3zu
LinuXploit