def post(account_number: str): """Create the payment records.""" current_app.logger.info('<AccountPurchaseHistory.post') request_json = request.get_json() current_app.logger.debug(request_json) # Validate the input request valid_format, errors = schema_utils.validate( request_json, 'purchase_history_request') if not valid_format: return error_to_response( Error.INVALID_REQUEST, invalid_params=schema_utils.serialize(errors)) # Check if user is authorized to perform this action check_auth(business_identifier=None, account_id=account_number, contains_role=EDIT_ROLE, is_premium=True) page: int = int(request.args.get('page', '1')) limit: int = int(request.args.get('limit', '10')) response, status = Payment.search_purchase_history( account_number, request_json, page, limit), HTTPStatus.OK current_app.logger.debug('>AccountPurchaseHistory.post') return jsonify(response), status
def post(account_id): """Update the statement settings .""" current_app.logger.info('<AccountStatementsNotifications.post') request_json = request.get_json() valid_format, errors = schema_utils.validate( request_json, 'statement_notification_request') if not valid_format: return error_to_response( Error.INVALID_REQUEST, invalid_params=schema_utils.serialize(errors)) current_app.logger.debug(request_json) # TODO add valid formatting # Check if user is authorized to perform this action check_auth(business_identifier=None, account_id=account_id, contains_role=EDIT_ROLE, is_premium=True) try: StatementRecipients.update_statement_notification_details( account_id, request_json) except BusinessException as exception: return exception.response() current_app.logger.debug('>AccountStatementsNotifications.post') return jsonify(None), HTTPStatus.CREATED
def put(payment_id): """Update the payment records.""" current_app.logger.info('<Payment.put') request_json = request.get_json() current_app.logger.debug(request_json) # Validate the input request valid_format, errors = schema_utils.validate(request_json, 'payment_request') if not valid_format: return jsonify({ 'code': 'PAY003', 'message': schema_utils.serialize(errors) }), HTTPStatus.BAD_REQUEST # Check if user is authorized to perform this action check_auth(request_json.get('businessInfo').get('businessIdentifier'), one_of_roles=[EDIT_ROLE]) try: response, status = ( PaymentService.update_payment(payment_id, request_json), HTTPStatus.OK, ) except BusinessException as exception: response, status = { 'code': exception.code, 'message': exception.message }, exception.status except ServiceUnavailableException as exception: response, status = { 'code': exception.status_code }, HTTPStatus.BAD_REQUEST current_app.logger.debug('>Payment.put') return jsonify(response), status
def post(account_id: str): """Create account payments.""" current_app.logger.info('<Payments.post') # Check if user is authorized to perform this action check_auth(business_identifier=None, account_id=account_id, contains_role=MAKE_PAYMENT) # If it's a staff user, then create credits. if set([Role.STAFF.value, Role.CREATE_CREDITS.value ]).issubset(set(g.jwt_oidc_token_info.get('roles'))): credit_request = request.get_json() # Valid payment payload. valid_format, errors = schema_utils.validate( credit_request, 'payment') if not valid_format: return error_to_response( Error.INVALID_REQUEST, invalid_params=schema_utils.serialize(errors)) if credit_request.get('paymentMethod') in \ (PaymentMethod.EFT.value, PaymentMethod.WIRE.value, PaymentMethod.DRAWDOWN.value): response, status = PaymentService.create_payment_receipt( auth_account_id=account_id, credit_request=credit_request).asdict(), HTTPStatus.CREATED else: is_retry_payment: bool = (request.args.get( 'retryFailedPayment', 'false').lower() == 'true') response, status = PaymentService.create_account_payment( auth_account_id=account_id, is_retry_payment=is_retry_payment).asdict(), HTTPStatus.CREATED current_app.logger.debug('>Payments.post') return jsonify(response), status
def get(account_id): """Get all statements records for an account.""" current_app.logger.info('<AccountStatementsNotifications.get') # Check if user is authorized to perform this action check_auth(business_identifier=None, account_id=account_id, contains_role=EDIT_ROLE, is_premium=True) statement_notification_details = StatementRecipients.find_statement_notification_details(account_id) response, status = statement_notification_details, HTTPStatus.OK current_app.logger.debug('>AccountStatementsNotifications.get') return jsonify(response), status
def get(account_number: str): """Get payment account details.""" current_app.logger.info('<Account.get') # Check if user is authorized to perform this action check_auth(business_identifier=None, account_id=account_number, one_of_roles=[EDIT_ROLE, VIEW_ROLE]) response, status = PaymentAccountService.find_by_auth_account_id( account_number).asdict(), HTTPStatus.OK current_app.logger.debug('>Account.get') return jsonify(response), status
def get(account_id: str): """Get account payments.""" current_app.logger.info('<Payments.get') # Check if user is authorized to perform this action check_auth(business_identifier=None, account_id=account_id, contains_role=MAKE_PAYMENT) page: int = int(request.args.get('page', '1')) limit: int = int(request.args.get('limit', '10')) status: str = request.args.get('status', None) response, status = PaymentService.search_account_payments(auth_account_id=account_id, status=status, page=page, limit=limit), HTTPStatus.OK current_app.logger.debug('>Payments.get') return jsonify(response), status
def get(account_id): """Get all statements records for an account.""" current_app.logger.info('<AccountStatements.get') # Check if user is authorized to perform this action check_auth(business_identifier=None, account_id=account_id, contains_role=EDIT_ROLE, is_premium=True) page: int = int(request.args.get('page', '1')) limit: int = int(request.args.get('limit', '10')) response, status = StatementService.find_by_account_id(account_id, page, limit), HTTPStatus.OK current_app.logger.debug('>AccountStatements.get') return jsonify(response), status
def test_auth_for_client_user_roles(session, public_user_mock): """Assert that the auth is working as expected.""" # token = jwt.create_jwt(get_claims(roles=[Role.EDITOR.value]), token_header) # headers = {'Authorization': 'Bearer ' + token} # def mock_auth(one, two): # pylint: disable=unused-argument; mocks of library methods # return headers['Authorization'] # with app.test_request_context(): # monkeypatch.setattr('flask.request.headers.get', mock_auth) # Test one of roles check_auth('CP0001234', one_of_roles=[EDIT_ROLE]) # Test contains roles check_auth('CP0001234', contains_role=EDIT_ROLE) # Test for exception with pytest.raises(HTTPException) as excinfo: check_auth('CP0000000', contains_role=VIEW_ROLE) assert excinfo.exception.code == 403 with pytest.raises(HTTPException) as excinfo: check_auth('CP0000000', one_of_roles=[EDIT_ROLE]) assert excinfo.exception.code == 403
def delete(account_number: str): """Get payment account details.""" current_app.logger.info('<Account.delete') # Check if user is authorized to perform this action check_auth(business_identifier=None, account_id=account_number, one_of_roles=[EDIT_ROLE, VIEW_ROLE]) try: PaymentAccountService.delete_account(account_number) except BusinessException as exception: return exception.response() except ServiceUnavailableException as exception: return exception.response() current_app.logger.debug('>Account.delete') return jsonify({}), HTTPStatus.NO_CONTENT
def find_by_id(identifier: int, jwt: JwtManager = None, skip_auth_check: bool = False, one_of_roles: Tuple = ALL_ALLOWED_ROLES): """Find payment by id.""" payment_dao = PaymentModel.find_by_id(identifier) # Check if user is authorized to view the payment if not skip_auth_check and payment_dao: for invoice in payment_dao.invoices: check_auth(invoice.account.corp_number, jwt, one_of_roles=one_of_roles) payment = Payment() payment._dao = payment_dao # pylint: disable=protected-access current_app.logger.debug('>find_by_id') return payment
def put(payment_id): """Update the payment records.""" current_app.logger.info('<Payment.put') request_json = request.get_json() current_app.logger.debug(request_json) # Validate the input request valid_format, errors = schema_utils.validate(request_json, 'payment_request') if not valid_format: return error_to_response( Error.INVALID_REQUEST, invalid_params=schema_utils.serialize(errors)) # Check if user is authorized to perform this action authorization = check_auth( request_json.get('businessInfo').get('businessIdentifier'), one_of_roles=[EDIT_ROLE]) try: response, status = ( PaymentService.update_payment(payment_id, request_json, authorization), HTTPStatus.OK, ) except (BusinessException, ServiceUnavailableException) as exception: return exception.response() current_app.logger.debug('>Payment.put') return jsonify(response), status
def post(): """Create the payment records.""" current_app.logger.info('<Payment.post') request_json = request.get_json() current_app.logger.debug(request_json) # Validate the input request valid_format, errors = schema_utils.validate(request_json, 'payment_request') if not valid_format: return error_to_response( Error.INVALID_REQUEST, invalid_params=schema_utils.serialize(errors)) # Check if user is authorized to perform this action business_identifier = get_str_by_path( request_json, 'businessInfo/businessIdentifier') corp_type_code = get_str_by_path(request_json, 'businessInfo/corpType') authorization = check_auth(business_identifier=business_identifier, corp_type_code=corp_type_code, contains_role=EDIT_ROLE) try: response, status = PaymentService.create_payment( request_json, authorization), HTTPStatus.CREATED except (BusinessException, ServiceUnavailableException) as exception: return exception.response() current_app.logger.debug('>Payment.post') return jsonify(response), status
def test_auth_role_for_service_account(session, monkeypatch): """Assert the auth works for service account.""" def token_info(): # pylint: disable=unused-argument; mocks of library methods return { 'username': '******', 'realm_access': { 'roles': ['system', 'edit'] } } def mock_auth(): # pylint: disable=unused-argument; mocks of library methods return 'test' monkeypatch.setattr('pay_api.utils.user_context._get_token', mock_auth) monkeypatch.setattr('pay_api.utils.user_context._get_token_info', token_info) # Test one of roles check_auth('CP0001234', one_of_roles=[EDIT_ROLE])
def post(account_number: str): """Create the payment records.""" current_app.logger.info('<AccountPurchaseReport.post') response_content_type = request.headers.get('Accept', ContentType.PDF.value) request_json = request.get_json() current_app.logger.debug(request_json) # Validate the input request valid_format, errors = schema_utils.validate( request_json, 'purchase_history_request') if not valid_format: return error_to_response( Error.INVALID_REQUEST, invalid_params=schema_utils.serialize(errors)) report_name = 'bcregistry-transactions-{}'.format( datetime.now().strftime('%m-%d-%Y')) if response_content_type == ContentType.PDF.value: report_name = f'{report_name}.pdf' else: report_name = f'{report_name}.csv' # Check if user is authorized to perform this action check_auth(business_identifier=None, account_id=account_number, contains_role=EDIT_ROLE, is_premium=True) report = Payment.create_payment_report(account_number, request_json, response_content_type, report_name) response = Response(report, 201) response.headers.set('Content-Disposition', 'attachment', filename=report_name) response.headers.set('Content-Type', response_content_type) response.headers.set('Access-Control-Expose-Headers', 'Content-Disposition') return response
def test_auth_for_roles(session): """Assert that the auth is working as expected.""" # Test one of roles check_auth('CP0001234', None, one_of_roles=[EDIT_ROLE]) # Test contains roles check_auth('CP0001234', None, contains_role=EDIT_ROLE) # Test for exception with pytest.raises(HTTPException) as excinfo: check_auth('CP0000000', None, contains_role=VIEW_ROLE) assert excinfo.exception.code == 403 with pytest.raises(HTTPException) as excinfo: check_auth('CP0000000', None, one_of_roles=[EDIT_ROLE]) assert excinfo.exception.code == 403
def post(account_id): """Update the statement settings .""" current_app.logger.info('<AccountStatementsSettings.put') request_json = request.get_json() current_app.logger.debug(request_json) # TODO add valid formatting frequency = request_json.get('frequency') # Check if user is authorized to perform this action check_auth(business_identifier=None, account_id=account_id, contains_role=CHANGE_STATEMENT_SETTINGS, is_premium=True) try: response, status = ( StatementSettingsService.update_statement_settings( account_id, frequency), HTTPStatus.OK, ) except BusinessException as exception: return exception.response() current_app.logger.debug('>Payment.put') return jsonify(response), status
def get(account_id: str, statement_id: str): """Create the statement report.""" current_app.logger.info('<AccountStatementReport.post') response_content_type = request.headers.get('Accept', ContentType.PDF.value) # Check if user is authorized to perform this action auth = check_auth(business_identifier=None, account_id=account_id, contains_role=EDIT_ROLE, is_premium=True) report, report_name = StatementService.get_statement_report(statement_id=statement_id, content_type=response_content_type, auth=auth) response = Response(report, 200) response.headers.set('Content-Disposition', 'attachment', filename=report_name) response.headers.set('Content-Type', response_content_type) response.headers.set('Access-Control-Expose-Headers', 'Content-Disposition') return response
def post(): """Create the payment records.""" current_app.logger.info('<Payment.post') request_json = request.get_json() # Validate the input request valid_format, errors = schema_utils.validate(request_json, 'payment_request') if not valid_format: return jsonify({ 'code': 'PAY999', 'message': schema_utils.serialize(errors) }), HTTPStatus.BAD_REQUEST # Check if user is authorized to perform this action check_auth(request_json.get('businessInfo').get('businessIdentifier'), _jwt, contains_role=EDIT_ROLE) try: response, status = PaymentService.create_payment( request_json, g.jwt_oidc_token_info.get('preferred_username', None)), HTTPStatus.CREATED except BusinessException as exception: response, status = { 'code': exception.code, 'message': exception.message }, exception.status except ServiceUnavailableException as exception: response, status = { 'code': exception.status_code }, HTTPStatus.BAD_REQUEST current_app.logger.debug('>Payment.post') return jsonify(response), status
def _check_for_auth(dao, one_of_roles=ALL_ALLOWED_ROLES): # Check if user is authorized to perform this action check_auth(dao.business_identifier, one_of_roles=one_of_roles)
def test_auth_for_client_user_roles(session, public_user_mock): """Assert that the auth is working as expected.""" # Test one of roles check_auth('CP0001234', one_of_roles=[EDIT_ROLE]) # Test contains roles check_auth('CP0001234', contains_role=EDIT_ROLE)
def test_auth_for_client_user_roles_for_error(session, public_user_mock, roles, param_name): """Assert that the auth is working as expected.""" # Test for exception with pytest.raises(HTTPException) as excinfo: check_auth('CP0000000', param_name=roles) assert excinfo.exception.code == 403
def _check_for_auth(jwt, dao): # Check if user is authorized to perform this action check_auth(dao.account.corp_number, jwt, one_of_roles=ALL_ALLOWED_ROLES)