def add_resources(): """ Adding Resources """ params = input( 'Provide Resource Details in Json Format Example i .e\n {"resource_name": "Backend Repository", "description": "test"}\n' ) try: params = json.loads(params) request_validator = req_validators.validate_resource_request(params) if not request_validator.get('status'): return request_validator conn_init = db_conn.InitDbConnection() conn = conn_init.open_connection() cr = conn.cursor() params = request_validator.get('params') import pdb pdb.set_trace() # Creating Resources cr.execute( db_query.INSERT_RECORD_QUERY.format( table_name='resources', col_name=db_query.RESOURCE_COL, values=(params.get('resource_name'), params.get('description', ""), params.get('created_by_id')))) conn.commit() conn.close() return {"status": True, "message": "Sucessfully Created Resouces"} except Exception as e: return { 'status': False, 'error': 'Invalid Request Format, Expecting JSON.' + str(e) }
def register_user(): """ Registering User as Admin in the system """ params = input('Provide User Details in Json Format Example\n'\ '{"name": "Naresh", "email": "*****@*****.**", "password": "******"}\n') try: params = json.loads(params) request_validator = req_validators.validate_register_user_params( params) if not request_validator.get('status'): return request_validator # Registering User Here conn_init = db_conn.InitDbConnection() conn = conn_init.open_connection() cr = conn.cursor() cr.execute( db_query.INSERT_RECORD_QUERY.format( table_name='user', col_name=db_query.USER_COL_NAME, values=(params.get('name'), params.get('email'), params.get('password'), params.get('mobile', ''), 'True'))) conn.commit() conn.close() return {'status': True, 'message': 'Sucessfully Created User!'} except Exception as e: return {'status': False, 'error': 'Invalid Request Format.' + str(e)}
def delete_resource(): """Reading Resources""" params = input( 'Provide Your Credentails i .e\n {"email": "*****@*****.**", "password": "******"}\n' ) user_details = req_validators.get_valid_user_details(params) if not user_details.get('status'): return user_details logged_in_user_id = user_details.get('data')[0] resource_id = int(input('Enter Resource Id - ')) conn_init = db_conn.InitDbConnection() conn = conn_init.open_connection() cr = conn.cursor() resource_details = cr.execute( 'select role_id from resourcesaccess where resource_id={res_id} and user_id={user_id}' .format(res_id=resource_id, user_id=logged_in_user_id)).fetchone() if not resource_details: return { 'status': False, 'error': "This Resource is not allowed to access you." } action_allow = cr.execute( 'select * from role where id={role_id} and is_deletable="true"'.format( role_id=resource_details[0])) if not action_allow: { 'status': False, 'error': "You do not have Permission to Read this resource.." } return {'status': True, "message": "Action Completed."} return
def add_role(): """ Adding Role """ params = input('Provide Role Details in Json Format Example\n'\ '{"role": "Commiter", "is_readable": true, "is_writable": false, "is_deletable": true}\n') try: params = json.loads(params) request_validator = req_validators.validate_add_role_params(params) if not request_validator.get('status'): return request_validator conn_init = db_conn.InitDbConnection() conn = conn_init.open_connection() cr = conn.cursor() params = request_validator.get('params') cr.execute( db_query.INSERT_RECORD_QUERY.format( table_name='role', col_name=db_query.ROLE_COL, values=(params.get('role'), str(params.get('is_readable', False)), str(params.get('is_writable', False)), str(params.get('is_deletable', False)), params.get('created_by_id')))) conn.commit() conn.close() return {"status": True, "message": "Sucessfully Added Role"} except Exception as e: return { 'status': False, 'error': 'Invalid Request Format, Expecting JSON.' + str(e) }
def validate_assign_resources(params, logged_in_user_id): """Validating Request Params""" try: resource_id = params['resource_id'] role_id = params['role_id'] email = params['email'] except Exception as e: return {'status': False, 'error': 'Field Required {}'.format(str(e))} conn_init = db_conn.InitDbConnection() conn = conn_init.open_connection() cr = conn.cursor() if not cr.execute( 'select * from resources where id={resource_id} and created_by_id={created_by_id}' .format(resource_id=params['resource_id'], created_by_id=logged_in_user_id)).fetchall(): return {'status': False, 'error': 'Resource does not belong to You.'} if not cr.execute( 'select * from role where id={role_id} and created_by_id={created_by_id}' .format(role_id=params['role_id'], created_by_id=logged_in_user_id)).fetchall(): return {'status': False, 'error': 'Role does not belong to You.'} assign_user = cr.execute( 'select * from user where email="{email_id}" and id!={user_id}'.format( email_id=params['email'], user_id=logged_in_user_id)).fetchone() if not assign_user: return {'status': False, 'error': 'Invalid User.'} params['assign_user_id'] = assign_user[0] return {'status': True, 'params': params}
def get_valid_user_details(user_password_params): """ Validating the Users """ try: user_password_params = json.loads(user_password_params) email = user_password_params['email'] password = user_password_params['password'] except Exception as e: return {'status': False, 'error': 'Field Required {}'.format(str(e))} conn_init = db_conn.InitDbConnection() conn = conn_init.open_connection() cr = conn.cursor() user_details = cr.execute( "select * from user where email = '{email}' and password = '******'" .format(email=user_password_params.get('email'), password=user_password_params.get('password'))).fetchone() if not user_details: return {'status': False, 'error': 'Invalid Credentails.'} return {'status': True, 'data': user_details}
def validate_register_user_params(params): """ Validating Register User Params """ # Try Catch validates for the required Fields try: name = params['name'], email = params['email'], password = params['password'] except Exception as e: return {'status': False, 'error': 'Field Required {}'.format(str(e))} # Validation Email req = re.compile('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$') if not req.match(params.get('email')): return {'status': False, 'error': 'Provide Vaild Email Id.'} conn_init = db_conn.InitDbConnection() conn = conn_init.open_connection() cr = conn.cursor() if cr.execute("select * from user where email = '{email}'".format( email=params.get('email'))).fetchall(): return {'status': False, 'error': 'Email Already Exists!'} return {'status': True}
def assign_resource(): """ Assigning Resources to User """ params = input( 'Provide Your Credentails i .e\n {"email": "*****@*****.**", "password": "******"}\n' ) user_details = req_validators.get_valid_user_details(params) if not user_details.get('status'): return user_details logged_in_user_id = user_details.get('data')[0] conn_init = db_conn.InitDbConnection() conn = conn_init.open_connection() cr = conn.cursor() resources = cr.execute( 'select id, resource_name from resources where created_by_id = {created_by_id}' .format(created_by_id=logged_in_user_id)).fetchall() if not resources: return { 'status': False, 'message': 'No Resource Available For You, Create Resource by using CMD addresource' } users = cr.execute('select name, email from user').fetchall() role = cr.execute( 'select id, role from role where created_by_id = {}'.format( logged_in_user_id)).fetchall() assign_resource_user_params = input( 'Provide Resources ID, Role ID and Email from Avialability i.e '\ '"resource_id": 1, "role_id": 1, "email": "*****@*****.**"\n\n'\ 'Avaiable Resocues - {resources}\n'\ 'Available Roles - {role}\n'\ 'Available Users {users}\n'.format( resources=resources, role=role, users=users )) try: params = json.loads(assign_resource_user_params) except Exception as e: return {'status': False, 'error': 'Need Json ' + str(e)} request_validator = req_validators.validate_assign_resources( params, logged_in_user_id) if not request_validator.get('status'): return request_validator # Assigning Resource cr.execute( db_query.INSERT_RECORD_QUERY.format( table_name='resourcesaccess', col_name=('resource_id', 'user_id', 'role_id'), values=(params.get('resource_id'), params.get('assign_user_id'), params.get('role_id')))) cr.execute( db_query.INSERT_RECORD_QUERY.format( table_name='userrole', col_name=('role_id', 'user_id'), values=(params.get('role_id'), params.get('assign_user_id')))) conn.commit() return { "status": True, "message": "Sucessfully Assigned Resource and Role To User." }
from conf import constants as const from resources.utils import * def execute_command(cmd_name): """ Executing Command Provided by User """ if cmd_name not in const.COMMANDS.values(): return { 'status': False, 'error': 'Invalid Command Line!'} success_response = eval(const.COMMAND_EXECUTION.get(cmd_name)) return success_response if __name__ == '__main__': db_connection = db_conn.InitDbConnection() parser = argparse.ArgumentParser( prog='Role Based Access System', usage='Usage: Pass the Command To Access the Features', description=const.DESCRIPTION, epilog='Copyrights @Naresh Yadav | 8123961170', add_help=True) parser.add_argument( "cmd_name", type=str, metavar="Regitser User --> regu\n Add Role --> addrole") cmd_name = parser.parse_args().cmd_name res = execute_command(cmd_name) print(res)