Example #1
0
from src.models.user import TokenData, JWTToken, UserAPI

env_dep: EnvYAML = EnvYAML()

# cookie_sec = APIKeyCookie(name="session")

# JWT VARIABLES
JWT_KEY: str = env_dep["security.key"]
JWT_ALGORITHM: str = env_dep["security.algorithm"]
JWT_TOKEN_EXPIRE: int = env_dep["security.token_expire"]

# create password context
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

# create oauth2_schema
oauth2_bearer_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/users/login/",
                                            auto_error=False)
oauth2_scheme = OAuth2(auto_error=False)


def time_utc_now(timestamp: int = None) -> datetime:
    return datetime.fromtimestamp(
        timestamp, tz=timezone.utc) if timestamp else datetime.now(
            tz=timezone.utc)


def pwd_verify(plain_password: str, hashed_password: str) -> bool:
    return plain_password and hashed_password and pwd_context.verify(
        plain_password, hashed_password)


def pwd_hash(plain_password: str) -> str:
Example #2
0
from typing import Generator

from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import jwt
from pydantic import ValidationError

from app import schemas
from app.core import security
from app.core.config import settings

reusable_oauth2 = OAuth2PasswordBearer(
    tokenUrl=f"{settings.API_V1_STR}/auth/access-token")


def get_current_user(token: str = Depends(reusable_oauth2)) -> schemas.User:
    try:
        payload = jwt.decode(token,
                             settings.SECRET_KEY,
                             algorithms=[security.ALGORITHM])
        token_data = schemas.TokenPayload(**payload)
    except (jwt.JWTError, ValidationError):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Could not validate credentials",
        )

    # Проверить пользователя с логином token_data.sub по БД - заглушка
    user = {"login": token_data.sub, "full_name": settings.TEST_USER_FULL_NAME}

    if not user:
Example #3
0

class User(BaseModel):
    username: str
    email: Optional[str] = None
    full_name: Optional[str] = None
    disabled: Optional[bool] = None


class UserInDB(User):
    hashed_password: str


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

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")


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, username: str):
    if username in db:
        user_dict = db[username]
        return UserInDB(**user_dict)
Example #4
0
from typing import Generator

from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import jwt
from pydantic import ValidationError
from sqlalchemy.orm import Session

from app import models, schemas
from app.db import operations
from app.core import security
from app.core.config import app_settings
from app.db.session import SessionLocal

oauth2_password_bearer = OAuth2PasswordBearer(tokenUrl='/login/')


def get_db() -> Generator:
    try:
        db = SessionLocal()
        yield db
    finally:
        db.close()


def get_current_user(db: Session = Depends(get_db),
                     token: str = Depends(
                         oauth2_password_bearer)) -> models.User:
    try:
        payload = jwt.decode(token,
                             app_settings.SECRET_KEY,
Example #5
0
from fastapi.security import OAuth2PasswordBearer

from .auth import Authentication
from .rds import RdsHandler

authentication = Authentication(oauth_scheme=OAuth2PasswordBearer(
    tokenUrl="/oauth"))
rds_handler = RdsHandler()
Example #6
0
"""
import string
from datetime import datetime

import ujson as json
from fastapi import Security
from fastapi.security import OAuth2PasswordBearer
from pydantic import BaseModel, ValidationError
from sqlalchemy import select

from common.clients import clients
from common.errors import raise_401
from common.global_utils import id_generator
from model import t_user_info

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/users/token")
VALID_KEY_CHARS = string.ascii_lowercase + string.digits
TOKEN_REDIS_EXPIRES = 60 * 60 * 24


class SessionUser(BaseModel):
    nickname: str
    user_id: int
    quiz_total: int
    invite_total: int
    head_image: str
    quiz_win_total: int
    daily: int
    weekly: int
    monthly: int
Example #7
0
                      partner_id)

    def get_map(self, access_token):
        try:
            url = self.consul_service_resolver.resolve_url(self.endpoint)
            response = requests.get(url, params={'token': access_token})
            if response.status_code is not 200:
                return {'error': response.json()}
            json_response = response.json()
            return json_response
        except Exception as ex:
            LOGGER.exception('exception')
            return {'error': ex}


oauth2_scheme = OAuth2PasswordBearer(tokenUrl='/token')


def get_current_user(
    request: Request, token: str = Depends(oauth2_scheme)) -> User:
    user_info_token_services = InjectorUtils \
        .get_injector(request) \
        .get(UserInfoTokenService)
    user = user_info_token_services.load_authentication(token)
    return user


get_current_user = Depends(get_current_user)


def get_current_client(
Example #8
0
class Auth(BaseModel):
    #want to sign user jwts
    _secret = ENV.get("SECRET")
    pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
    oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
Example #9
0
from jwt import decode, ExpiredSignatureError

from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm

ACCESS_TOKEN_SECRET = 'secret_access_token'

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/v1/token/access/")


def get_access_token(auth_token: str = Depends(oauth2_scheme)):
    return auth_token


def decode_access_token(access_token: str):
    try:
        return decode(
            access_token,
            ACCESS_TOKEN_SECRET,
            algorithms=['HS256'],
        )
    except (Exception, ExpiredSignatureError):
        return None


async def get_access_token_payload(
        access_token: str = Depends(get_access_token)):
    payload = decode_access_token(access_token)

    if not payload:
        raise HTTPException(
Example #10
0
from fastapi.security import OAuth2PasswordBearer

from app import crud, db, errors, security
from app.entities import Namespace, User
from app.security import TokenPayload

from . import exceptions

__all__ = [
    "current_user",
    "current_user_id",
    "db_client",
    "superuser",
]

reusable_oauth2 = OAuth2PasswordBearer(tokenUrl="/auth/tokens",
                                       auto_error=False)

# This is just an alias to be consistent and import all deps from one place
db_client = db.client


def token_payload(token: str
                  | None = Depends(reusable_oauth2)) -> TokenPayload:
    """Return payload from authentication token."""
    if token is None:
        raise exceptions.MissingToken() from None

    try:
        return security.decode_token(token)
    except security.InvalidToken as exc:
        raise exceptions.InvalidToken() from exc
Example #11
0
from typing import Optional
from uuid import UUID, uuid4

from databases import Database
from fastapi import (Depends, HTTPException, status)
from fastapi.security import OAuth2PasswordBearer
from jose import jwt
from pydantic import ValidationError

from .db import get_db
from .security import decode_token
from . import schemas
from .services import UserService

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/login/access-token/",
                                     auto_error=False)

anonymous_user = schemas.UserInDb(uid=uuid4(),
                                  id=-1,
                                  is_anonymous=True,
                                  is_active=True,
                                  is_superuser=False)


async def get_current_user(db: Database = Depends(get_db),
                           token: str = Depends(oauth2_scheme)) -> Optional[
                               schemas.UserInDb]:
    if token:
        try:
            payload = decode_token(token)
            token_data = schemas.TokenPayload(**payload)
Example #12
0
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm

app = FastAPI()

oauth_sheme = OAuth2PasswordBearer(tokenUrl='token')


@app.post('/token')
async def gen_token(form_data: OAuth2PasswordRequestForm = Depends()):
    return {'access_token': form_data.username + 'token'}


@app.get('/')
async def index(token: str = Depends(oauth_sheme)):
    return {'the_token': token}
Example #13
0
from jose import JWTError
from starlette import requests

from compass.api.schemas.auth import User
from compass.api.util.http_errors import auth_error
import compass.core as ci
from compass.core.logger import logger

if TYPE_CHECKING:
    from aioredis import Redis

SECRET_KEY = os.environ["SECRET_KEY"]  # hard fail if key not in env
aes_gcm = AESGCM(bytes.fromhex(SECRET_KEY))
ALGORITHM = "HS256"
SESSION_STORE = Path(os.getenv("CI_SESSION_STORE", "sessions/")).resolve()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="v1/token/")


async def encrypt(data: bytes) -> bytes:
    nonce = os.urandom(12)  # GCM mode needs 12 fresh bytes every time
    return nonce + aes_gcm.encrypt(nonce, data, None)


async def store_kv(key: str,
                   value: bytes,
                   redis: Optional[Redis] = None,
                   expire_seconds: int = 600) -> None:
    # expire param is integer number of seconds for key to live
    if redis is not None:
        await redis.set(f"session:{key}", value, expire=expire_seconds)
    SESSION_STORE.joinpath(f"{key}.bin").write_bytes(value)  # TODO async
Example #14
0
from fastapi import Depends
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy.orm import Session

from app.common.auth import decode_token, TokenDecodeException, credentials_exception
from app.common.db_init import SessionLocal, engine
from app.config import PLAYERS_API_SECRET_KEY, PUBLISHER_API_SECRET_KEY
from app.crud import auth

studio_oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth/login")
players_oauth2_scheme = OAuth2PasswordBearer(tokenUrl="players/token")


def get_db():
    db = SessionLocal(bind=engine)
    try:
        yield db
    finally:
        db.close()


async def get_current_player(db: Session = Depends(get_db),
                             token: str = Depends(players_oauth2_scheme)):
    try:
        payload = decode_token(token, PLAYERS_API_SECRET_KEY)
    except TokenDecodeException:
        raise credentials_exception
    player = auth.get_player_by_id(db, player_id=payload.get("id"))
    if player is None:
        raise credentials_exception
    return player
from passlib.context import CryptContext
from models.jwtUser import JWTUser
from datetime import datetime, timedelta
from utils.const import JWT_EXPIRATION_TIME_MINUTES, JWT_ALGORITHM, JWT_SECRET_KEY
import jwt
from fastapi import Depends
from fastapi.security import OAuth2PasswordBearer
import time
import service.JWTUserService as JWTUserService

passwordContext = CryptContext(schemes=["bcrypt"])
oauthSchema = OAuth2PasswordBearer(tokenUrl="/token")


def getHashedPassword(password):
    return passwordContext.hash(password)


def verifyPassword(password, hashPassword):
    try:
        return passwordContext.verify(password, hashPassword)
    except Exception as e:
        return False


# Authenticate username and password to give JWT token
async def authenticateUser(user: JWTUser):
    validUser = await JWTUserService.getUserByEmail(user)

    if validUser != {} and verifyPassword(user.password,
                                          validUser["password"]):
Example #16
0
# get db session
from jose import jwt
from fastapi import Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
from pydantic import ValidationError
from sqlalchemy.orm import Session
from loguru import logger
from app import models, schemas
from app.config import settings
from app.database import SessionLocal, RedisLocal

oauth2_scheme = OAuth2PasswordBearer(tokenUrl=f"{settings.API_V1_STR}/login")


def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


def get_redis_db():
    redis = RedisLocal
    try:
        yield redis
    except Exception as e:
        logger.error(e)
    finally:
        redis.close()
Example #17
0
from fastapi import APIRouter, Depends, Header, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from passlib.context import CryptContext
from jose import JWTError, jwt

app06 = APIRouter()
''' OAuth2 密码模式和 FastAPI 的OAuth2PasswordBearer '''
'''
OAuth2PasswordBearer是接收url作为参数的一个类,客户端会向该url发送
passworld,username参数,然后得到一个token值
OAuth2PasswordBearer并不会创建相应的url路径操作,只是指明客户端用来请求token的url地址
当请求到来的时候,FastApi会检查侵权的Authorization头信息,如果没有找到Authorization头信息
或者头信息不是Bearer token,它会返回401状态码(UNAUTHORIZED)
'''
#请求token的url地址=http://127.0.0.0:8000/chapter06/token
oauth2_schema = OAuth2PasswordBearer(tokenUrl='/chapter06/token')


@app06.get("/oauth2_password_bearer")
async def oauth2_password_bearer(token: str = Depends(oauth2_schema)):
    return {"token": token}


''' 基于password 和 Bearer token的OAuth2认证'''

fake_users_db = {
    "jox": {
        "username": "******",
        "full_name": "jox x",
        "email": "*****@*****.**",
        "hashed_password": "******",
Example #18
0
ALGORITHM = "HS256"



class CreateUser(BaseModel):
    username: str
    email: Optional[str]
    first_name: str 
    last_name: str 
    password: str
    
  
bcrypt_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
models.Base.metadata.create_all(bind=engine)

oauth2_bearer = OAuth2PasswordBearer(tokenUrl="token")

# app = FastAPI()

router = APIRouter(prefix="/auth", tags=["auth"], responses={401: {"user": "******"}})

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


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

def get_db():
    try:
        db = SessionLocal()
import requests

from fastapi import Depends, FastAPI
from fastapi.exceptions import HTTPException
from fastapi.security import OAuth2PasswordBearer
from starlette.status import (HTTP_200_OK, HTTP_401_UNAUTHORIZED,
                              HTTP_500_INTERNAL_SERVER_ERROR)

app = FastAPI()

REALM = 'MyRealm'
KEYCLOAK_BASEURL = f'https://proxy/auth/realms' \
                   f'/{REALM}/protocol/openid-connect'

oauth2_scheme = OAuth2PasswordBearer(tokenUrl=KEYCLOAK_BASEURL + '/token')


async def auth(token: str = Depends(oauth2_scheme)):
    headers = {'Authorization': 'bearer ' + token}
    r_user = requests.get(KEYCLOAK_BASEURL + '/userinfo',
                          headers=headers,
                          verify=False)
    if r_user.status_code == HTTP_200_OK:
        return r_user.json()
    elif r_user.status_code == HTTP_401_UNAUTHORIZED:
        raise HTTPException(status_code=HTTP_401_UNAUTHORIZED,
                            detail=r_user.json())
    else:
        raise HTTPException(status_code=HTTP_500_INTERNAL_SERVER_ERROR,
                            detail='Internal authentication error (our bad)')
Example #20
0
import requests

from fastapi.security import OAuth2PasswordBearer
from fastapi import Depends, HTTPException, status

authurl = "https://tahurauser.herokuapp.com/api/v1/auth"
authsuperurl = "{}/authorized_super_admin".format(authurl)
authadminurl = "{}/authorized_admin".format(authurl)

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="{}/login".format(authurl))

credentials_exception = HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
                                      detail="Could not validate credentials",
                                      headers={"WWW-Authenticate": "Bearer"})


async def get_current_superadmin(token: str = Depends(oauth2_scheme)):
    print(token)
    headers = {'Authorization': 'Bearer {}'.format(token)}
    print(headers)
    r = requests.get(authsuperurl, headers=headers)
    if r.status_code != status.HTTP_200_OK:
        raise credentials_exception
    return True


async def get_current_admin(token: str = Depends(oauth2_scheme)):
    print(token)
    headers = {'Authorization': 'Bearer {}'.format(token)}
    print(headers)
    r = requests.get(authadminurl, headers=headers)
Example #21
0
    JWT_ALGORITHM: str = "HS256"

    ACCESS_TOKEN_EXPIRE_MINUTES: int = 60

    # Don't decrease this number unless you have a good reason not to.
    # Please read
    # https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html
    # #maximum-password-lengths
    MINIMUM_PASSWORD_LENGTH: int = 8

    # Don't increase this number unless you have a good reason not to.
    # Please read
    # https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html
    # #maximum-password-lengths
    MAXIMUM_PASSWORD_LENGTH: int = 16

    class Config:
        """Base Config for Settings."""

        env_file = BASE_DIR.joinpath(".env")


settings = Settings()

logger.add(sys.stderr,
           format="{time:YYYY-MM-DD at HH:mm:ss} | {level} | {message}")

OAUTH2_SCHEME = OAuth2PasswordBearer(tokenUrl="/users/login/")

PASSWORD_CONTEXT = CryptContext(schemes=["bcrypt"], deprecated="auto")
Example #22
0
    username: str
    email: str = None
    full_name: str = None
    disabled: bool = None


class UserInDB(User):
    hashed_password: str


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

oauth2_scheme = OAuth2PasswordBearer(
    tokenUrl="/token",
    scopes={
        "me": "Read information about the current user.",
        "items": "Read items."
    },
)

app = FastAPI()


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)

Example #23
0
from typing import Generator, Iterator

from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import jwt, JWTError
from pydantic import ValidationError
from sqlalchemy.orm import Session

from app import models, schemas
from app import config

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/users/login")


def get_db() -> Iterator[Session]:
    try:
        db = config.SessionLocal()
        yield db
    finally:
        db.close()


async def get_current_user(db: Session = Depends(get_db),
                           token: str = Depends(oauth2_scheme)) -> models.User:
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token,
Example #24
0
class Utility:
    pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
    oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login")
    environment = None

    @staticmethod
    def check_empty_string(value: str):
        if not value:
            return True
        if not value.strip():
            return True
        else:
            return False

    @staticmethod
    def prepare_nlu_text(example: Text, entities: List[Dict]):
        if not Utility.check_empty_string(example):
            if entities:
                for entity in entities:
                    example = example.replace(
                        entity["value"],
                        "[" + entity["value"] + "](" + entity["entity"] + ")",
                    )
        return example

    @staticmethod
    def validate_document_list(documents: List[BaseDocument]):
        if documents:
            for document in documents:
                document.validate()

    @staticmethod
    def load_yaml(file: Text):
        with open(file) as fp:
            return yaml.load(fp, yaml.FullLoader)

    @staticmethod
    def load_evironment():
        environment = Utility.load_yaml(
            os.getenv("system_file", "./system.yaml"))
        for key in environment:
            if key in os.environ:
                environment[key] = os.getenv(key)
        Utility.environment = environment

    @staticmethod
    def validate_fields(fields: Dict, data: Dict):
        error = ""
        for key, value in fields.items():
            if isinstance(value, StringField):
                if data[key] != None and str(data["key"]).strip():
                    error += "\n " + key + " cannot be empty or blank spaces"
            elif isinstance(value, ListField):
                if value.required and value:
                    error += "\n " + key + " cannot be empty"
        if error:
            raise error

    @staticmethod
    def is_exist(
        document: Document,
        query: Dict,
        exp_message: Text = None,
        raise_error=True,
    ):
        doc = document.objects(status=True, __raw__=query)
        if doc.__len__():
            if raise_error:
                if Utility.check_empty_string(exp_message):
                    raise AppException("Exception message cannot be empty")
                raise AppException(exp_message)
            else:
                return True
        else:
            if not raise_error:
                return False

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

    @staticmethod
    def get_password_hash(password):
        if not Utility.check_empty_string(password):
            return Utility.pwd_context.hash(password)

    @staticmethod
    def get_latest_file(folder):
        if not os.path.exists(folder):
            raise AppException("Folder does not exists!")
        return max(glob.iglob(folder + "/*"), key=os.path.getctime)

    @staticmethod
    def check_empty_list_elements(items: List[Text]):
        for item in items:
            if Utility.check_empty_string(item):
                return True
        return False

    @staticmethod
    def deploy_model(endpoint: Dict, bot: Text):
        if not endpoint or not endpoint.get("bot_endpoint"):
            raise AppException(
                "Please configure the bot endpoint for deployment!")
        headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
        url = endpoint["bot_endpoint"].get("url")
        if endpoint["bot_endpoint"].get(
                "token_type") and endpoint["bot_endpoint"].get("token"):
            headers['Authorization'] = endpoint["bot_endpoint"].get(
                "token_type") + " " + endpoint["bot_endpoint"].get("token")

        try:
            response = requests.put(url + "/model",
                                    json={
                                        "model_file":
                                        Utility.get_latest_file(
                                            os.path.join(
                                                DEFAULT_MODELS_PATH, bot))
                                    },
                                    headers=headers)
            json_response = response.json()
            if 'message' in json_response:
                result = json_response['message']
            elif 'reason' in json_response:
                result = json_response['reason']
            else:
                result = json_response
        except requests.exceptions.ConnectionError as e:
            raise AppException("Host is not reachable")
        return result

    @staticmethod
    def generate_password(size=6,
                          chars=string.ascii_uppercase + string.digits):
        return ''.join(random.choice(chars) for _ in range(size))
Example #25
0
app = FastAPI()


# Dependency


def get_db():
	db = None
	try:
		db = SessionLocal()
		yield db
	finally:import requests
	db.close()


oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/authenticate")


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"},
    )
    try:
        payload = decode_access_token(data=token)
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_data = TokenData(username=username)
    except PyJWTError:
Example #26
0
from datetime import datetime, timedelta
from os import getenv
from typing import Optional

from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import jwt, JWTError
from passlib.context import CryptContext
from pydantic import BaseModel

import database

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

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


def hash_password(password: str) -> str:
    return pwd_context.hash(password)


def authenticate_user(username: str, password: str):
    user = database.get_user(username)
    if user is None:
        return None
    if not pwd_context.verify(password, user.password_hash):
        return None
    return user


class Token(BaseModel):
Example #27
0
 def __init__(self, name: str = "mock"):
     super().__init__(name, logout=True)
     self.scheme = OAuth2PasswordBearer("/login", auto_error=False)
Example #28
0
import jwt
from fastapi import Depends, HTTPException, Security
from fastapi.security import OAuth2PasswordBearer
from jwt import PyJWTError
from sqlalchemy.orm import Session

from api.dependency.db import get_db
from core import config
from core.jwt import ALGORITHM
from dto.token import TokenPayload
from model.user import User
from service import user as user_service

reusable_oauth2 = OAuth2PasswordBearer(tokenUrl="/dev/login/access-token")


def get_current_user(
        db: Session = Depends(get_db), token: str = Security(reusable_oauth2)
):
    try:
        payload = jwt.decode(token, config.SECRET_KEY, algorithms=[ALGORITHM])
        token_data = TokenPayload(**payload)
    except PyJWTError:
        raise HTTPException(
            status_code=401, detail="Could not validate credentials"
        )
    user = user_service.get(db, user_id=token_data.user_id)
    if not user:
        raise HTTPException(status_code=401, detail="User not found")
    return user
Example #29
0
from typing import Optional
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from app.core.config import SECRET_KEY, API_PREFIX
from app.models.user import UserInDB
from app.api.dependencies.database import get_repository
from app.db.repositories.users import UsersRepository
from app.services import auth_service

oauth2_scheme = OAuth2PasswordBearer(
    tokenUrl=f"{API_PREFIX}/users/login/token/")


async def get_user_from_token(
    *,
    token: str = Depends(oauth2_scheme),
    user_repo: UsersRepository = Depends(get_repository(UsersRepository)),
) -> Optional[UserInDB]:
    try:
        username = auth_service.get_username_from_token(
            token=token, secret_key=str(SECRET_KEY))
        user = await user_repo.get_user_by_username(username=username)
    except Exception as e:
        raise e
    return user


def get_current_active_user(current_user: UserInDB = Depends(
    get_user_from_token)) -> Optional[UserInDB]:
    if not current_user:
        raise HTTPException(
Example #30
0
import jwt
from jwt import PyJWTError
from passlib.context import CryptContext
from sqlalchemy.orm import Session
from modules.database import SessionLocal
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from pydantic import BaseModel
from datetime import timedelta, datetime

router = APIRouter()
# import onedrivesdk
# from onedrivesdk.helpers import GetAuthCodeServer

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

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/admin/token")

SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 100


def get_db():
    db = SessionLocal()
    try:
        yield db

    finally:
        db.close()