Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions examples/doc_scan/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
RequestedSupplementaryDocTextExtractionTaskBuilder,
SdkConfigBuilder,
SessionSpecBuilder,
SessionOverviewPdfRequestBuilder,
)
from yoti_python_sdk.doc_scan.exception import DocScanException
from yoti_python_sdk.doc_scan.session.create.filter import (
Expand Down Expand Up @@ -174,6 +175,53 @@ def media():
)


@app.route("/session-pdf")
def session_pdf():
"""
Generates and returns the session overview PDF for the current session.
The PDF is streamed back to the browser as a downloadable file.
"""
doc_scan_client = DocScanClient(YOTI_CLIENT_SDK_ID, YOTI_KEY_FILE_PATH)

session_id = session.get("doc_scan_session_id", None)
if session_id is None:
return Response("No session ID available", status=404)

include_images = request.args.get("include_images", None)
include_extracted_text = request.args.get("include_extracted_text", None)
include_device_tracking = request.args.get("include_device_tracking", None)

pdf_request_builder = SessionOverviewPdfRequestBuilder()
if include_images is not None:
pdf_request_builder.with_include_images(include_images.lower() == "true")
if include_extracted_text is not None:
pdf_request_builder.with_include_extracted_text(
include_extracted_text.lower() == "true"
)
if include_device_tracking is not None:
pdf_request_builder.with_include_device_tracking(
include_device_tracking.lower() == "true"
)

pdf_request = pdf_request_builder.build()

try:
pdf_bytes = doc_scan_client.create_session_overview_pdf(session_id, pdf_request)
except DocScanException as e:
return render_template("error.html", error=e.message)

return Response(
pdf_bytes,
content_type="application/pdf",
status=200,
headers={
"Content-Disposition": "attachment; filename=session-overview-{}.pdf".format(
session_id
)
},
)


@app.route("/privacy-policy")
def privacy_policy():
return render_template("privacy.html")
Expand Down
12 changes: 12 additions & 0 deletions examples/doc_scan/templates/success.html
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,18 @@ <h1>Get Session Result</h1>
<td>{{ session_result.biometric_consent_timestamp }}</td>
</tr>
{% endif %}
<tr>
<td>Session Overview PDF</td>
<td>
<a href="/session-pdf" class="btn btn-sm btn-primary">
Download PDF
</a>
&nbsp;
<a href="/session-pdf?include_images=true&include_extracted_text=true&include_device_tracking=true" class="btn btn-sm btn-secondary">
Download PDF (all flags)
</a>
</td>
</tr>
</tbody>
</table>
</div>
Expand Down
14 changes: 14 additions & 0 deletions yoti_python_sdk/auth/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# -*- coding: utf-8 -*-
from .authentication_token_generator import (
AuthenticationTokenGenerator,
AuthenticationTokenGeneratorBuilder,
)
from .create_authentication_token_response import CreateAuthenticationTokenResponse
from .exception import AuthException

__all__ = [
"AuthenticationTokenGenerator",
"AuthenticationTokenGeneratorBuilder",
"CreateAuthenticationTokenResponse",
"AuthException",
]
223 changes: 223 additions & 0 deletions yoti_python_sdk/auth/authentication_token_generator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import base64
import json
import time
import uuid
from os import environ

import requests

from yoti_python_sdk.crypto import Crypto
from .create_authentication_token_response import CreateAuthenticationTokenResponse
from .exception import AuthException

DEFAULT_AUTH_API_URL = "https://auth.api.yoti.com/v1/oauth/token"
CLIENT_ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
JWT_EXPIRY_SECONDS = 300
DEFAULT_REQUEST_TIMEOUT_SECONDS = 30


def _default_jwt_id_supplier():
return str(uuid.uuid4())


class AuthenticationTokenGenerator(object):
"""
Generates a central auth token that can be supplied to an SDK client
(e.g. DocScanClient, Client) instead of a PEM file, allowing the Relying
Business to authenticate using the new central auth scheme.

The SDK does not automatically refresh or cache the generated token; the
caller is responsible for generating a new one before it expires
(see CreateAuthenticationTokenResponse.expires_in).
"""

def __init__(
self,
sdk_id,
crypto,
auth_api_url,
jwt_id_supplier=None,
timeout=DEFAULT_REQUEST_TIMEOUT_SECONDS,
):
self.__sdk_id = sdk_id
self.__crypto = crypto
self.__auth_api_url = auth_api_url
self.__jwt_id_supplier = jwt_id_supplier or _default_jwt_id_supplier
self.__timeout = timeout

@staticmethod
def builder():
"""
Returns an instance of AuthenticationTokenGeneratorBuilder
"""
return AuthenticationTokenGeneratorBuilder()

def generate(self, scopes):
"""
Generates an authentication token for the supplied scopes

:param scopes: the scopes to request for the token
:type scopes: list[str]
:return: the generated token response
:rtype: CreateAuthenticationTokenResponse
:raises ValueError: if scopes is empty
:raises AuthException: if the token could not be generated
"""
if not scopes:
raise ValueError("scopes must not be empty")

client_assertion = self.__create_signed_jwt()
form_data = {
"grant_type": "client_credentials",
"client_assertion_type": CLIENT_ASSERTION_TYPE,
"client_assertion": client_assertion,
"scope": " ".join(scopes),
}

response = requests.post(
self.__auth_api_url, data=form_data, timeout=self.__timeout
)

if response.status_code != 200:
raise AuthException("Failed to generate authentication token", response)

return CreateAuthenticationTokenResponse(json.loads(response.text))

def __create_signed_jwt(self):
"""
Creates a PS384-signed JWT client assertion, identifying the SDK by
sdk_id and valid for JWT_EXPIRY_SECONDS
"""
issuer = "sdk:{0}".format(self.__sdk_id)
now = int(time.time())

header = {"alg": "PS384", "typ": "JWT"}
payload = {
"iss": issuer,
"sub": issuer,
"jti": self.__jwt_id_supplier(),
"aud": self.__auth_api_url,
"iat": now,
"exp": now + JWT_EXPIRY_SECONDS,
}

signing_input = "{0}.{1}".format(
self.__base64url_encode(self.__json_dumps(header)),
self.__base64url_encode(self.__json_dumps(payload)),
)
signature = self.__crypto.sign_ps384(signing_input.encode("utf-8"))

return "{0}.{1}".format(signing_input, self.__base64url_encode(signature))

@staticmethod
def __json_dumps(data):
return json.dumps(data, separators=(",", ":"), sort_keys=True).encode("utf-8")

@staticmethod
def __base64url_encode(data):
return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")


class AuthenticationTokenGeneratorBuilder(object):
"""
Builder to assist in the creation of :class:`AuthenticationTokenGenerator`
"""

def __init__(self):
self.__sdk_id = None
self.__crypto = None
self.__auth_api_url = None
self.__jwt_id_supplier = None
self.__timeout = DEFAULT_REQUEST_TIMEOUT_SECONDS

def with_sdk_id(self, sdk_id):
"""
Sets the SDK ID to identify the token request

:param sdk_id: the SDK ID
:type sdk_id: str
:return: the builder
:rtype: AuthenticationTokenGeneratorBuilder
"""
self.__sdk_id = sdk_id
return self

def with_pem_file(self, pem_file):
"""
Sets the PEM file used to sign the JWT client assertion. Can be an
instance of yoti_python_sdk.crypto.Crypto or a path to a PEM file

:param pem_file: the PEM file or Crypto instance
:return: the builder
:rtype: AuthenticationTokenGeneratorBuilder
"""
if isinstance(pem_file, Crypto):
self.__crypto = pem_file
else:
self.__crypto = Crypto.read_pem_file(pem_file)

return self

def with_auth_api_url(self, auth_api_url):
"""
Overrides the default auth API URL

:param auth_api_url: the auth API URL
:type auth_api_url: str
:return: the builder
:rtype: AuthenticationTokenGeneratorBuilder
"""
self.__auth_api_url = auth_api_url
return self

def with_jwt_id_supplier(self, jwt_id_supplier):
"""
Overrides the callable used to generate the JWT ID (jti claim).
Defaults to generating a random UUID v4 for each token request

:param jwt_id_supplier: a callable returning a unique string
:type jwt_id_supplier: callable
:return: the builder
:rtype: AuthenticationTokenGeneratorBuilder
"""
self.__jwt_id_supplier = jwt_id_supplier
return self

def with_timeout(self, timeout):
"""
Overrides the timeout (in seconds) used for the auth token request

:param timeout: the timeout in seconds
:type timeout: float
:return: the builder
:rtype: AuthenticationTokenGeneratorBuilder
"""
self.__timeout = timeout
return self

def build(self):
"""
Builds an AuthenticationTokenGenerator with the supplied values

:return: the authentication token generator
:rtype: AuthenticationTokenGenerator
"""
if self.__sdk_id is None:
raise ValueError("sdk_id must be provided")
if self.__crypto is None:
raise ValueError("pem_file must be provided")

auth_api_url = self.__auth_api_url or environ.get(
"YOTI_AUTH_URL", DEFAULT_AUTH_API_URL
)

return AuthenticationTokenGenerator(
self.__sdk_id,
self.__crypto,
auth_api_url,
jwt_id_supplier=self.__jwt_id_supplier,
timeout=self.__timeout,
)
59 changes: 59 additions & 0 deletions yoti_python_sdk/auth/create_authentication_token_response.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# -*- coding: utf-8 -*-


class CreateAuthenticationTokenResponse(object):
"""
The response returned when generating a central auth token
"""

def __init__(self, data):
"""
:param data: the parsed JSON response body
:type data: dict
"""
self.__access_token = data.get("access_token")
self.__token_type = data.get("token_type")
self.__expires_in = data.get("expires_in")
self.__scope = data.get("scope")

@property
def access_token(self):
"""
The auth token to be supplied to an SDK client

:return: the access token
:rtype: str
"""
return self.__access_token

@property
def token_type(self):
"""
The type of token issued, e.g. "Bearer"

:return: the token type
:rtype: str
"""
return self.__token_type

@property
def expires_in(self):
"""
The lifetime of the access token in seconds. The SDK does not
automatically refresh the token on expiry; it is the caller's
responsibility to generate a new one before it expires

:return: the expiry, in seconds
:rtype: int or None
"""
return self.__expires_in

@property
def scope(self):
"""
The scopes granted to the access token

:return: the granted scopes
:rtype: str or None
"""
return self.__scope
Loading
Loading