Exemplo n.º 1
0
async def delete_user_form(request: Request,
                           user: User = Depends(get_current_active_user)):
    vm = VMBase(request, user=user)
    if user.deletion_protection:
        return templates.TemplateResponse(
            "dashboard/account_deletion_protection_warning.html",
            vm.to_dict(),
            headers={"HX-Trigger-After-Settle": "openModal"},
        )
    return templates.TemplateResponse(
        "dashboard/account_delete.html",
        vm.to_dict(),
        headers={"HX-Trigger-After-Settle": "openModal"},
    )
Exemplo n.º 2
0
async def get_user_assort_price(
    trader_id: str,
    profile: Profile = Depends(with_profile_readonly),
    trader_manager: TraderManager = Depends(
        Provide[AppContainer.trader.manager]),
) -> Union[TarkovSuccessResponse[Dict[ItemId, List[List[dict]]]],
           TarkovErrorResponse]:
    trader = trader_manager.get_trader(TraderType(trader_id))
    items = {}

    for item in profile.inventory.items.values():
        if item.parent_id != profile.inventory.root_id:
            continue
        if not trader.can_sell(item):
            continue

        children_items = profile.inventory.iter_item_children_recursively(item)
        price = trader.get_sell_price(item, children_items=children_items)
        items[item.id] = [[{"_tpl": price.template_id, "count": price.amount}]]

    # TODO: Calculate price for items to sell in specified trader
    # output is { "item._id": [[{ "_tpl": "", "count": 0 }]] }
    return TarkovSuccessResponse(data=items)
Exemplo n.º 3
0
async def get_rating_correlation(account: Account = Depends(auth_account)):
    import pymysql
    c = pymysql.connect(host=DATABASE_URL.hostname,
                        user=DATABASE_URL.username,
                        password=DATABASE_URL.password,
                        database=DATABASE_URL.database)
    cur = c.cursor()
    cur.execute('CALL compute_correlation(%s)', account.id)
    rows = cur.fetchall()
    cur.close()
    return [
        Correlation(attrID=attr_id, correlation=correlation)
        for attr_id, correlation in rows if correlation is not None
    ]
Exemplo n.º 4
0
def create_book(request: schemas.Book, db: Session = Depends(get_db)):
    if (validate(request.startDate)):
        datetime_obj = datetime.strptime(request.startDate, '%d/%m/%y')
        new_book = models.Book(title=request.title,
                               readIntent=request.readIntent,
                               startDate=datetime_obj)
        db.add(new_book)
        db.commit()
        db.refresh(new_book)
        return new_book
    else:
        raise HTTPException(
            status_code=status.HTTP_406_NOT_ACCEPTABLE,
            detail=f"wrong format of startDate : {request.startDate}")
Exemplo n.º 5
0
def summary_get(batch: int, dept: str, sem: int,
                db: Session = Depends(get_db)):
    if not is_batch_exists(db, batch):
        raise BatchDoesNotExist

    if not is_dept_exist(db, dept):
        raise DeptDoesNotExist

    if not is_scores_exist(db, batch, sem, dept):
        raise NoResultFoundForQuery

    res = get_summary(db, batch, dept, sem)

    return res
Exemplo n.º 6
0
def create_file(*,
                file: UploadFile = File(...),
                db_session: Session = Depends(get_db)):
    """
    upload a new file.
    """
    meta_in = MetaCreate()
    meta_in.file_name, meta_in.content_type = file.filename, file.content_type
    meta_read = create(db_session=db_session, meta_in=meta_in)
    if meta_read.id > 0:
        with open(os.path.join(UPLOAD_FOLDER, 'temp', str(meta_read.id)),
                  "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)
    return meta_read
Exemplo n.º 7
0
def run_migration(migration_id, repos: RepoProvider = Depends(repos_provider)):
    """ Run the migration process in foreground

    :param repos: RepoProvider
    :param migration_id: Migration id
    :return: String message
    """
    repo = repos.migration_repo
    manager = MigrationManager(repo)
    coro = asyncio.ensure_future(manager.start_migration_async(migration_id),
                                 loop=loop)
    loop.run_until_complete(coro)

    return f"The migration {migration_id} started successfully"
Exemplo n.º 8
0
def login_access_token(form_data: LoginRequestForm = Depends()):
    user = UserService().authenticate(email=form_data.username,
                                      password=form_data.password)
    if not user:
        raise HTTPException(status_code=400,
                            detail='Incorrect email or password')
    elif not user.is_active:
        raise HTTPException(status_code=401, detail='Inactive user')

    user.last_login = datetime.now()
    db.session.commit()

    return DataResponse().success_response(
        {'access_token': create_access_token(user_id=user.id)})
Exemplo n.º 9
0
def delete_subscribe(subscribers: List[Subscriber],
                     DB: Session = Depends(get_db)):
    try:
        logger.info('Delete Subscriptions method start')
        if delete_subscribers(DB, subscribers):
            logger.info('Delete Subscriptions method successfully ends')
            return {'isError': False}
        else:
            logger.info('Delete Subscriptions method unsuccessfully ends')
            return {'isError': True, 'message': 'Cannot be deleted'}
    except Exception as ex:
        logger.info('Delete Subscriptions method error:')
        logger.info(ex)
        return {'isError': True, 'message': ex}
Exemplo n.º 10
0
 def push(body=Depends(get_body)):
     try:
         request = PushFeaturesRequest(**json.loads(body))
         df = pd.DataFrame(request.df)
         store.push(
             push_source_name=request.push_source_name,
             df=df,
             allow_registry_cache=request.allow_registry_cache,
         )
     except Exception as e:
         # Print the original exception on the server side
         logger.exception(traceback.format_exc())
         # Raise HTTPException to return the error message to the client
         raise HTTPException(status_code=500, detail=str(e))
Exemplo n.º 11
0
async def get_task_outputs(
        kernel_events: bool = True,
        window_enumeration: bool = True,
        db: AsyncIOMotorDatabase = Depends(get_db_instance),
):
    projection = {"_id": 1, "same_as": 1}

    print(window_enumeration)
    if window_enumeration:
        projection["window_enumeration"] = 1
    if kernel_events:
        projection["kernel_events"] = 1

    tasks = await db.output.find({}, projection).to_list(length=None)
    return tasks
Exemplo n.º 12
0
def create_page(page: Page, sess: Session = Depends(create_session)):
    if page.user_id is None or page.config_id is None:
        raise HTTPException(400, "user or config id is not given")
    user = sess.query(UserORM).filter(UserORM.id == page.user_id).scalar()
    if not user:
        raise HTTPException(400, f"user id ({page.user_id}) does not exist")
    config = sess.query(WebsiteConfigORM).filter(
        WebsiteConfigORM.id == page.config_id).scalar()
    if not config:
        raise HTTPException(400,
                            f"config id ({page.config_id}) does not exist")
    pageOrm = PageORM(**page.dict(exclude_none=True, exclude_unset=True))
    sess.add(pageOrm)
    sess.flush([pageOrm])
    return Page.from_orm(pageOrm)
Exemplo n.º 13
0
async def update_migration(migration_id,
                           bind: MigrationBind,
                           repos: RepoProvider = Depends(repos_provider)):
    """ Modify the migration model

    :param migration_id: Migration id
    :param bind: New migration configuration
    :param repos: RepoProvider
    :return: Migration model
    """
    migration_repo = repos.migration_repo

    updated_migration = await migration_repo.update_async(migration_id, bind)

    return updated_migration
Exemplo n.º 14
0
def acapy_auth(auth: str = Depends(x_api_key_scheme)):
    if not "." in auth:
        raise HTTPException(401, "Unauthorized")

    try:
        [role_str, token] = auth.split(".", maxsplit=1)

        role = Role.from_str(role_str)
    except:
        raise HTTPException(401, "Unauthorized")

    if not role:
        raise HTTPException(401, "Unauthorized")

    return AcaPyAuth(role=role, token=token)
Exemplo n.º 15
0
async def settings_get(
        request: Request,
        api: api_.API = Depends(get_api),
        db: database.Database = Depends(get_db),
        scheduler: scheduler.Scheduler = Depends(get_scheduler),
):
    schedules = [{
        "schedule":
        str(schedule),
        "next_feeding":
        f"{next_feeding:%Y-%m-%d %H:%M}" if next_feeding else "",
        "id":
        schedule.id,
    } for schedule, next_feeding in api.list_schedules_with_runtimes(
        db, scheduler)]

    return templates.TemplateResponse(
        "settings.html",
        context={
            "request": request,
            "feed_angle": db.get_feed_angle(),
            "schedules": schedules,
        },
    )
async def register_schema(
    schema_id: SchemaID, db: Session = Depends(get_db)) -> Schema:
    schema_attrs_list = _get_schema_attrs(schema_id)
    create_schema_res = crud.create_schema(
        db,
        schema=Schema(
            did=schema_attrs_list[0],
            name=schema_attrs_list[2],
            version=schema_attrs_list[3],
            id=schema_id.schema_id,
        ),
    )
    if create_schema_res == 1:
        raise HTTPException(status_code=405, detail="Schema already exists")
    return create_schema_res
Exemplo n.º 17
0
async def post_reject(item_id: int, db: Session = Depends(get_db)):
    """
    Rejeita um contrato por id
    """
    contract: Contract = db.query(Contract).get(item_id)
    if contract is None:
        raise HTTPException(HTTPStatus.NOT_FOUND)

    if contract.status != ContractStatus.IMAGES_UPLOADED:
        raise HTTPException(HTTPStatus.BAD_REQUEST)

    contract.status = ContractStatus.REJECTED
    db.add(contract)
    db.commit()
    return contract
Exemplo n.º 18
0
def pincode_subscribe(subscribers: List[SubscriberPincodeModel],
                      DB: Session = Depends(get_db)):
    dbSubs = []
    try:
        logger.info('Pincode Subscribe method start')
        for sub in subscribers:
            dbSubs.append(DBSubscriber(**sub.dict(), active=True))
        isSuccess = insert_pincode_subscribers(DB, dbSubs)
        logKeyword = f'{"Uns" if not isSuccess else "S"}uccessfully'
        logger.info(f'Pincode Subscribe method {logKeyword} ends')
        return {'isSubscriptionSuccess': isSuccess}
    except Exception as ex:
        logger.info('Pincode Subscribe method error:')
        logger.info(ex)
        return {'isSubscriptionSuccess': False, 'message': ex}
Exemplo n.º 19
0
def client_profile_status(
    profile: Profile = Depends(profile_manager.with_profile),
) -> Union[TarkovSuccessResponse[List[dict]], TarkovErrorResponse]:
    response = []
    for profile_type in ("scav", "pmc"):
        response.append({
            "profileid": f"{profile_type}{profile.profile_id}",
            "status": "Free",
            "sid": "",
            "ip": "",
            "port": 0,
        })
    print(response)

    return TarkovSuccessResponse(data=response)
Exemplo n.º 20
0
async def websocket_endpoint(
    websocket: WebSocket, client_id: int,
    token: Any = Depends(get_token)) -> None:
    if token is None:
        return
    await manager.connect(websocket)

    try:
        while True:
            data = await websocket.receive_json()
            print(data)
            asyncio.create_task(manager.eventHandle(websocket, data))

    except WebSocketDisconnect:
        manager.disconnect(websocket)
Exemplo n.º 21
0
async def join(
    request: Request,
    profile: Profile = Depends(profile_manager.with_profile),
) -> Union[TarkovSuccessResponse[list], TarkovErrorResponse]:
    request_data: dict = await request.json()
    return TarkovSuccessResponse(data=[{
        "profileid": profile.pmc.id,
        "status": "busy",
        "sid": "",
        "ip": "127.0.0.1",
        "port": 9909,
        "version": "live",
        "location``": request_data["location"],
        "gamemode": "deathmatch",
        "shortid": "TEST",
    }])
Exemplo n.º 22
0
async def client_game_profile_list(
    profile_id: str = Cookie(..., alias="PHPSESSID"),
    profile_manager: ProfileManager = Depends(Provide[AppContainer.profile.manager]),
) -> Union[TarkovSuccessResponse[List[dict]], TarkovErrorResponse]:
    try:
        async with profile_manager.locks[profile_id]:
            profile = profile_manager.get_profile(profile_id)
            return TarkovSuccessResponse(
                data=[
                    profile.pmc.dict(exclude_none=True),
                    profile.scav.dict(exclude_none=True),
                ]
            )
    except Profile.ProfileDoesNotExistsError as error:
        logger.exception(error)
        return TarkovSuccessResponse(data=[])
Exemplo n.º 23
0
async def get_bills_for_user_family(
    user_id: int, state: State = Depends(get_state)) -> List[Bill]:
    # vrne seznam userjev, ki so druzina od userja z id=user_id
    bills = []
    fam = []
    for user in state.users:
        if user.id == user_id:
            main_user = user
    for u2 in state.users:
        if main_user and u2.id in main_user.family:
            fam.append(u2)
    for bill in state.bills:
        if bill.date_payment == "" and bill.id_payer in main_user.family:
            if bill.visible_family:
                bills.append(bill)
    return bills
Exemplo n.º 24
0
async def generate_bots(
    request: Request,
    bot_generator: BotGenerator = Depends(Provide[BotContainer.bot_generator]),
) -> TarkovSuccessResponse[List[dict]]:
    bots: List[dict] = []
    request_data: dict = await request.json()

    logger.debug(request_data)
    for condition in request_data["conditions"]:
        bot_limit = condition["Limit"]

        for _ in range(bot_limit):
            bot = bot_generator.generate(bot_role="assault")
            bots.append(bot)

    return TarkovSuccessResponse(data=bots)
Exemplo n.º 25
0
async def get_task_output(task_id: str,
                          db: AsyncIOMotorDatabase = Depends(get_db_instance)):
    # Check whether this task is valid
    response = await db.input.find_one({"_id": ObjectId(task_id)})

    if response is None:
        raise HTTPException(status_code=404, detail="Task does not exist.")

    response = await db.output.find_one({"_id": ObjectId(task_id)}, {"_id": 0})

    # Return no content if the task exists but has no output
    if response is None:
        raise HTTPException(status_code=202,
                            detail="Task exists but has not finished.")

    return response
Exemplo n.º 26
0
Arquivo: users.py Projeto: hill/UEM2
def create_user(*, session: Session = Depends(get_session), user: UserCreate):

    # create the stripe customer
    customer = stripe.Customer.create(email=user.email, name=user.name)

    db_user = User.from_orm(
        user,
        {
            "password_hash": security.get_password_hash(user.password),
            "stripe_customer_id": customer["id"],
        },
    )
    session.add(db_user)
    session.commit()
    session.refresh(db_user)
    return db_user
Exemplo n.º 27
0
async def get_statistics_dict(user_id: int, state: State = Depends(get_state)):
    stat1 = get_stat_value_for_month(user_id)
    stat2 = get_stat_value_for_week(user_id)
    stat3 = get_stat_credits(user_id)
    stat4 = get_stat_donations(user_id)
    stat5 = get_stat_transactions(user_id)
    stat6 = get_stat_byCategory(user_id)
    stat7 = get_stat_byCategory_num(user_id)
    return {
        "for_month": stat1,
        "for_week": stat2,
        "credits": stat3,
        "donations": stat4,
        "transactions": stat5,
        "cake1": stat6,
        "cake2": stat7
    }
Exemplo n.º 28
0
 def _access_token(
     security_scopes: SecurityScopes,
     token: Tuple[bool, Union[dict, HTTPException]] = Depends(oidc_scheme),
 ) -> Optional[dict]:
     success, payload = token
     if not success:
         if raise_on_error:
             raise payload
         else:
             return None
     if set(security_scopes.scopes) - current_scopes(payload):
         error = HTTPException(status_code=status.HTTP_404_NOT_FOUND)
         if raise_on_error:
             raise error
         else:
             return None
     return payload
Exemplo n.º 29
0
async def task_error(
        task_id: str,
        request: models.ErrorMessage,
        db: AsyncIOMotorDatabase = Depends(get_db_instance),
):
    """Process a error message from a VM."""

    await db.error.insert_one({
        "time":
        int(datetime.datetime.now(tz=datetime.timezone.utc).timestamp()),
        "task_id":
        task_id,
        "stack_trace":
        request.stack_trace.strip(),
    })
    await update_task_status(db, ObjectId(task_id), "failed")
    return {}
Exemplo n.º 30
0
def register_account(
    email: str = Body(..., embed=True),
    password: str = Body(..., embed=True),
    edition: str = Body(..., embed=True),
    account_service: AccountService = Depends(
        Provide[AppContainer.launcher.account_service]),
) -> PlainTextResponse:
    try:
        account_service.find(email=email, password=password)
        return PlainTextResponse(
            content=zlib.compress("FAILED".encode("utf8")))
    except NotFoundError:
        account_service.create_account(
            email=email,
            password=password,
            edition=edition,
        )
        return PlainTextResponse(content=zlib.compress("OK".encode("utf8")))