Ejemplo n.º 1
0
 def query_token(self, token, token_type_hint, client):  # pylint: disable=R1710
     if token_type_hint == 'access_token':
         tok = db.query(OAuth2Token).filter(  # pylint: disable=E1101
             OAuth2Token.access_token == token).first()
     elif token_type_hint == 'refresh_token':
         tok = db.query(OAuth2Token).filter(  # pylint: disable=E1101
             OAuth2Token.refresh_token == token).first()
     else:
         tok = db.query(OAuth2Token).filter(  # pylint: disable=E1101
             OAuth2Token.access_token == token).first()
         if not tok:
             tok = db.query(OAuth2Token).filter(  # pylint: disable=E1101
                 OAuth2Token.refresh_token == token).first()
     if tok:
         if tok.client_id == client.client_id:
             return tok
Ejemplo n.º 2
0
 def query_authorization_code(self, code, client):  # pylint: disable=R1710
     '''Query the authorization code'''
     item = db.query(OAuth2AuthorizationCode).filter(  # pylint: disable=E1101
         OAuth2AuthorizationCode.code == code,
         OAuth2Client.client_id == client.client_id).first()
     if item and not item.is_expired():
         return item
Ejemplo n.º 3
0
def home(request: Request):
    '''List all clients'''
    clients = db.query(OAuth2Client).all()  # pylint: disable=E1101
    return templates.TemplateResponse('home.html', {
        'request': request,
        'clients': clients
    })
Ejemplo n.º 4
0
async def vc_configs(request: Request, response: Response,
                     id: str = Form(...)):
    presentation_config = db.query(PresentationConfigurations).filter(
        PresentationConfigurations.id == id)

    if not presentation_config.first():
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Presentation Config with id {id} not found")

    presentation_config.delete(synchronize_session=False)
    db.commit()
    return 'done'
Ejemplo n.º 5
0
def url_shortener(request: Request, id: str, response: Response):
    print('IN URL ENDPOINT WITH VAR ', id)
    try:
        mapped_url = db.query(MappedUrl).filter(MappedUrl.id == id).all()
        print('MAPPED URL ID ', mapped_url[0].id)
        print('MAPPED URL RETRIEVED ', mapped_url[0].url)
        print('MAPPED URL SESSION ', mapped_url[0].session)
        return RedirectResponse(mapped_url[0].url)
    except Exception:
        print('URL ENDPOINT RESPONSE ', response.body)
        #TODO - change all exception status codes to be HTTPExceptions with error codes
        response.status_code = status.HTTP_400_BAD_REQUEST  # ("Wrong key provided")
        return response
Ejemplo n.º 6
0
def authorize(request: Request, uuid: str = Form(...)):
    '''Provide authorization code response'''
    user = db.query(User).filter(User.uuid == uuid).first()  # pylint: disable=E1101

    if not user:
        user = User(uuid=uuid)
        db.add(user)  # pylint: disable=E1101
        db.commit()  # pylint: disable=E1101

    request.body = {'uuid': uuid}

    try:
        authorization.validate_consent_request(request=request, end_user=user)
    except OAuth2Error as error:
        return dict(error.get_body())

    return authorization.create_authorization_response(request=request,
                                                       grant_user=user)
Ejemplo n.º 7
0
def poll(request: Request, response: Response, pid: str):
    # presentation_request_id = request.get("pid")
    presentation_request_id = request.query_params.get("pid")
    print('POLL PRESENTATION REQUEST ', presentation_request_id)
    if not presentation_request_id:
        response.status_code = status.HTTP_404_NOT_FOUND
        return response

    print('POLL A')
    session = db.query(AuthSession).filter(
        AuthSession.presentation_request_id == presentation_request_id).all()
    # session = get_object_or_404(
    #     AuthSession, presentation_request_id=presentation_request_id
    # )
    print('POLL SESSION ', session)
    if not session[0].presentation_request_satisfied:
        response.status_code = status.HTTP_400_BAD_REQUEST
        return response

    return response
Ejemplo n.º 8
0
async def vc_configs(request: Request,
                     response: Response,
                     id: str = Form(...),
                     subject_identifier: str = Form(...),
                     configuration: str = Form(...)):
    presentation_config_record = db.query(PresentationConfigurations).filter(
        PresentationConfigurations.id == id)

    if not presentation_config_record.first():
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Presentation Config with id {id} not found")

    presentation_config = PresentationConfigurations(
        id=id,
        subject_identifier=subject_identifier,
        configuration=configuration)
    print('DEBUG ',
          request.body().__str__(), request.headers, request.query_params)
    presentation_config_record.update(request)
    db.commit()
    return 'updated'
Ejemplo n.º 9
0
 def authenticate_user(self, credential):
     return db.query(User).filter(  # pylint: disable=E1101
         User.id == credential.user_id).first()
Ejemplo n.º 10
0
 def authenticate_refresh_token(self, refresh_token):  # pylint: disable=R1710
     token = db.query(OAuth2Token).filter(  # pylint: disable=E1101
         OAuth2Token.refresh_token == refresh_token).first()
     if token and token.is_refresh_token_active():
         return token
Ejemplo n.º 11
0
 def authenticate_user(self, authorization_code):
     return db.query(User).filter(  # pylint: disable=E1101
         User.id == authorization_code.user_id).first()
Ejemplo n.º 12
0
def exists_nonce(nonce, req):
    '''Check nonce existance'''
    exists = db.query(OAuth2AuthorizationCode).filter(  # pylint: disable=E1101
        OAuth2Client.client_id == req.client_id,
        OAuth2AuthorizationCode.nonce == nonce).first()
    return bool(exists)
Ejemplo n.º 13
0
async def authorization_vc(pres_req_conf_id: str, request_parameters: dict):
    # TODO - replace AcaPy args with FastAPI.settings module
    # agent_controller = AriesAgentController(admin_url=settings.ACA_PY_URL)
    agent_controller = AriesAgentController(admin_url=ACA_PY_URL)
    # TODO - fix database storage and recovery of pres_req_conf_id
    presentation_configuration = db.query(PresentationConfigurations).filter(PresentationConfigurations.id == pres_req_conf_id).first()
    print('presentation_configuration ', presentation_configuration.to_json())

    response = await agent_controller.proofs.create_request(presentation_configuration.to_json())
    print('PROOF CREATE', response)
    public_did = await agent_controller.wallet.get_public_did()
    print('DID', public_did)
    endpoint = await agent_controller.ledger.get_did_endpoint(public_did['result']['did'])
    print('ENDPOINT', endpoint)
    # TODO - this will wail due to no TAA accepted on ledger
    TAA_response = await agent_controller.ledger.get_taa()
    TAA = TAA_response['result']['taa_record']
    TAA['mechanism'] = "service_agreement"
    # print(TAA)

    TAA_accept = await agent_controller.ledger.accept_taa(TAA)
    ## Will return {} if successful
    print(TAA_accept)
    # TODO - replace AcaPy args with FastAPI.settings module
    # await agent_controller.wallet.set_did_endpoint(public_did['did'], settings.ACA_PY_TRANSPORT_URL, 'Endpoint')
    await agent_controller.wallet.set_did_endpoint(public_did['result']['did'], ACA_PY_TRANSPORT_URL, 'Endpoint')
    endpoint = await agent_controller.ledger.get_did_endpoint(public_did['result']['did'])
    endpoint = endpoint['endpoint']
    print('ENDPOINT ', endpoint)
    print('VERKEY ', [public_did['result']['verkey']] )

    presentation_request = PresentationFactory.from_params(
        presentation_request=response.get("presentation_request"),
        p_id=response.get("thread_id"),
        verkey=[public_did['result']['verkey']],
        endpoint=endpoint,
    ).to_json()

    print('PROOF REQUEST ', presentation_request)

    presentation_request_id = response["presentation_exchange_id"]

    print('PRESENTATION REQUEST ID ', presentation_request_id)
    print('REQUEST PARAMETERS ', request_parameters)
    session = AuthSession(
        id=str(uuid.uuid4()),
        presentation_record_id=pres_req_conf_id,
        presentation_request_id=presentation_request_id,
        presentation_request=presentation_request,
        request_parameters=request_parameters,
        expired_timestamp=datetime.now() + timedelta(minutes=60),
    )
    print('SESSION ', session)
    db.add(session)
    db.commit()
    db.refresh(session)
    print('SESSION ',session.id)

    url, b64_presentation = create_short_url(presentation_request)
    print('URL ', url)

    id = str(uuid.uuid4())
    print('ID ', id)
    mapped_url = MappedUrl(id=id, url=url, session=session.id)
    db.add(mapped_url)
    db.commit()
    db.refresh(mapped_url)
    print('MAPPED URL ', mapped_url, id)
    # return presentation_config
    short_url = mapped_url.get_short_url()
    print('SHORT_URL ',short_url)

    # Terminate controller
    await agent_controller.terminate()

    return short_url, str(session.id), presentation_request_id, b64_presentation
Ejemplo n.º 14
0
async def vc_configs(request: Request, response: Response):
    presentation_configuration = db.query(PresentationConfigurations).all()
    print('presentation_configuration ', presentation_configuration)
    return presentation_configuration
Ejemplo n.º 15
0
async def authorize(request: Request, response: Response, client_id: str,
                    pres_req_conf_id: str, uuid: str, scope: str,
                    response_type: str, redirect_uri: str, state: str,
                    nonce: str):
    '''Provide authorization code response'''
    user = db.query(User).filter(User.uuid == uuid).first()  # pylint: disable=E1101

    if not user:
        user = User(uuid=uuid)
        db.add(user)  # pylint: disable=E1101
        db.commit()  # pylint: disable=E1101

    request.body = {'uuid': uuid}

    pres_req_conf_id = request.query_params.get("pres_req_conf_id")
    print('Presentation Request ID ', pres_req_conf_id)
    if not pres_req_conf_id:
        response.status_code = status.HTTP_400_BAD_REQUEST
        return response  #("pres_req_conf_id query parameter not found")

    presentation_configuration = db.query(PresentationConfigurations).filter(
        PresentationConfigurations.id == pres_req_conf_id).all()

    print('Presentation Configuration ', presentation_configuration)

    scopes = request.query_params.get("scope")
    print('Scopes ', scopes)
    if not scopes or "vc_authn" not in scopes.split(" "):
        response.status_code = status.HTTP_400_BAD_REQUEST
        return response  #("Scope vc_authn not found")

    try:
        print('Request Body ', request.body)
        print('Request Query Params ', request.query_params)
        print('Request Headers ', request.headers)
        authorization.validate_consent_request(request=request, end_user=user)
        print('CONSENT REQUEST VALIDATED')
    except OAuth2Error as error:
        return dict(error.get_body())
    print('VALIDATION DONE')

    short_url, session_id, pres_req, b64_presentation = await authorization_vc(
        pres_req_conf_id, request.query_params.__str__())
    print('PRES REQ ', pres_req)
    print('B64 PRESENTATION ', b64_presentation)

    request.session["sessionid"] = session_id
    print('SESSION ', request.session["sessionid"])

    result = authorization.create_authorization_response(request=request,
                                                         grant_user=user)
    print('AUTHORISATION RESPONSE', result)
    # Create QR Code
    # TODO - remove static variables
    # img_short_url = qrcode.make(f'{SITE_URL}/url/' + pres_req, image_factory=SvgImage)
    img_short_url = qrcode.make(short_url, image_factory=SvgImage)
    img_base64_url = qrcode.make(f'{SITE_URL}?m=' + b64_presentation,
                                 image_factory=SvgImage)

    rendered_svg_short_url = etree.tostring(img_short_url.get_image()).decode()
    rendered_svg_base64_url = etree.tostring(
        img_base64_url.get_image()).decode()

    # TODO - remove static variables
    return templates.TemplateResponse(
        'qr_display.html', {
            'request': request,
            "b64_presentation": b64_presentation,
            "poll_interval": 5000,
            "poll_max_tries": 12,
            "poll_url": f"{SITE_URL}/vc/connect/poll?pid={pres_req}",
            "resolution_url": f"{SITE_URL}/vc/connect/callback?pid={pres_req}",
            "pres_req": pres_req,
            "rendered_svg_short_url": rendered_svg_short_url,
            "rendered_svg_base64_url": rendered_svg_base64_url
        })
Ejemplo n.º 16
0
async def webhooks(request: Request, response: Response, topic: str):
    print('WEBHOOK ENDPOINT WITH TOPIC ', topic)
    print('WEBHOOK REQUEST ', await request.body())
    message_dict = json.dumps(await request.json())
    message = json.loads(message_dict)

    print('WEBHOOK MESSAGE ', message)

    LOGGER.info(f"webhook received - topic: {topic} and message: {message}")
    print('WEBHOOK DEBUG1')
    # Should be triggered after a proof request has been sent by the org
    if topic == "present_proof":
        state = message["state"]
        print('WEBHOOK DEBUG2')
        if state != "presentation_received":
            LOGGER.info(
                f"WEBHOOK - Presentation Request not yet received, state is [{state}]"
            )
            print('WEBHOOK DEBUG3')

            response.status_code = status.HTTP_200_OK
            print('WEBHOOK RESPONSE ', response.body, response.status_code)
            return response
        print('WEBHOOK DEBUG4')
        presentation_exchange_id = "- not_set -"
        try:
            print('WEBHOOK DEBUG5')
            proof = message["presentation"]["requested_proof"]
            presentation_exchange_id = message["presentation_exchange_id"]
            print('WEBHOOK PRESENTATION EXCHANGE ID ',
                  presentation_exchange_id)

            LOGGER.info(f"Proof received: {proof}")
            print('WEBHOOK DEBUG6')
            # session = AuthSession.objects.get(
            #     presentation_request_id=presentation_exchange_id
            # )
            print('WEBHOOK SESSION A ')
            session = db.query(AuthSession).filter(
                AuthSession.presentation_request_id ==
                presentation_exchange_id).all()

            print('WEBHOOK SESSION B ', session)
            # TODO - fix the satisfy_session in the DB models

            # session.satisfy_session(proof)

            authsession = AuthSession(
                presentation_request_id=presentation_exchange_id,
                presentation_request_satisfied=True,
                presentation=presentation)
            print('WEBHOOK SESSION C ', authsession)
            db.add(authsession)
            db.commit()

            print('WEBHOOK SESSION C ', authsession)
        # except (AuthSession.DoesNotExist, AuthSession.MultipleObjectsReturned):
        # except Exception(KeyError):
        #     # TODO - enable logging again
        #     LOGGER.warning(
        #         f"KEYERROR"
        #         f"Presentation request id: [{presentation_exchange_id}] and message body is [{message}]"
        #     )
        #     return response

        except Exception as e:
            # TODO - enable logging again
            LOGGER.warning(
                f"Could not find a corresponding auth session to satisfy. "
                f"Presentation request id: [{presentation_exchange_id}] with message [{message}]"
            )
            response.status_code = status.HTTP_200_OK
            return response

        # except Exception as e:
        #     # TODO - enable logging again
        #     # LOGGER.error(f"Wrong 'present_proof' body: {message} - error: {e}")
        #     return response
    response.status_code = status.HTTP_200_OK
    return response