示例#1
0
def post_create_client(  # pylint: disable=R0913
        client_name: str = Form(...),
        client_uri: str = Form(...),
        grant_type: str = Form(...),
        redirect_uri: str = Form(...),
        response_type: str = Form(...),
        scope: str = Form(...),
        token_endpoint_auth_method: str = Form(...)):
    '''Create the client information'''
    client_id = gen_salt(24)
    client_id_issued_at = int(time.time())
    client = OAuth2Client(client_id=client_id,
                          client_id_issued_at=client_id_issued_at)

    client_metadata = {
        'client_name': client_name,
        'client_uri': client_uri,
        'grant_types': grant_type.splitlines(),
        'redirect_uris': redirect_uri.splitlines(),
        'response_types': response_type.splitlines(),
        'scope': scope,
        'token_endpoint_auth_method': token_endpoint_auth_method
    }
    client.set_client_metadata(client_metadata)

    if token_endpoint_auth_method == 'none':
        client.client_secret = ''
    else:
        client.client_secret = gen_salt(48)

    db.add(client)  # pylint: disable=E1101
    db.commit()  # pylint: disable=E1101

    return RedirectResponse(url='/', status_code=status.HTTP_303_SEE_OTHER)
示例#2
0
 def save_authorization_code(self, code, request):
     nonce = request.data.get('nonce')
     item = OAuth2AuthorizationCode(code=code,
                                    client_id=self.client.client_id,
                                    redirect_uri=request.redirect_uri,
                                    scope=request.scope,
                                    user_id=request.user.id,
                                    nonce=nonce)
     db.add(item)  # pylint: disable=E1101
     db.commit()  # pylint: disable=E1101
示例#3
0
async def vc_configs(request: Request,
                     response: Response,
                     id: str = Form(...),
                     subject_identifier: str = Form(...),
                     configuration: str = Form(...)):
    presentation_config = PresentationConfigurations(
        id=id,
        subject_identifier=subject_identifier,
        configuration=configuration)
    print('presentation_config ', presentation_config)
    db.add(presentation_config)
    db.commit()
    return presentation_config
示例#4
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)
示例#5
0
 def revoke_old_credential(self, credential):
     credential.revoked = True
     db.add(credential)  # pylint: disable=E1101
     db.commit()  # pylint: disable=E1101
示例#6
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
示例#7
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
        })
示例#8
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