def wrapper(*args, **kwargs): current_time = int(round(time.time())) if (current_time + TOKEN_REPLACEMENT_IN_SECONDS) > DsClient.expiresTimestamp: if DsClient.jwt_auth: DsClient.get_instance().update_token() elif DsClient.code_grant: return redirect(url_for("auth.code_grant_auth")) return func(*args, **kwargs)
def wrapper(*args, **kwargs): if session.get('auth_type') == 'jwt': DsClient.update_token() if not SessionData.is_logged(): return redirect(url_for("auth.code_grant_auth")) return func(*args, **kwargs)
def callback(): try: try: req_json = request.get_json(force=True) code = req_json['code'] except TypeError: return jsonify(message='Invalid json input'), 400 DsClient.callback(code) except ApiException: return redirect(url_for("auth.jwt_auth"), code=307) return jsonify(message="Logged in with code grant"), 200
def get_user_agreements(cls, args): """Gets all the users that have agreed to a clickwrap Parameters: args (dict): parameters for the clickwrap. Returns: list of users that have agreed to a clickwrap """ # Make a GET call to the clickwraps endpoint to retrieve all the users # that have agreed to a clickwrap ds_client = DsClient.get_instance(CLICKWRAP_BASE_HOST) uri = f"{CLICKWRAP_BASE_URI}/{ds_client.account_id}/clickwraps/{args['clickwrap_id']}/users" response = ds_client.api_client.call_api(uri, 'GET', response_type='object') agreed_users = [] utc_time_now = datetime.utcnow() user_agreements = response[0].get('userAgreements') if user_agreements: for agreement in user_agreements: client_user_id = agreement['clientUserId'] agreed_on = datetime.strptime( agreement['agreedOn'].split('.')[0], '%Y-%m-%dT%H:%M:%S') time_delta = (utc_time_now - agreed_on).total_seconds() / 60 # Сheck that no more than 15 minutes have passed since the # agreement was agreed if time_delta <= CLICKWRAP_TIME_DELTA_IN_MINUTES: agreed_users.append(client_user_id) return agreed_users
def get_view(cls, envelope_id, envelope_args, user, authentication_method='None'): """Get the recipient view Parameters: envelope_id (str): Envelope ID envelope_args (dict): Parameters of the document user (dict): User information authentication_method (str): Authentication method Returns: URL to the recipient view UI """ # Create the recipient view request object recipient_view_request = RecipientViewRequest( authentication_method=authentication_method, client_user_id=envelope_args['signer_client_id'], recipient_id='1', return_url=envelope_args['ds_return_url'], user_name=f"{user['first_name']} {user['last_name']}", email=user['email'] ) # Obtain the recipient view URL for the signing ceremony # Exceptions will be caught by the calling function ds_client = DsClient.get_instance() envelope_api = EnvelopesApi(ds_client.api_client) results = envelope_api.create_recipient_view( ds_client.account_id, envelope_id, recipient_view_request=recipient_view_request ) return results
def get_view(envelope_id, envelope_args, student, session, authentication_method='None'): """Get the recipient view Parameters: envelope_id (str): envelope ID envelope_args (dict): parameters of the document student (dict): student information authentication_method (str): authentication method Returns: URL to the recipient view UI """ access_token = session.get('access_token') account_id = session.get('account_id') # Create the RecipientViewRequest object recipient_view_request = RecipientViewRequest( authentication_method=authentication_method, client_user_id=envelope_args['signer_client_id'], recipient_id='1', return_url=envelope_args['ds_return_url'], user_name=f"{student['first_name']} {student['last_name']}", email=student['email'] ) # Obtain the recipient view URL for the signing ceremony # Exceptions will be caught by the calling function ds_client = DsClient.get_configured_instance(access_token) envelope_api = EnvelopesApi(ds_client) results = envelope_api.create_recipient_view( account_id, envelope_id, recipient_view_request=recipient_view_request ) return results
def create(cls, args): """Creates a clickwrap for an account Parameters: args (dict): parameters for the clickwrap. Returns: JSON structure of the created clickwrap. """ terms_name = args.get('terms_name') terms_transcript = args.get('terms_transcript') display_name = args.get('display_name') with open(path.join(TPL_PATH, 'transcript-terms.html'), 'r') as file: terms = file.read() terms = Environment(loader=BaseLoader).from_string(terms).render( terms_transcript=terms_transcript, ) base64_terms = base64.b64encode(bytes(terms, 'utf-8')).decode('ascii') # Construct clickwrap JSON body body = { 'displaySettings': { 'consentButtonText': 'I Agree', 'displayName': display_name, 'downloadable': True, 'format': 'modal', 'hasAccept': True, 'mustRead': True, 'mustView': True, 'requireAccept': True, 'size': 'medium', 'documentDisplay': 'document' }, 'documents': [{ 'documentBase64': base64_terms, 'documentName': terms_name, 'fileExtension': 'html', 'order': 0 }], 'name': terms_name, 'requireReacceptance': True } # Make a POST call to the clickwraps endpoint to create a clickwrap # for an account ds_client = DsClient.get_instance(CLICKWRAP_BASE_HOST) uri = f"{CLICKWRAP_BASE_URI}/{ds_client.account_id}/clickwraps" response = ds_client.api_client.call_api(uri, 'POST', body=body, response_type='object') clickwrap_id = response[0].get('clickwrapId') # Make a PUT call to the clickwraps endpoint to activate created # clickwrap uri = f"{CLICKWRAP_BASE_URI}/{ds_client.account_id}/clickwraps/{clickwrap_id}/versions/1" response_active = ds_client.api_client.call_api( uri, 'PUT', body={'status': 'active'}, response_type='object') return response_active[0]
def check_payment(): try: if DsClient.check_payment_gateway(): return jsonify(message="User has a payment gateway account"), 200 else: return jsonify( message="User doesn't have a payment gateway account"), 402 except ApiException as ex: return process_error(ex)
def create(cls, args): """Creates a clickwrap for an account Parameters: args (dict): Parameters for the clickwrap. Returns: JSON structure of the created clickwrap. """ display_name = args.get('display_name') terms_name = args.get('terms_name') file_name = 'terms-renewal.docx' file_extension = file_name[file_name.rfind('.') + 1:] with open(path.join(TPL_PATH, file_name), 'rb') as binary_file: binary_file_data = binary_file.read() base64_encoded_data = base64.b64encode(binary_file_data) base64_terms = base64_encoded_data.decode('utf-8') # Construct clickwrap JSON body body = { 'displaySettings': { 'consentButtonText': 'I Agree', 'displayName': display_name, 'downloadable': True, 'format': 'modal', 'hasAccept': True, 'mustRead': True, 'mustView': True, 'requireAccept': True, 'size': 'medium', 'documentDisplay': 'document', }, 'documents': [{ 'documentBase64': base64_terms, 'documentName': terms_name, 'fileExtension': file_extension, 'order': 0 }], 'name': terms_name, 'requireReacceptance': True } # Make a POST call to the clickwraps endpoint to create a clickwrap for an account ds_client = DsClient.get_instance(CLICKWRAP_BASE_HOST) uri = f"{CLICKWRAP_BASE_URI}/{ds_client.account_id}/clickwraps" response = ds_client.api_client.call_api(uri, 'POST', body=body, response_type='object') clickwrap_id = response[0].get('clickwrapId') # Make a PUT call to the clickwraps endpoint to activate created clickwrap uri = f"{CLICKWRAP_BASE_URI}/{ds_client.account_id}/clickwraps/{clickwrap_id}/versions/1" response_active = ds_client.api_client.call_api( uri, 'PUT', body={'status': 'active'}, response_type='object') return response_active[0]
def code_grant_auth(): try: url = DsClient.code_auth() except ApiException as ex: return process_error(ex) return jsonify({ 'reason': 'Unauthorized', 'response': 'Permissions should be granted for current integration', 'url': url }), 401
def jwt_auth(): try: auth_data = DsClient.update_token() except ApiException as exc: return process_error(exc) SessionData.set_auth_data(auth_data) SessionData.set_payment_data() return jsonify(message="Logged in with JWT"), 200
def download(cls, args): """Download the specified document from the envelope""" ds_client = DsClient.get_instance() envelope_api = EnvelopesApi(ds_client.api_client) file_path = envelope_api.get_document(ds_client.account_id, args['document_id'], args['envelope_id']) (dirname, filename) = os.path.split(file_path) return send_from_directory(directory=dirname, filename=filename, as_attachment=True)
def check_payment(): try: payment_data = DsClient.check_payment_gateway(session) except ApiException as exc: return process_error(exc) if payment_data: session.update(payment_data) return jsonify(message="User has a payment gateway account"), 200 return jsonify(message="User doesn't have a payment gateway account"), 402
def code_grant_auth(): """ Starting authorization by code grant """ try: url = DsClient.get_redirect_uri() except ApiException as exc: return process_error(exc) return jsonify({ 'reason': 'Unauthorized', 'response': 'Permissions should be granted for current integration', 'url': url }), 401
def send(cls, envelope): """Send an envelope Parameters: envelope (object): EnvelopeDefinition object Returns: envelope_id (str): envelope ID """ # Call Envelope API create method # Exceptions will be caught by the calling function ds_client = DsClient.get_instance() envelope_api = EnvelopesApi(ds_client.api_client) results = envelope_api.create_envelope(ds_client.account_id, envelope_definition=envelope) return results.envelope_id
def callback(): """ Completing authorization by code grant """ try: req_json = request.get_json(force=True) except TypeError: return jsonify(message='Invalid json input'), 400 try: auth_data = DsClient.callback(req_json['code']) except ApiException: return redirect(url_for("auth.jwt_auth"), code=307) SessionData.set_auth_data(auth_data) return jsonify(message="Logged in with code grant"), 200
def download(args, session): """Download the specified document from the envelope""" access_token = session.get('access_token') account_id = session.get('account_id') ds_client = DsClient.get_configured_instance(access_token) envelope_api = EnvelopesApi(ds_client) file_path = envelope_api.get_document( account_id, args['document_id'], args['envelope_id'] ) (dirname, filename) = os.path.split(file_path) return send_from_directory( directory=dirname, filename=filename, as_attachment=True )
def list(cls, envelope_args, user_documents): """Get status changes for one or more envelopes Parameters: envelope_args (dict): Document parameters user_documents (list): Documents signed by user Returns: EnvelopesInformation """ ds_client = DsClient.get_instance() envelope_api = EnvelopesApi(ds_client.api_client) envelopes_info = envelope_api.list_status_changes( ds_client.account_id, from_date=envelope_args['from_date'], include='recipients' ) if not envelopes_info.envelopes: return [] results = [env.to_dict() for env in envelopes_info.envelopes if env.envelope_id in user_documents] return results
def send(envelope, session): """Send an envelope Parameters: envelope (object): EnvelopeDefinition object Returns: envelope_id (str): envelope ID """ # Call Envelope API create method # Exceptions will be caught by the calling function access_token = session.get('access_token') account_id = session.get('account_id') ds_client = DsClient.get_configured_instance(access_token) envelope_api = EnvelopesApi(ds_client) results = envelope_api.create_envelope( account_id, envelope_definition=envelope ) return results.envelope_id
def list(envelope_args, user_documents, session): """Get status changes for one or more envelopes Parameters: envelope_args (dict): document parameters user_documents (list): documents signed by user Returns: EnvelopesInformation """ access_token = session.get('access_token') account_id = session.get('account_id') ds_client = DsClient.get_configured_instance(access_token) envelope_api = EnvelopesApi(ds_client) envelopes_info = envelope_api.list_status_changes( account_id, from_date=envelope_args['from_date'], include='recipients' ) if not envelopes_info.envelopes: return [] results = [env.to_dict() for env in envelopes_info.envelopes if env.envelope_id in user_documents] return results
def jwt_auth(): try: DsClient.update_token() except ApiException as ex: return process_error(ex) return jsonify(message="Logged in with JWT"), 200
def log_out(): DsClient.destroy() return jsonify(message="Logged out"), 200