def editProduct(itemCode): response = Response() # Ensure user has permission for this endpoint userId = authenticateRequest(response, request) if response.hasError(): return response.getJson() # Ensure required input parameters are received required = [] optional = ['price'] data = checkVars(response, request.get_json(), required, optional, atLeastOneOptional=True) if response.hasError(): return response.getJson() if 'price' in data and not checkPrice(response, data['price']): return response.getJson() # Setup database connection and table con = mimsDbEng.connect() users = Table('users', MetaData(mimsDbEng), autoload=True) # Get the business reference of the business of the user making this request stm = select([users]).where(users.c.id == userId) businessId = con.execute(stm).fetchone()['business'] # Call the relevant get products function depending on business to get response data if businessId == 1: product = targetGetProduct(itemCode) if not product: return response.setError(18) response.data['item_code'] = targetEditProduct(itemCode, data) return response.getJson()
def test_get_aad_access_token_403(self, mock_post, mock_save, mock_secret, mock_conf, mock_proxy): db_utils = import_module('databricks_common_utils') mock_save.return_value = MagicMock() mock_secret.return_value = MagicMock() mock_conf. return_value = MagicMock() mock_proxy.side_effect = MagicMock() mock_post.side_effect = [Response(403), Response(403), Response(403)] return_val = db_utils.get_aad_access_token("session_key", "user_agent", retry=3) self.assertEqual (return_val, ("Client secret may have expired. Please configure a valid Client secret.", False)) self.assertEqual(mock_post.call_count, 3)
def getProductMovement(itemCode): response = Response() # Ensure user has permission for this endpoint userId = authenticateRequest(response, request) if response.hasError(): return response.getJson() # Ensure required input parameters are received required = [] optional = [] data = checkVars(response, request.values.to_dict(), required, optional) if response.hasError(): return response.getJson() startDate = datetime.datetime.combine(datetime.date.today(), datetime.time()) - datetime.timedelta(days=7) # Setup database connection and table con = mimsDbEng.connect() users = Table('users', MetaData(mimsDbEng), autoload=True) # Get the business reference of the business of the user making this request stm = select([users]).where(users.c.id == userId) businessId = con.execute(stm).fetchone()['business'] # Call the relevant get products function depending on business to get response data if businessId == 1: product = targetGetProduct(itemCode) if not product: return response.setError(18) response.data['product_movement'] = targetGetProductMovement(itemCode, startDate.date()) return response.getJson()
def login(): response = Response() # Ensure required input parameters are received required = ['username', 'password'] optional = [] data = checkVars(response, request.get_json(), required, optional) if response.hasError(): return response.getJson() # Setup database connection, table, and query con = mimsDbEng.connect() users = Table('users', MetaData(mimsDbEng), autoload=True) # Get user id of username passed in, also ensure user exists stm = select([users]).where(and_(users.c.username == data['username'], users.c.is_deleted == 0)) user = con.execute(stm).fetchone() con.close() if not user: return response.setError(2) # Verify that the password is valid if not verifyPassword(user['id'], data['password']): return response.setError(2) # Generate and attach access token to response data response.data['access_token'] = jwt.encode({ 'userId': user['id'] }, config['jwt']['secret'], algorithm='HS256').decode('utf-8') response.data['user_type'] = user['type'] return response.getJson()
def getProducts(): response = Response() # Ensure user has permission for this endpoint userId = authenticateRequest(response, request) if response.hasError(): return response.getJson() # Ensure required input parameters are received required = [] optional = ['name', 'item_code', 'plu', 'barcode', 'department', 'search_term', 'page_size', 'page'] data = checkVars(response, request.values.to_dict(), required, optional) if response.hasError(): return response.getJson() # Setup database connection and table con = mimsDbEng.connect() users = Table('users', MetaData(mimsDbEng), autoload=True) # Get the business reference of the business of the user making this request stm = select([users]).where(users.c.id == userId) businessId = con.execute(stm).fetchone()['business'] # Call the relevant get products function depending on business to get response data if businessId == 1: response.data['products'] = targetGetProducts(data) return response.getJson()
def test_get_api_response_refresh_token(self, mock_conf, mock_session, mock_proxy, mock_token, mock_version, mock_refresh): db_com = import_module('databricks_com') mock_conf.return_value = { "databricks_instance": "123", "auth_type": "AAD" } obj = db_com.DatabricksClient("session_key") obj.session.post.side_effect = [Response(403), Response(200)] resp = obj.databricks_api("post", "endpoint", args="123", data={"p1": "v1"}) self.assertEqual(obj.session.post.call_count, 2) self.assertEqual(resp, {"status_code": 200})
def test_get_api_response_refresh_token_error(self, mock_conf, mock_session, mock_proxy, mock_token, mock_version, mock_refresh): db_com = import_module('databricks_com') mock_conf.return_value = { "databricks_instance": "123", "auth_type": "AAD" } obj = db_com.DatabricksClient("session_key") obj.session.post.side_effect = [Response(403), Response(403)] with self.assertRaises(Exception) as context: resp = obj.databricks_api("post", "endpoint", args="123", data={"p1": "v1"}) self.assertEqual(obj.session.post.call_count, 2) self.assertEqual( "Invalid access token. Please enter the valid access token.", str(context.exception))
def test_get_api_response_get(self, mock_conf, mock_session, mock_proxy, mock_token, mock_version): db_com = import_module('databricks_com') mock_conf.return_value = { "databricks_instance": "123", "auth_type": "PAT" } obj = db_com.DatabricksClient("session_key") obj.session.get.return_value = Response(200) resp = obj.databricks_api("get", "endpoint", args="123") self.assertEqual(obj.session.get.call_count, 1) self.assertEqual(resp, {"status_code": 200})
def test_get_api_response_429(self, mock_conf, mock_session, mock_proxy, mock_token, mock_version): db_com = import_module('databricks_com') mock_conf.return_value = { "databricks_instance": "123", "auth_type": "PAT" } obj = db_com.DatabricksClient("session_key") obj.session.post.return_value = Response(429) with self.assertRaises(Exception) as context: resp = obj.databricks_api("post", "endpoint", args="123", data={"p1": "v1"}) self.assertEqual(obj.session.post.call_count, 1) self.assertEqual( "API limit exceeded. Please try again after some time.", str(context.exception))
class TestDatabricksUtils(unittest.TestCase): """Test Databricks Validators.""" @patch("databricks_validators.SessionKeyProvider", return_value=MagicMock()) @patch("databricks_validators.utils.get_proxy_uri", return_value="{}") @patch("splunk_aoblib.rest_migration.ConfigMigrationHandler", autospec=True) @patch("databricks_validators.Validator", autospec=True) @patch("databricks_validators.ValidateDatabricksInstance.validate_pat", autospec=True) @patch("databricks_validators.ValidateDatabricksInstance.validate_aad", autospec=True) def test_validate_pat(self, mock_aad, mock_pat, mock_validator, mock_conf, mock_proxy, mock_session): db_val = import_module('databricks_validators') db_val._LOGGER = MagicMock() db_val_obj = db_val.ValidateDatabricksInstance() mock_pat.return_value = True db_val_obj.validate("PAT", { "auth_type": "PAT", "databricks_access_token": "pat_token" }) self.assertEqual(mock_pat.call_count, 1) @patch("databricks_validators.SessionKeyProvider", return_value=MagicMock()) @patch("databricks_validators.utils.get_proxy_uri", return_value="{}") @patch("splunk_aoblib.rest_migration.ConfigMigrationHandler", autospec=True) @patch("databricks_validators.Validator.put_msg", return_value=MagicMock()) @patch("databricks_validators.ValidateDatabricksInstance.validate_pat", autospec=True) @patch("databricks_validators.ValidateDatabricksInstance.validate_aad", autospec=True) def test_validate_pat_error(self, mock_aad, mock_pat, mock_put, mock_conf, mock_proxy, mock_session): db_val = import_module('databricks_validators') db_val._LOGGER = MagicMock() db_val_obj = db_val.ValidateDatabricksInstance() db_val_obj.validate("PAT", {"auth_type": "PAT"}) mock_put.assert_called_once_with( "Field Databricks Access Token is required") @patch("databricks_validators.SessionKeyProvider", return_value=MagicMock()) @patch("databricks_validators.utils.get_proxy_uri", return_value="{}") @patch("splunk_aoblib.rest_migration.ConfigMigrationHandler", autospec=True) @patch("databricks_validators.Validator", autospec=True) @patch("databricks_validators.ValidateDatabricksInstance.validate_pat", autospec=True) @patch("databricks_validators.ValidateDatabricksInstance.validate_aad", autospec=True) def test_validate_aad(self, mock_aad, mock_pat, mock_validator, mock_conf, mock_proxy, mock_session): db_val = import_module('databricks_validators') db_val._LOGGER = MagicMock() db_val_obj = db_val.ValidateDatabricksInstance() mock_aad.return_value = True db_val_obj.validate( "PAT", { "auth_type": "AAD", "client_id": "cl_id", "client_secret": "cl_sec", "tenant_id": "tn_id" }) self.assertEqual(mock_aad.call_count, 1) @patch("databricks_validators.SessionKeyProvider", return_value=MagicMock()) @patch("databricks_validators.utils.get_proxy_uri", return_value="{}") @patch("splunk_aoblib.rest_migration.ConfigMigrationHandler", autospec=True) @patch("databricks_validators.Validator.put_msg", return_value=MagicMock()) @patch("databricks_validators.ValidateDatabricksInstance.validate_pat", autospec=True) @patch("databricks_validators.ValidateDatabricksInstance.validate_aad", autospec=True) def test_validate_aad_client_id_error(self, mock_aad, mock_pat, mock_put, mock_conf, mock_proxy, mock_session): db_val = import_module('databricks_validators') db_val._LOGGER = MagicMock() db_val_obj = db_val.ValidateDatabricksInstance() db_val_obj.validate("PAT", {"auth_type": "AAD"}) mock_put.assert_called_once_with("Field Client Id is required") @patch("databricks_validators.SessionKeyProvider", return_value=MagicMock()) @patch("databricks_validators.utils.get_proxy_uri", return_value="{}") @patch("splunk_aoblib.rest_migration.ConfigMigrationHandler", autospec=True) @patch("databricks_validators.Validator.put_msg", return_value=MagicMock()) @patch("databricks_validators.ValidateDatabricksInstance.validate_pat", autospec=True) @patch("databricks_validators.ValidateDatabricksInstance.validate_aad", autospec=True) def test_validate_aad_tenant_error(self, mock_aad, mock_pat, mock_put, mock_conf, mock_proxy, mock_session): db_val = import_module('databricks_validators') db_val._LOGGER = MagicMock() db_val_obj = db_val.ValidateDatabricksInstance() db_val_obj.validate("PAT", {"auth_type": "AAD", "client_id": "cl_id"}) mock_put.assert_called_once_with("Field Tenant Id is required") @patch("databricks_validators.SessionKeyProvider", return_value=MagicMock()) @patch("databricks_validators.utils.get_proxy_uri", return_value="{}") @patch("splunk_aoblib.rest_migration.ConfigMigrationHandler", autospec=True) @patch("databricks_validators.Validator.put_msg", return_value=MagicMock()) @patch("databricks_validators.ValidateDatabricksInstance.validate_pat", autospec=True) @patch("databricks_validators.ValidateDatabricksInstance.validate_aad", autospec=True) def test_validate_aad_client_secret_error(self, mock_aad, mock_pat, mock_put, mock_conf, mock_proxy, mock_session): db_val = import_module('databricks_validators') db_val._LOGGER = MagicMock() db_val_obj = db_val.ValidateDatabricksInstance() db_val_obj.validate("PAT", { "auth_type": "AAD", "client_id": "cl_id", "tenant_id": "tn_id" }) mock_put.assert_called_once_with("Field Client Secret is required") @patch("databricks_validators.Validator", autospec=True) @patch( "databricks_validators.ValidateDatabricksInstance.validate_db_instance", autospec=True) def test_validate_pat_function(self, mock_valid_inst, mock_validator): db_val = import_module('databricks_validators') db_val._LOGGER = MagicMock() db_val_obj = db_val.ValidateDatabricksInstance() mock_valid_inst.return_value = True db_val_obj.validate_pat({ "auth_type": "PAT", "databricks_access_token": "pat_token", "databricks_instance": "db_instance" }) mock_valid_inst.assert_called_once_with(db_val_obj, "db_instance", "pat_token") @patch("databricks_validators.utils.get_aad_access_token", return_value="access_token") @patch("databricks_validators.Validator", autospec=True) @patch( "databricks_validators.ValidateDatabricksInstance.validate_db_instance", autospec=True) def test_validate_aad_function(self, mock_valid_inst, mock_validator, mock_access): db_val = import_module('databricks_validators') db_val._LOGGER = MagicMock() db_val_obj = db_val.ValidateDatabricksInstance() db_val_obj._splunk_session_key = "session_key" db_val_obj._splunk_version = "splunk_version" db_val_obj._proxy_settings = {} mock_valid_inst.return_value = True db_val_obj.validate_aad({ "auth_type": "AAD", "client_id": "cl_id", "tenant_id": "tenant_id", "client_secret": "client_secret", "databricks_instance": "db_instance" }) mock_valid_inst.assert_called_once_with(db_val_obj, "db_instance", "access_token") @patch("databricks_validators.Validator.put_msg", return_value=MagicMock()) @patch("databricks_validators.utils.get_aad_access_token", return_value=("test", False)) @patch( "databricks_validators.ValidateDatabricksInstance.validate_db_instance", autospec=True) def test_validate_aad_function_error(self, mock_valid_inst, mock_access, mock_put): db_val = import_module('databricks_validators') db_val._LOGGER = MagicMock() db_val_obj = db_val.ValidateDatabricksInstance() db_val_obj._splunk_session_key = "session_key" db_val_obj._splunk_version = "splunk_version" db_val_obj._proxy_settings = {} mock_valid_inst.return_value = True db_val_obj.validate_aad({ "auth_type": "AAD", "client_id": "cl_id", "tenant_id": "tenant_id", "client_secret": "client_secret", "databricks_instance": "db_instance" }) mock_put.assert_called_once_with("test") self.assertEqual(mock_valid_inst.call_count, 0) @patch("databricks_validators.Validator.put_msg", return_value=MagicMock()) @patch("requests.get", return_value=Response(500)) def test_validate_instance_false(self, mock_get, mock_put): db_val = import_module('databricks_validators') db_val._LOGGER = MagicMock() db_val_obj = db_val.ValidateDatabricksInstance() db_val_obj._splunk_version = "splunk_version" db_val_obj._proxy_settings = {} ret_val = db_val_obj.validate_db_instance("instance", "token") mock_put.assert_called_once_with( "Internal server error. Cannot verify Databricks instance.") self.assertEqual(ret_val, False)
def createSale(): response = Response() # Ensure user has permission for this endpoint userId = authenticateRequest(response, request, mustBeManager=True) if response.hasError(): return response.getJson() # Ensure required input parameters are received required = ['items'] optional = [] data = checkVars(response, request.get_json(), required, optional) if response.hasError(): return response.getJson() for item in data['items']: # Ensure item is not missing required data if not 'item_code' in item or not 'amount' in item or not 'datetime' in item: return response.setError(23) # Ensure amount is formatted properly if not type(item['amount']) is int and not type( item['amount']) is float: return response.setError(21) # Ensure datetime is formatted properly try: datetime.datetime.strptime(item['datetime'], "%Y-%m-%d %H:%M:%S") except: return response.setError(22) # Setup database connection and table con = mimsDbEng.connect() users = Table('users', MetaData(mimsDbEng), autoload=True) # Get the business reference of the business of the user making this request stm = select([users]).where(users.c.id == userId) businessId = con.execute(stm).fetchone()['business'] # Call the relevant get products function depending on business to get response data if businessId == 1: # Ensure each item code is accurate for item in data['items']: product = targetGetProduct(item['item_code']) if not product: return response.setError(24) response.data['sale'] = targetCreateSale(data) return response.getJson()
def createInventoryTransaction(): response = Response() # Ensure user has permission for this endpoint userId = authenticateRequest(response, request, mustBeManager=False) if response.hasError(): return response.getJson() # Ensure required input parameters are received required = ['item_code', 'amount', 'unit', 'datetime'] optional = [] data = checkVars(response, request.get_json(), required, optional) if response.hasError(): return response.getJson() if not type(data['amount']) is int and not type(data['amount']) is float: return response.setError(21) try: datetime.datetime.strptime(data['datetime'], "%Y-%m-%d %H:%M:%S") except: return response.setError(22) # Setup database connection and table con = mimsDbEng.connect() users = Table('users', MetaData(mimsDbEng), autoload=True) # Get the business reference of the business of the user making this request stm = select([users]).where(users.c.id == userId) businessId = con.execute(stm).fetchone()['business'] # Call the relevant get products function depending on business to get response data if businessId == 1: product = targetGetProduct(data['item_code']) if not product: return response.setError(18) unit = targetGetUnit(data['unit']) if not unit: return response.setError(20) response.data[ 'inventory_transaction'] = targetCreateInventoryTransaction(data) return response.getJson()
from django.contrib.sites.shortcuts import get_current_site from django.core.mail import send_mail from django.http import HttpResponse, request from django.shortcuts import render, redirect from django.urls import reverse from rest_framework.generics import GenericAPIView from .serializer import LoginSerializer, ResetSerializer, UserSerializer, ForgotSerializer from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string from django.utils.html import strip_tags from fundoonotes.settings import file_handler, AUTH_ENDPOINT from utility import Crypto from utility import Response obj = Crypto() obj1 = Response() logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) logger.addHandler(file_handler) class Login(GenericAPIView): serializer_class = LoginSerializer def post(self, request): """ :param APIView: -------------- user request is made from the user :return: --------
def createUser(): response = Response() # Ensure user has permission for this endpoint userId = authenticateRequest(response, request, mustBeManager=True) if response.hasError(): return response.getJson() # Ensure required input parameters are received required = ['username', 'first_name', 'last_name', 'password', 'type'] optional = [] data = checkVars(response, request.get_json(), required, optional) if response.hasError(): return response.getJson() # Setup database connection and table con = mimsDbEng.connect() users = Table('users', MetaData(mimsDbEng), autoload=True) # Select the business of this manager so we know what business to make # the user for stm = select([users]).where(users.c.id == userId) businessId = con.execute(stm).fetchone()['business'] # Check username validity if not checkUsername(response, data['username']): return response.getJson() # Check validity of type if not checkUserType(response, data['type']): return response.getJson() # Ensure username is not already taken stm = select([users]).where(users.c.username == data['username']) if con.execute(stm).fetchone(): return response.setError(7) # Check password validity if not checkPassword(response, data['password']): return response.getJson() # Hash password to store in database hashedPassword = hashPassword(data['password']) # Create user stm = users.insert().values(username=data['username'], password_hash=hashedPassword, first_name=data['first_name'], last_name=data['last_name'], type=data['type'], business=businessId) result = con.execute(stm) con.close() # Attach newly created user id to response data response.data['user_id'] = result.lastrowid return response.getJson()
def getUsers(): response = Response() # Ensure user has permission for this endpoint userId = authenticateRequest(response, request, mustBeManager=True) if response.hasError(): return response.getJson() # Ensure required input parameters are received required = [] optional = [ 'username', 'first_name', 'last_name', 'search_term', 'type', 'page_size', 'page' ] data = checkVars(response, request.values.to_dict(), required, optional) if response.hasError(): return response.getJson() # Setup database connection and table con = mimsDbEng.connect() users = Table('users', MetaData(mimsDbEng), autoload=True) # Get business of user making request stm = select([users]).where(users.c.id == userId) userBusiness = con.execute(stm).fetchone()['business'] # Setup main select statement stm = select([users]).where( and_(users.c.business == userBusiness, users.c.is_deleted == 0)) # Handle optional filters if 'username' in data: stm = stm.where(users.c.username.like('%' + data['username'] + '%')) if 'first_name' in data: stm = stm.where(users.c.first_name.like('%' + data['first_name'] + '%')) if 'last_name' in data: stm = stm.where(users.c.last_name.like('%' + data['last_name'] + '%')) if 'type' in data: stm = stm.where(users.c.type == data['type']) # Handle search_term if 'search_term' in data: search_term = '%' + data['search_term'] + '%' stm = stm.where( or_( users.c.first_name.like(search_term), users.c.last_name.like(search_term), users.c.username.like(search_term), func.concat(users.c.first_name, ' ', users.c.last_name).like(search_term))) # Handle page_size and page stm = setPagination(stm, data) response.data['users'] = resultSetToJson( con.execute(stm).fetchall(), [ 'password_hash', 'business', 'is_deleted', 'updated_datetime', 'creation_datetime' ]) con.close() for item in response.data['users']: item['id'] = int(item['id']) item['type'] = int(item['type']) return response.getJson()
def editUser(userIdToEdit): response = Response() # Ensure user has permission for this endpoint userId = authenticateRequest(response, request) if response.hasError(): return response.getJson() # Ensure required input parameters are received required = [] optional = [ 'username', 'first_name', 'last_name', 'new_password', 'current_password', 'type', 'is_deleted' ] data = checkVars(response, request.get_json(), required, optional, atLeastOneOptional=True) if response.hasError(): return response.getJson() # Setup database connection and table con = mimsDbEng.connect() users = Table('users', MetaData(mimsDbEng), autoload=True) # Ensure user exists stm = select([users]).where(users.c.id == userIdToEdit) userToEdit = con.execute(stm).fetchone() if not userToEdit: return response.setError(11) # Get user making request stm = select([users]).where(users.c.id == userId) userMakingRequest = con.execute(stm).fetchone() # Permission checking for if user making request is manager if userMakingRequest['type'] == 1: # Ensure user making request is in same business as user being editted, if not, permission denied if userMakingRequest['business'] != userToEdit['business']: return response.setError(6) elif userMakingRequest['type'] == 2: # User is employee, permission checking for if user is employee # Ensure they are editing themselves, if not, permission denied if userId != userToEdit['id']: return response.setError(6) # Ensure they are not trying to edit type or is_deleted if 'type' in data or 'is_deleted' in data: return response.setError(6) # If they are trying to set a new password if 'new_password' in data: # Ensure they passed in their current password if not 'current_password' in data: return response.setError(13) # Verify current password if not verifyPassword(userIdToEdit, data['current_password']): return response.setError(14) # Check validity of username if set if 'username' in data: # Check username validity if not checkUsername(response, data['username']): return response.getJson() # Ensure username is not already taken stm = select([users]).where( and_(users.c.username == data['username'], users.c.id != userIdToEdit)) if con.execute(stm).fetchone(): return response.setError(7) # Check validity of type if set if 'type' in data: if not checkUserType(response, data['type']): return response.getJson() # Check validity of is_deleted if set if 'is_deleted' in data: if not type(data['is_deleted']) is bool: return response.setError(16) # Handle new password hashing and validity hashedNewPassword = None if 'new_password' in data: # Check validity of new password if not checkPassword(response, data['new_password']): return response.getJson() # Hash new password to store in database hashedNewPassword = hashPassword(data['new_password']) # Main update statement stm = users.update().where(users.c.id == userIdToEdit) # Check potential passed in params to update if 'username' in data: stm = stm.values(username=data['username']) if 'first_name' in data: stm = stm.values(first_name=data['first_name']) if 'last_name' in data: stm = stm.values(last_name=data['last_name']) if 'new_password' in data: stm = stm.values(password_hash=hashedNewPassword) if 'type' in data: stm = stm.values(type=data['type']) if 'is_deleted' in data: stm = stm.values(is_deleted=data['is_deleted']) result = con.execute(stm) con.close() # Attach newly created user id to response data response.data['user_id'] = int(userIdToEdit) return response.getJson()