Esempio n. 1
0
    :param token_api_key_header API key provided by Authorization[api_key] header
    
    
    :type token_api_key_header: str
    :return: Information attached to provided api_key or None if api_key is invalid or does not allow access to called API
    :rtype: TokenModel | None
    """

    ...

oauth2_implicit = OAuth2(
    flows=OAuthFlows(
        implicit=OAuthFlowImplicit(
            authorizationUrl="http://petstore.swagger.io/api/oauth/dialog",
            scopes={
                "write:pets": "modify pets in your account",
                "read:pets": "read your pets",
            }
        )
    )
)


def get_token_petstore_auth(
    security_scopes: SecurityScopes, token: str = Depends(oauth2_implicit)
) -> TokenModel:
    """
    Validate and decode token.

    :param token Token provided by Authorization header
    :type token: str
from typing import Optional

import pytest
from fastapi import Depends, FastAPI, Security
from fastapi.security import OAuth2, OAuth2PasswordRequestFormStrict
from fastapi.testclient import TestClient
from pydantic import BaseModel

app = FastAPI()

reusable_oauth2 = OAuth2(
    flows={
        "password": {
            "tokenUrl": "token",
            "scopes": {
                "read:users": "Read the users",
                "write:users": "Create users"
            },
        }
    },
    auto_error=False,
)


class User(BaseModel):
    username: str


def get_current_user(oauth_header: Optional[str] = Security(reusable_oauth2)):
    if oauth_header is None:
        return None
    user = User(username=oauth_header)
from fastapi.security import OAuth2
from fastapi.security.utils import get_authorization_scheme_param
from jose import jwt
from jsonschema import ValidationError
from model.model.common.user import User
from starlette import status

from watchmen.auth.storage.user import load_user_by_name
from watchmen.common.security.index import validate_jwt
from watchmen.common.security.pat.pat_model import PersonAccessToken
from watchmen.common.security.pat.pat_service import verifyPAT
from watchmen_boot.config.config import settings

tokenUrl = f"{settings.API_V1_STR}/login/access-token"
flows = OAuthFlowsModel(password={"tokenUrl": tokenUrl, "scopes": {}})
reusable_oauth2 = OAuth2(flows=flows)


def get_current_user(authorization=Depends(reusable_oauth2)) -> User:
    scheme, token = get_authorization_scheme_param(authorization)
    username = get_username(scheme, token)

    user = load_user_by_name(username)

    if settings.DEFAULT_DATA_ZONE_ON:
        user.tenantId = "1"

    if not user:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
                            detail="User not found")
Esempio n. 4
0

@app.get("/header_under")
def get_header(head_name=Header(None, convert_underscores=False)):
    return head_name


@app.get("/security")
def get_security(sec=Security(HTTPBasic())):
    return sec


reusable_oauth2 = OAuth2(
    flows={
        "password": {
            "tokenUrl": "/token",
            "scopes": {"read:user": "******", "write:user": "******"},
        }
    }
)


@app.get("/security/oauth2")
def get_security_oauth2(sec=Security(reusable_oauth2, scopes=["read:user"])):
    return sec


reusable_oauth2b = OAuth2PasswordBearer(tokenUrl="/token")


class User(BaseModel):
    username: str
Esempio n. 5
0
import jwt
from fastapi.security import OAuth2PasswordBearer, OAuth2
from passlib.context import CryptContext
from datetime import datetime, timedelta

oauth2_scheme = OAuth2(
    flows={
        "password": {
            "tokenUrl": "token",
            "scopes": {
                "read:users": "Read the users",
                "write:users": "Create users"
            },
        }
    })

# oauth2_scheme = OAuth2PasswordBearer(tokenUrl="")

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

SECRET_KEY = "123"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30


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


def verify_password(plain_password: str, hashed_password: str) -> bool:
    return pwd_context.verify(plain_password, hashed_password)
Esempio n. 6
0
            *,
            auto_error: Optional[bool] = True
    ):
        self.model = HTTPBase(scheme='signature')
        self.scheme_name = self.__class__.__name__
        self.auto_error = auto_error

    async def __call__(self, request: Request) -> Optional[str]:
        signature_header: str = request.headers.get("Signature")
        if not signature_header:
            raise InvalidAuthentication
        return signature_header


signature_scheme = Signature()
oauth2_scheme = OAuth2()


class UnauthenticatedProofOfPossession(SecurityBase):
    def __init__(self, allowed_issuers: list, allowed_scopes: list, allowed_aud: list, require_signed_headers: list = ['Date']):
        self.allowed_issuers = allowed_issuers
        self.allowed_scopes = allowed_scopes
        self.allowed_aud = allowed_aud
        self.require_signed_headers = require_signed_headers
        self.model = HTTPBase(scheme='pop')
        self.scheme_name = self.__class__.__name__
        self.auto_error = True

    async def __call__(
            self, request: Request, access_token: str = Depends(oauth2_scheme),
            signature_header: str = Depends(signature_scheme)
from typing import Optional

import pytest
from fastapi import Depends, FastAPI, Security
from fastapi.security import OAuth2, OAuth2PasswordRequestFormStrict
from fastapi.testclient import TestClient
from pydantic import BaseModel

app = FastAPI()

reusable_oauth2 = OAuth2(
    flows={
        "password": {
            "tokenUrl": "token",
            "scopes": {"read:users": "Read the users", "write:users": "Create users"},
        }
    },
    description="OAuth2 security scheme",
    auto_error=False,
)


class User(BaseModel):
    username: str


def get_current_user(oauth_header: Optional[str] = Security(reusable_oauth2)):
    if oauth_header is None:
        return None
    user = User(username=oauth_header)
    return user
 def __init__(self, scopes: List[str], client_id: str):
     self.scopes = scopes
     self.oauth2_scheme: OAuth2 = OAuth2(flows=OAuthFlows(
         implicit=OAuthFlowImplicit(authorizationUrl=url +
                                    f'?client_id={client_id}',
                                    scopes=self.scopes)))
Esempio n. 9
0
from fastapi.security import OAuth2
from google.auth import jwt
from google.auth.transport.requests import Request
from google.oauth2 import id_token
from pydantic import ValidationError
from starlette.status import HTTP_400_BAD_REQUEST, HTTP_403_FORBIDDEN

from excars import config, repositories
from excars.api.utils.redis import get_redis_cli
from excars.models.token import TokenPayload
from excars.models.user import User

oauth2 = OAuth2(  # pylint: disable=invalid-name
    flows=OAuthFlows(
        authorizationCode=OAuthFlowAuthorizationCode(
            authorizationUrl="https://accounts.google.com/o/oauth2/v2/auth?scope=openid+email+profile",
            tokenUrl="https://oauth2.googleapis.com/token",
        )
    )
)


async def get_current_user(token: str = Security(oauth2), redis_cli: Redis = Depends(get_redis_cli)) -> User:
    try:
        payload = verify_id_token(token.rpartition(" ")[-1])
    except ValueError as exc:
        raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail=str(exc)) from exc

    if payload["iss"] not in ["accounts.google.com", "https://accounts.google.com"]:
        raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="Wrong issuer.")

    try:
Esempio n. 10
0
from fastapi import Depends
from fastapi.openapi.models import OAuthFlows, OAuthFlowAuthorizationCode
from fastapi.security import OAuth2

from app.config import settings
from app.helpers.oauth2 import Oauth2Client

oauth2_scheme = OAuth2(
    flows=OAuthFlows(
        authorizationCode=OAuthFlowAuthorizationCode(
            authorizationUrl=settings.AUTHORIZATION_URL,
            tokenUrl=settings.AUTHORIZATION_TOKEN_URL,
            scopes={
                'openid': 'OpenID',
                'email': 'Email',
                'profile': 'Profile',
                'groups': 'Groups',
                'offline_access': 'Offline Access',
            }
        ),
    )
)


def get_current_user(access_token: str = Depends(oauth2_scheme)):
    """
    Return the current user profile
    :return: current user
    """
    oauth2 = Oauth2Client()
    user = oauth2.user_profile(access_token)
Esempio n. 11
0
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:
    return pwd_context.hash(plain_password)