Beispiel #1
0
def login(
        *,
        db: Session = Depends(deps.get_db),
        form_data: OAuth2PasswordRequestForm = Depends(OAuth2PasswordRequestForm)
) -> dict:
    """
        用户JWT登录
        :param db:
        :param user_info:
        :return:
    """
    user = crud_user.CRUDUser.authenticate(
        db=db,
        user_name=form_data.username,
        password=form_data.password
    )
    if not user:
        return {
                "return_code": -1,
                "return_msg": "认证失败"
        }

    access_token_expires = timedelta(minutes=setting.ACCESS_TOKEN_EXPIRE_MINUTES)
    return {
        "return_code": 0,
        "return_msg": "OK",
        "uid": user.uid,
        "access_token": security.create_access_token(
            user.uid, expires_delta=access_token_expires
        ),
        "token_type": "bearer",
    }
class OverhaveLdapClientSettings(BaseOverhavePrefix):
    """ Settings for Overhave LDAP client for AuthorizationStrategy.LDAP strategy. """

    ldap_url: str  # for example: "ldap://mydomain.ru"
    ldap_domain: str  # for example: "domain\\"
    ldap_dn: str  # for example: "dc=example,dc=com"
    ldap_timeout: timedelta = timedelta(seconds=10)
def createAccessToken(data: dict, expires_delta: Optional[timedelta] = None):
    try:
        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
    except Exception as e:
        print(e)
        raise HTTPException(status_code=400,
                            detail={"message": "Unexpected Error Occured"})
class OverhaveRedisSettings(BaseOverhavePrefix):
    """ Settings for Redis entities, which use for work with different framework tasks. """

    redis_url: URL = URL("redis://*****:*****@validator("redis_url", pre=True)
    def validate_url(cls, v: Union[str, URL]) -> URL:
        if isinstance(v, str):
            return URL(v)
        return v

    @property
    def timeout_milliseconds(self) -> int:
        return int(self.redis_block_timeout.total_seconds() * 1000)
Beispiel #5
0
class BaseChallengeInfo(BaseModel):
    name: str
    description: str
    picture: Optional[PictureModel]

    max_winners: conint(ge=1) = 1  # type: ignore
    duration: timedelta = timedelta(days=1)

    type: ChallengeType

    @validator('picture')
    def validate_picture(cls,
                         v: Optional[PictureModel]) -> Optional[PictureModel]:
        if isinstance(v, PictureModel):
            path = get_path_settings().root_dir / v.file
            if not path.exists():
                raise PictureNotExistError(
                    f"Specified picture '{v}' does not exist with path '{path}'!"
                )
            v.file = path
        return v
def validateUser(userObj: UserModel):
    if not userObj:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail={"message": "Invalid credentials"},
            headers={"WWW-Authenticate": "Bearer"},
        )
    else:
        try:
            access_token_expires = timedelta(
                minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
            access_token = createAccessToken(
                data={"sub": userObj.userName},
                expires_delta=access_token_expires)

            headers = {
                "access_token": access_token,
                "token_type": "bearer",
            }
            return JSONResponse(status_code=200, content=headers)
        except Exception as e:
            print(e)
            raise HTTPException(status_code=400,
                                detail={"message": "Login Failed"})
class OverhaveEmulationSettings(BaseOverhavePrefix):
    """ Settings for Overhave Emulator, which emulates session with test user. """

    # Path for emulation core application, such as GoTTY
    emulation_core_path: str = "/gotty"

    # All emulation core application prefixes for execution
    emulation_prefix: str = "--permit-write --once --address {address} --port {port} --timeout {timeout}"

    # Specific terminal tool startup command with relative `feature_type`, for example: `myapp {feature_type}`
    emulation_base_cmd: Optional[str]
    # Terminal tool command postfix with specified user `name` and `model`, for example: `--name={name} --model={model}`
    # If it is no need in use - may be optional.
    emulation_postfix: Optional[str]

    # Optional additional terminal tool usage description
    emulation_desc_link: Optional[str]

    emulation_bind_ip: str = "0.0.0.0"  # noqa: S104
    # Ports for emulation binding. Expects as string with format `["port1", "port2", ...]`
    emulation_ports: List[int] = [8080]

    # As a real service, should be used follow path: `http://my-service.domain/mount`
    # where `emulation_service_url` = `http://my-service.domain` - URL for service,
    # and `emulation_service_mount` = `mount` - mount point for service redirection.
    # If `emulation_service_mount` is `None` - this is localhost debug.
    emulation_service_url: URL = URL("http://localhost")
    emulation_service_mount: Optional[str]

    # Wait until emulation become served
    emulation_wait_timeout: timedelta = timedelta(seconds=300)

    @validator("emulation_service_url", pre=True)
    def validate_url(cls, v: Union[str, URL]) -> URL:
        if isinstance(v, str):
            return URL(v)
        return v

    @validator("emulation_ports", pre=True)
    def validate_ports(cls, v: Union[List[int], str]) -> List[int]:
        if isinstance(v, str):
            return [int(x.strip()) for x in v.split(",")]
        return v

    def get_emulation_url(self, port: str) -> str:
        if isinstance(self.emulation_service_mount, str):
            return (
                self.emulation_service_url / self.emulation_service_mount /
                port / ""
            ).human_repr(
            )  # NGINX should redirect to `service:port` by mount point and specified port
        return self.emulation_service_url.with_port(
            int(port)).human_repr()  # only for local debug

    @property
    def wait_timeout_seconds(self) -> int:
        return int(self.emulation_wait_timeout.total_seconds())

    @property
    def enabled(self) -> bool:
        return isinstance(self.emulation_base_cmd, str)