Beispiel #1
0
async def post_state(
        request: Request,
        x_lightning_type: Optional[str] = Header(None),
        x_lightning_session_uuid: Optional[str] = Header(None),
        x_lightning_session_id: Optional[str] = Header(None),
) -> Mapping:
    if x_lightning_session_uuid is None:
        raise Exception("Missing X-Lightning-Session-UUID header")
    if x_lightning_session_id is None:
        raise Exception("Missing X-Lightning-Session-ID header")
    # This needs to be sent so that it can be set as last state
    # in app (see sequencing above)
    # Actually: we need to make sure last_state is actually
    # the latest state seen by the UI, that is, the last state
    # ui to the UI from the API, not the last state
    # obtained by the app.
    body: Dict = await request.json()
    x_lightning_session_uuid = TEST_SESSION_UUID

    if "stage" in body:
        last_state = global_app_state_store.get_served_state(
            x_lightning_session_uuid)
        state = deepcopy(last_state)
        state["app_state"]["stage"] = body["stage"]
        deep_diff = DeepDiff(last_state, state)
    else:
        state = body["state"]
        last_state = global_app_state_store.get_served_state(
            x_lightning_session_uuid)
        deep_diff = DeepDiff(last_state, state)
    update_delta = Delta(deep_diff)
    api_app_delta_queue.put(update_delta)
Beispiel #2
0
async def get_spec(
        x_lightning_session_uuid: Optional[str] = Header(None),
        x_lightning_session_id: Optional[str] = Header(None),
) -> List:
    if x_lightning_session_uuid is None:
        raise Exception("Missing X-Lightning-Session-UUID header")
    if x_lightning_session_id is None:
        raise Exception("Missing X-Lightning-Session-ID header")
    global app_spec
    return app_spec or []
Beispiel #3
0
async def get_picture_meta(
        picture_id: str,
        if_none_match: str = Header(None),
        if_match: str = Header(None),
):
    """Get picture metadata."""
    try:
        stream, headers = await _async_get_picture(picture_id, if_none_match,
                                                   if_match)
        stream.close()
    except HTTPException as e:
        return Response(status_code=e.status_code)
    return Response(status_code=200, headers=headers)
Beispiel #4
0
async def get_state(
        x_lightning_type: Optional[str] = Header(None),
        x_lightning_session_uuid: Optional[str] = Header(None),
        x_lightning_session_id: Optional[str] = Header(None),
) -> Mapping:
    if x_lightning_session_uuid is None:
        raise Exception("Missing X-Lightning-Session-UUID header")
    if x_lightning_session_id is None:
        raise Exception("Missing X-Lightning-Session-ID header")

    with lock:
        x_lightning_session_uuid = TEST_SESSION_UUID
        state = global_app_state_store.get_app_state(x_lightning_session_uuid)
        global_app_state_store.set_served_state(x_lightning_session_uuid,
                                                state)
        return state
Beispiel #5
0
def get_device_data(tablename: TableName,
                    connection_string: str = Header(...)):

    with zk_device(connection_string) as zk:
        data = zk.get_data(tablename)

    return data
Beispiel #6
0
async def get_register_user(
        token: str = Header(..., alias="x-token"), ) -> UserViewData:
    """Gets user data for registration."""
    check_token(token)
    user_data = DotDict.from_obj(await async_user_collection.find_one({
        'registration_token':
        token,
    }))
    if user_data is None:
        raise HTTPException(401, "Invalid token")
    user_data['sub'] = user_data['_id']
    if user_data.get('picture') is not None:
        user_data[
            'picture'] = f"{config.oauth2.base_url}/picture/{user_data['picture']}"
    if 'password' in user_data:
        del user_data['password']
    # User will be active afterwards, send active
    user_data['active'] = True
    return UserViewData(
        user_id=user_data['_id'],
        properties=[
            UserPropertyWithValue(key=prop,
                                  value=_get_user_property_value(
                                      prop,
                                      user_data,
                                      is_self=True,
                                      is_registering=True),
                                  **config.oauth2.user.properties[prop].dict())
            for prop in config.manager.registration
            if config.oauth2.user.properties[prop].can_read.has_access(
                is_self=True) or config.oauth2.user.properties[prop].can_edit.
            has_access(is_self=True)
        ])
Beispiel #7
0
def set_device_data(data: List[Mapping[str, Any]],
                    tablename: TableName,
                    connection_string: str = Header(...)):
    with zk_device(connection_string) as zk:
        zk.set_data(tablename, data)

    return {"status": "success", "message": "data updated successfully"}
Beispiel #8
0
def set_device_param(updated_params: Mapping[DeviceParametersEnum, Any],
                     connection_string: str = Header(...)):
    with zk_device(connection_string) as zk:
        for k, v in updated_params.items():
            zk.parameters.__setattr__(k, v)

    return {"status": "success", "message": "parameter updated successfully"}
Beispiel #9
0
async def reset_password(
        token: str = Header(..., alias="x-token"),
        password_data: PasswordInWrite = Body(...),
):
    check_token(token)
    user_data = await async_user_collection.find_one(
        {'password_reset_token': token})
    if user_data is None:
        raise HTTPException(401, "Invalid token")
    new_hash = create_password(password_data.password)
    updated_at = int(time.time())
    await async_user_collection.update_one({'_id': user_data['_id']}, {
        '$set': {
            'password': new_hash,
            'updated_at': updated_at,
        },
        '$unset': {
            'password_reset_token': ''
        },
    })
    await async_client_user_cache_collection.update_many(
        {'user_id': user_data['_id']},
        {'$set': {
            'last_modified': updated_at
        }},
    )
Beispiel #10
0
async def upload_picture(
        user_id: str,
        file: UploadFile = File(..., media_type='application/octet-stream'),
        user: UserInfo = Depends(Authentication(auto_error=False)),
        registration_token: Optional[str] = Header(None, alias="x-token"),
):
    """Uploads a new picture for the passed user."""
    if user is not None:
        is_admin = 'admin' in user['roles']
        is_self = user.sub == user_id
        if not is_self or not is_admin:
            raise HTTPException(401)
        user_data = await async_user_collection.find_one({'_id': user_id})
    elif registration_token is not None:
        check_token(registration_token)
        user_data = await async_user_collection.find_one(
            {'registration_token': registration_token})
    else:
        raise HTTPException(401)
    if user_data is None:
        raise HTTPException(404)
    user = User.validate(user_data)
    if user.picture is None:
        user.picture = generate_token(48)
        updated_at = int(time.time())
        await async_user_collection.update_one(
            {'_id': user_id},
            {'$set': {
                'picture': user.picture,
                'updated_at': updated_at
            }})
        await async_client_user_cache_collection.update_many(
            {'user_id': user_data['_id']},
            {'$set': {
                'last_modified': updated_at
            }},
        )
    else:
        try:
            await async_user_picture_bucket.delete(user.picture)
        except gridfs.errors.NoFile:
            pass
    hash_ = hashlib.sha512()
    while True:
        chunk = await file.read(4 * 1024)
        if not chunk:
            break
        hash_.update(chunk)
    await file.seek(0)
    file.file.seek(0)
    await async_user_picture_bucket.upload_from_stream_with_id(
        user.picture,
        user.id,
        file.file,
        metadata={
            'content_type': file.content_type,
            'hash': hash_.digest()
        })
Beispiel #11
0
async def post_delta(
        request: Request,
        x_lightning_type: Optional[str] = Header(None),
        x_lightning_session_uuid: Optional[str] = Header(None),
        x_lightning_session_id: Optional[str] = Header(None),
) -> Mapping:
    """This endpoint is used to make an update to the app state using delta diff, mainly used by streamlit to
    update the state."""

    if x_lightning_session_uuid is None:
        raise Exception("Missing X-Lightning-Session-UUID header")
    if x_lightning_session_id is None:
        raise Exception("Missing X-Lightning-Session-ID header")

    body: Dict = await request.json()
    delta = body["delta"]
    update_delta = Delta(delta)
    api_app_delta_queue.put(update_delta)
Beispiel #12
0
def post_items_all_params(
    item_id: str = Path(...),
    body: Item = Body(...),
    query_a: int = Query(None),
    query_b=Query(None),
    coo: str = Cookie(None),
    x_head: int = Header(None),
    x_under: str = Header(None, convert_underscores=False),
):
    return {
        "item_id": item_id,
        "body": body,
        "query_a": query_a,
        "query_b": query_b,
        "coo": coo,
        "x_head": x_head,
        "x_under": x_under,
    }
Beispiel #13
0
def delete_device_data(data_filter: Mapping[str, Any],
                       tablename: TableName,
                       connection_string: str = Header(...)):
    with zk_device(connection_string) as zk:
        device_data_filter = DeviceDataFilter()
        for k, v in data_filter.items():
            device_data_filter.add_condition(k, v)

        zk.sdk.delete_device_data(tablename, [device_data_filter])
    return {"status": "success", "message": "data deleted successfully"}
Beispiel #14
0
def login_required(authorization: str = Header(None)):
    if not authorization:
        raise HTTPException(401, detail="로그인을 해주세요")

    user = auth_user(authorization)

    if user is None:
        raise HTTPException(401, detail="로그인을 해주세요")

    return user
Beispiel #15
0
async def list_github_repository_info(repository=Header('repository')):
    git = Github(login_or_token=PERSONAL_TOKEN)
    response = git.get_repo(repository)

    return GithubRepositoryInfo(
        repository=response.full_name,
        owner=response.owner.login,
        owner_login=response.owner.login,
        owner_picture=response.owner.avatar_url,
        description=response.description,
    )
Beispiel #16
0
def post_items_all_params_default(
    item_id: str,
    body_item_a: Item,
    body_item_b: Item,
    query_a: int,
    query_b: int,
    coo: str = Cookie(None),
    x_head: int = Header(None),
    x_under: str = Header(None, convert_underscores=False),
):
    return {
        "item_id": item_id,
        "body_item_a": body_item_a,
        "body_item_b": body_item_b,
        "query_a": query_a,
        "query_b": query_b,
        "coo": coo,
        "x_head": x_head,
        "x_under": x_under,
    }
Beispiel #17
0
async def add_process_time_header(request: Request,
                                  call_next,
                                  Authorization: str = Header(None)):
    start_time = time.time()
    print('请求前')
    print(request.headers.get('authorization'))
    # 解析用户
    request.scope['user'] = '******'
    response = await call_next(request)
    print('请求后')
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response
Beispiel #18
0
def auth_user(authorization: str = Header(None)):
    if not authorization:
        return None

    try:
        payload = AuthController.decode_token(authorization)
        user_email = payload.get("sub", None)
    except JWTError:
        return None

    user = UserController().get_user(email=user_email)

    return user
Beispiel #19
0
async def _async_get_picture(
        picture_id: str,
        if_none_match: str = Header(None),
        if_match: str = Header(None),
) -> Tuple[gridfs.GridOut, dict]:
    try:
        stream = await async_user_picture_bucket.open_download_stream(
            picture_id)
    except gridfs.errors.NoFile:
        raise HTTPException(404)
    file_hash = stream.metadata['hash'].hex()
    if if_none_match is not None and file_hash in [
            m.strip() for m in if_none_match.split(',')
    ]:
        stream.close()
        raise HTTPException(304)
    if if_match is not None and file_hash not in [
            m.strip() for m in if_match.split(',')
    ]:
        stream.close()
        raise HTTPException(304)
    return stream, {'ETag': file_hash}
Beispiel #20
0
async def add_process_time_header(
    request: Request, call_next, authorization: str = Header('authorization')):

    start_time = time.time()
    if request.url.path not in ('/test', '/', '/docs', '/favicon.ico',
                                '/openapi.json', '/authorizations/'):
        user = await get_user(request)
        if isinstance(user, JSONResponse):
            return user
        request.scope['user'] = user
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response
Beispiel #21
0
async def get_picture(
        picture_id: str,
        if_none_match: str = Header(None),
        if_match: str = Header(None),
):
    """Get picture data."""
    try:
        stream, headers = await _async_get_picture(picture_id, if_none_match,
                                                   if_match)
    except HTTPException as e:
        return Response(status_code=e.status_code)

    async def stream_iterator():
        while True:
            chunk = await stream.readchunk()
            if not chunk:
                break
            yield chunk
        stream.close()

    return StreamingResponse(stream_iterator(),
                             media_type=stream.metadata['content_type'],
                             headers=headers)
Beispiel #22
0
def delete_all_data(connection_string: str = Header(...)):
    with zk_device(connection_string) as zk:

        for tablename in TableName:
            device_data = zk.sdk.get_device_data(tablename, 1024 * 1024 * 4)

            i: Any
            for i in device_data:
                zk.sdk.delete_device_data(tablename, [i])

    return {
        "status": "success",
        "message": "all device data deleted successfully"
    }
Beispiel #23
0
def auth(body: UserAuthLogin,
         db: Session = Depends(get_db),
         user_agent: Optional[str] = Header(None)):
    """
    User auth method. Creates the token
    \f
    :param body:
    :param db:
    :param user_agent:
    :return:
    """
    return UserAuthActions.login(db,
                                 body.login,
                                 body.password,
                                 meta=user_agent)
Beispiel #24
0
async def webhook_handler(request: Request,
                          sign: str = Header("", alias="x-line-signature")):
    """
    Handle all webhook requests from LINE
    """

    try:
        handler.handle((await request.body()).decode(), sign)
    except InvalidSignatureError:
        err = (f"Invalid Signature, check token and secret\n"
               f"request body:\n"
               f"{(await request.body()).decode()}")
        print(err)
        raise HTTPException(HTTP_200_OK, detail=err)
    else:
        return "OK"
Beispiel #25
0
async def save_register_user(
        token: str = Header(..., alias="x-token"),
        update_data: Dict[str, Any] = Body(...),
):
    """Gets user data for registration."""
    check_token(token)
    user_data = DotDict.from_obj(await async_user_collection.find_one({
        'registration_token':
        token,
    }))
    if user_data is None:
        raise HTTPException(401, "Invalid token")
    del user_data['registration_token']
    await _update_user(user_data,
                       update_data,
                       is_registering=True,
                       is_self=True)
Beispiel #26
0
async def list_github_commit_info(repository=Header('repository')):
    now_date = datetime.datetime.now()
    prev_month = now_date - datetime.timedelta(days=4 * 30)  # 4 months

    git = Github(login_or_token=PERSONAL_TOKEN)
    repository: Repository = git.get_repo(repository)
    commits = repository.get_commits(since=prev_month, until=now_date)

    list_commits = []
    for commit in commits:
        list_commits.append(
            GithubRepositoryCommitInfo(
                author=commit.author.name,
                email=commit.author.email,
                date_commit=commit.commit.last_modified,
                hash_commit=commit.commit.sha,
                description=commit.commit.message,
                owner_picture=commit.author.avatar_url,
            ))

    return list_commits
Beispiel #27
0
async def verify_email(token: str = Header(..., alias="x-token"), ):
    new_email = check_token(token)
    user_data = await async_user_collection.find_one(
        {'email_verification_token': token})
    if user_data is None:
        raise HTTPException(401, "Invalid token")
    updated_at = int(time.time())
    await async_user_collection.update_one({'_id': user_data['_id']}, {
        '$set': {
            'email': new_email,
            'email_verified': True,
            'updated_at': updated_at,
        },
        '$unset': {
            'email_verification_token': ""
        },
    })
    await async_client_user_cache_collection.update_many(
        {'user_id': user_data['_id']},
        {'$set': {
            'last_modified': updated_at
        }},
    )
async def end_session(
        id_token_hint: Optional[str] = Query(None),
        post_logout_redirect_uri: Optional[str] = Query(None),
        state: Optional[str] = Query(None),
        sid: Optional[str] = Cookie(None, alias=COOKIE_KEY_SID),
        referer: Optional[str] = Header(None),
):
    """Ends the session."""
    if sid is not None:
        await async_session_collection.delete_one({'_id': sid})
    if id_token_hint is not None:
        await async_token_collection.delete_one(
            {'access_token': id_token_hint})
    if post_logout_redirect_uri is not None:
        if state is not None:
            if '#' in post_logout_redirect_uri:
                post_logout_redirect_uri, post_logout_redirect_hash = post_logout_redirect_uri.split(
                    '#', 1)
                post_logout_redirect_hash = '#' + post_logout_redirect_hash
            else:
                post_logout_redirect_hash = ''
            if '?' in post_logout_redirect_uri[:-1]:
                post_logout_redirect_uri += '&state=' + state
            else:
                post_logout_redirect_uri += '?state=' + state
            post_logout_redirect_uri += post_logout_redirect_hash
    elif referer is not None:
        post_logout_redirect_uri = referer
    else:
        post_logout_redirect_uri = ''
    response = RedirectResponse(
        status_code=302,
        headers={'Location': post_logout_redirect_uri},
    )
    response.delete_cookie(COOKIE_KEY_SID)
    response.delete_cookie(COOKIE_KEY_STATE)
    return response
Beispiel #29
0
async def get_center_menu(request: Request, authorization: str = Header(None)):
    # 获取当前的用户
    user = request.scope.get('user')
    level = user.level
    if level == 0:
        sql = '''select dm1.id pid,dm1.sort_id p_sort_id,dm1.menu_name p_name,dm2.id id,dm2.href,dm2.sort_id sort_id,dm2.menu_name  from data2_menu dm1 LEFT JOIN data2_menu dm2 on dm1.id=dm2.pid where dm1.pid = 0 '''.format(
            user.id)
    else:
        sql = '''
        select dm1.id pid,dm1.sort_id p_sort_id, dm1.menu_name p_name,dm2.id id,dm2.href,dm2.sort_id sort_id,dm2.menu_name  from data2_menu dm1 LEFT JOIN data2_menu dm2 on dm1.id=dm2.pid  RIGHT join data2_operator_auth da on da.menu_id=dm2.pid where dm1.pid = 0
        and group_id={}'''.format(user.group_id)
    data = await jade_db.fetch_all(sql)
    df = pd.DataFrame(data)
    data = []
    for p_menu in df.itertuples():
        tmp = {}
        data.append(tmp)
        tmp['yiji_menu'] = {
            'id': p_menu.pid,
            'name': p_menu.p_name,
            'href': '',
            'pid': 0,
            'osrt_id': p_menu.p_sort_id,
        }
        tmp['erji_menu'] = []
        for x, menu in df[df.pid == p_menu.pid].sort_values('sort').iterrows():
            dict_tmp = {
                'id': menu.id,
                'name': menu['name'],
                'href': menu.href,
                'pid': p_menu.pid,
                'sort_id': menu.sort
            }
            tmp['erji_menu'].append(dict_tmp)

    return {'code': "0", 'message': data}
Beispiel #30
0
async def post_webhook(request_body: Request,
                       X_Line_Signature: str = Header(None)):
    body = await request_body.body()
    handler.handle(body.decode(), X_Line_Signature)
    return {"detail": "OK"}