def get_graph_values(request, equipment_name, module_name): """ This will return the graph data for the selected module :return: Json Response """ try: loggedin_user_details = _TokenValidation.validate_token(request) if loggedin_user_details: if equipment_name == COKE_DRUM_VALUE and module_name == PDI_VALUE: return JsonResponse(pdi_graph.get_pdi_graph(request, equipment_name, module_name), safe=False) if equipment_name == FURNACE_VALUE and (module_name == PASS_A_VALUE or module_name == PASS_B_VALUE): return JsonResponse(furnace_graph.get_furnace_graph(request, equipment_name, module_name), safe=False) if equipment_name == FURNACE_VALUE and (module_name == SPALL_PASS_A_VALUE or module_name == SPALL_PASS_B_VALUE): return JsonResponse(furnace_spall_graph.get_furnace_spall_graph(request, equipment_name, module_name), safe=False) if equipment_name == COKE_DRUM_VALUE and module_name == OUTAGE_VALUE: return JsonResponse(outage_graph.get_outage_graph(request, equipment_name, module_name), safe=False) if equipment_name == COKE_DRUM_VALUE and module_name == HGI_VALUE: return JsonResponse(hgi_graph.get_hgi_graph(request, equipment_name, module_name), safe=False) else: return JsonResponse("This equipment is not registered with us!", safe=False) except jwt.ExpiredSignatureError: token = request.META[HTTP_AUTHORIZATION_TOKEN].split(" ")[1] role = jwt.decode(token, verify=False) ob = HashingSalting() if role['role'] == 'Admin': ob.decreasing_admin_login_count() if role['role'] == 'Non Admin': ob.decreasing_Non_Admin_login_count() if role['role'] == 'Super Admin': ob.decreasing_super_Admin_login_count() return JsonResponse({MESSAGE_KEY: "Token Expired"}, status=HTTP_401_UNAUTHORIZED)
def __change_user_password_query(self): """ This function will execute the query for change the user password :return: Json object """ if DEVELOPMENT: self._psql_session.execute( USER_AUTHETICATION_QUERY.format( self.loggedin_userid_details[LOGGEDINUSEREMAIL_KEY])) else: self._psql_session.execute( USER_PROD_AUTHETICATION_QUERY.format( self.loggedin_userid_details[LOGGEDINUSEREMAIL_KEY])) if not self._psql_session.rowcount: return JsonResponse({MESSAGE_KEY: USERNAME_NOT_REGISTERED}, status=HTTP_400_BAD_REQUEST) obj = HashingSalting() result_set = self._psql_session.fetchone() if obj.check_password(self._request_payload[USERPASSWORD_KEY], result_set[SALT_KEY], result_set[USERPASSWORD_KEY]): hash_value, salt_value = obj.get_hashed_password( self._request_payload[USERFUTUREPASSWORD_KEY]) if ENV: self._psql_session.execute( CHANGE_RESET_USER_PASSWORD_QUERY.format( SALT_KEY, salt_value, USERPASSWORD_KEY, hash_value, USERID_KEY, self.loggedin_userid_details[LOGGEDINUSERID_KEY])) else: self._psql_session.execute( CHANGE_RESET_USER_PROD_PASSWORD_QUERY.format( SALT_KEY, salt_value, USERPASSWORD_KEY, hash_value, USERID_KEY, self.loggedin_userid_details[LOGGEDINUSERID_KEY])) if self._psql_session.rowcount: return JsonResponse({MESSAGE_KEY: CHANGED_SUCCESSFULLY}) return JsonResponse({MESSAGE_KEY: RESET_ERROR}, status=HTTP_400_BAD_REQUEST) return JsonResponse({MESSAGE_KEY: PASSWORD_WRONG}, status=HTTP_400_BAD_REQUEST)
def update_user(request): """ This function will update the existing user :param request: request django object :return: jsonobject """ obj = None try: if request.method == PUT_REQUEST: loggedin_user_details = _TokenValidation.validate_token(request) r_name = loggedin_user_details['role'] names = ['Super Admin', 'Admin'] if r_name in names: if loggedin_user_details: request_payload = _RequestValidation().validate_request( request, [ USERID_KEY, NAME, LOGIN_ID, USEREMAIL_KEY, DESIGNATION, USER_TYPE, EAMIL_NOTIFICATION ]) obj = UpdateUser(loggedin_user_details, request_payload) return obj.update_user() else: return JsonResponse({MESSAGE_KEY: "FORBIDDEN ERROR"}, status=HTTP_403_FORBIDDEN) log_debug(METHOD_NOT_ALLOWED) return json_MethodNotAllowed except jwt.ExpiredSignatureError: token = request.META[HTTP_AUTHORIZATION_TOKEN].split(" ")[1] role = jwt.decode(token, verify=False) ob = HashingSalting() if role['role'] == 'Admin': ob.decreasing_admin_login_count() if role['role'] == 'Non Admin': ob.decreasing_Non_Admin_login_count() if role['role'] == 'Super Admin': ob.decreasing_super_Admin_login_count() return JsonResponse({MESSAGE_KEY: "Token Expired"}, status=HTTP_401_UNAUTHORIZED) except Exception as e: excMsg = "update_users_data API : " + str(error_instance(e)) return excMsg finally: if obj: del obj
def get_revenue_graph(request, equipment_name=None, module_name=None): """ This function will return the revenue loss data for the overhead pdi module :param module_name: module name :param equipment_name: equipment name :param request: request django object :return: json response """ query_params, obj = None, None try: query_params = { TAG_NAME_REQUEST: request.GET[TAG_NAME_REQUEST], START_DATE_REQUEST: request.GET[START_DATE_REQUEST], END_DATE_REQUEST: request.GET[END_DATE_REQUEST] } except: pass try: if request.method == GET_REQUEST: loggedin_user_details = _TokenValidation.validate_token(request) if loggedin_user_details: obj = RevenueGraph(query_params, equipment_name, module_name) return obj.get_values() log_debug(METHOD_NOT_ALLOWED) return JsonResponse({MESSAGE_KEY: METHOD_NOT_ALLOWED}, status=HTTP_405_METHOD_NOT_ALLOWED) except jwt.ExpiredSignatureError: token = request.META[HTTP_AUTHORIZATION_TOKEN].split(" ")[1] role = jwt.decode(token, verify=False) ob = HashingSalting() if role['role'] == 'Admin': ob.decreasing_admin_login_count() if role['role'] == 'Non Admin': ob.decreasing_Non_Admin_login_count() if role['role'] == 'Super Admin': ob.decreasing_super_Admin_login_count() return JsonResponse({MESSAGE_KEY: "Token Expired"}, status=HTTP_401_UNAUTHORIZED) except Exception as e: return error_instance(e) finally: if obj: del obj
def get_logout_user(self): try: token = self._request_payload[TOKEN] role = jwt.decode(token, verify=False) obj = HashingSalting() if role['role'] == 'Admin': obj.decreasing_admin_login_count() if role['role'] == 'Non Admin': obj.decreasing_Non_Admin_login_count() if role['role'] == 'Super Admin': obj.decreasing_super_Admin_login_count() return JsonResponse({MESSAGE_KEY: "Logout Successfully"}) except Exception as e: log_error(e)
def __reset_user_password_query(self): """ This function will execute the query for resetting the user password :return: Json object """ try: with transaction.atomic(): """ Future use """ # self._psql_session.execute(CHECK_USER_EXISTANCE_QUERY.format(self._request_payload[USERNAME_KEY])) if not self._psql_session.rowcount: return JsonResponse({MESSAGE_KEY: USERNAME_NOT_REGISTERED}, status=HTTP_400_BAD_REQUEST) obj = HashingSalting() hash, salt = obj.get_hashed_password( self._request_payload[USERPASSWORD_KEY]) self._psql_session.execute( CHANGE_RESET_USER_PASSWORD_QUERY.format( SALT_KEY, salt, USERPASSWORD_KEY, hash, USERNAME_KEY, self._request_payload[USERNAME_KEY])) if not self._psql_session.rowcount: return JsonResponse({MESSAGE_KEY: CHANGE_ERROR}, status=HTTP_400_BAD_REQUEST) return JsonResponse({MESSAGE_KEY: RESET_SUCCESSFULLY}) except IntegrityError as e: log_error(traceback.format_exc()) return JsonResponse({MESSAGE_KEY: traceback.format_exc()}, status=HTTP_500_INTERNAL_SERVER_ERROR) except Exception as e: log_error(traceback.format_exc()) return JsonResponse( {MESSAGE_KEY: INTERNAL_ERROR.format(traceback.format_exc())}, status=HTTP_500_INTERNAL_SERVER_ERROR)
def get_outage_multiline(request, equipment_name=None, module_name=None): """ This function will return the outage multiline graph data :param module_name: module name :param equipment_name: equipment name :param request: request django object :return: json response """ query_params, obj = None, None try: query_params = request except: pass try: if request.method == GET_REQUEST: loggedin_user_details = _TokenValidation.validate_token(request) if loggedin_user_details: obj = OutageMultiLine(query_params, equipment_name, module_name) return obj.get_values() log_debug(METHOD_NOT_ALLOWED) return JsonResponse({MESSAGE_KEY: METHOD_NOT_ALLOWED}, status=HTTP_405_METHOD_NOT_ALLOWED) except jwt.ExpiredSignatureError: token = request.META[HTTP_AUTHORIZATION_TOKEN].split(" ")[1] role = jwt.decode(token, verify=False) ob = HashingSalting() if role['role'] == 'Admin': ob.decreasing_admin_login_count() if role['role'] == 'Non Admin': ob.decreasing_Non_Admin_login_count() if role['role'] == 'Super Admin': ob.decreasing_super_Admin_login_count() return JsonResponse({MESSAGE_KEY: "Token Expired"}, status=HTTP_401_UNAUTHORIZED) except Exception as e: excMsg = "get_outage_multi_line_graph_data API : " + str( error_instance(e)) return excMsg finally: if obj: del obj
def download_algorithm_file(request, algorithm_name): """ This function will download csv, xml files and will return error if generated. :param request: request django object :param algorithm_name : this will have the algorithm name :return: json response """ query_params = obj = None try: query_params = {FILES_NAME_REQUEST: request.GET[FILES_NAME_REQUEST]} except: pass try: if request.method == GET_REQUEST: loggedin_user_details = _TokenValidation.validate_token(request) permissions = loggedin_user_details['permissions']['Settings'] permission_name = 'Upload/Download Configuration Files' if permission_name in permissions: if loggedin_user_details: obj = DownloadAlgorithmFile(algorithm_name, query_params) return obj.download_file() else: return JsonResponse({MESSAGE_KEY: "Forbidden Error"}, status=HTTP_403_FORBIDDEN) log_debug(METHOD_NOT_ALLOWED) return json_MethodNotAllowed except jwt.ExpiredSignatureError: token = request.META[HTTP_AUTHORIZATION_TOKEN].split(" ")[1] role = jwt.decode(token, verify=False) ob = HashingSalting() if role['role'] == 'Admin': ob.decreasing_admin_login_count() if role['role'] == 'Non Admin': ob.decreasing_Non_Admin_login_count() if role['role'] == 'Super Admin': ob.decreasing_super_Admin_login_count() return JsonResponse({MESSAGE_KEY: "Token Expired"}, status=HTTP_401_UNAUTHORIZED) except Exception as e: return error_instance(e) finally: if obj: del obj
def get_algorithm_list(request, algorithm_name=None): """ This function will return the algorithm list and will return error if generated. :param request: request django object :param algorithm_name : this either can be none or else it will have the algorithm name :return: json response """ obj = None try: if request.method == GET_REQUEST: loggedin_user_details = _TokenValidation.validate_token(request) r_name = loggedin_user_details['role'] names = ['Super Admin'] if r_name in names: if loggedin_user_details: obj = AllAlgorithmList() if algorithm_name: return obj.get_file_data_by_algorithm_name( algorithm_name) else: return obj.get_algorithms_details() else: return JsonResponse({MESSAGE_KEY: "Forbidden Error"}, status=HTTP_403_FORBIDDEN) log_debug(METHOD_NOT_ALLOWED) return json_MethodNotAllowed except jwt.ExpiredSignatureError: token = request.META[HTTP_AUTHORIZATION_TOKEN].split(" ")[1] role = jwt.decode(token, verify=False) ob = HashingSalting() if role['role'] == 'Admin': ob.decreasing_admin_login_count() if role['role'] == 'Non Admin': ob.decreasing_Non_Admin_login_count() if role['role'] == 'Super Admin': ob.decreasing_super_Admin_login_count() return JsonResponse({MESSAGE_KEY: "Token Expired"}, status=HTTP_401_UNAUTHORIZED) except Exception as e: excMsg = "get_access_list API : " + str(error_instance(e)) return excMsg finally: if obj: del obj
def update_access_configuration(request): """ This function will update the Access of users details with the passed json values. :param request: request django object :return: json response """ obj = None try: if request.method == PUT_REQUEST: request_payload = json.loads(request.body.decode(UTF8_FORMAT)) loggedin_user_details = _TokenValidation.validate_token(request) r_name = loggedin_user_details['role'] names = ['Super Admin'] if r_name in names: if loggedin_user_details: request_payload = _RequestValidation().validate_request( request, request_payload) obj = AccessUpdate(request_payload) return obj.update_access() else: return JsonResponse({MESSAGE_KEY: "FORBIDDEN ERROR"}, status=HTTP_403_FORBIDDEN) log_debug(METHOD_NOT_ALLOWED) return json_MethodNotAllowed except jwt.ExpiredSignatureError: token = request.META[HTTP_AUTHORIZATION_TOKEN].split(" ")[1] role = jwt.decode(token, verify=False) ob = HashingSalting() if role['role'] == 'Admin': ob.decreasing_admin_login_count() if role['role'] == 'Non Admin': ob.decreasing_Non_Admin_login_count() if role['role'] == 'Super Admin': ob.decreasing_super_Admin_login_count() return JsonResponse({MESSAGE_KEY: "Token Expired"}, status=HTTP_401_UNAUTHORIZED) except Exception as e: excMsg = "Access_Update API : " + str(error_instance(e)) return excMsg finally: if obj: del obj
def download_notifications_data(request): """ This function will download the notifications from the database :param request: request django object :return: json response """ query_params, obj = None, None try: query_params = request except: pass try: if request.method == GET_REQUEST: loggedin_user_details = _TokenValidation.validate_token(request) if loggedin_user_details: obj = Notifications(loggedin_user_details, query_params) return obj.get_notifications(request) else: return JsonResponse({MESSAGE_KEY: "FORBIDDEN ERROR"}, status=HTTP_403_FORBIDDEN) log_debug(METHOD_NOT_ALLOWED) return json_MethodNotAllowed except jwt.ExpiredSignatureError: token = request.META[HTTP_AUTHORIZATION_TOKEN].split(" ")[1] role = jwt.decode(token, verify=False) ob = HashingSalting() if role['role'] == 'Admin': ob.decreasing_admin_login_count() if role['role'] == 'Non Admin': ob.decreasing_Non_Admin_login_count() if role['role'] == 'Super Admin': ob.decreasing_super_Admin_login_count() return JsonResponse({MESSAGE_KEY: "Token Expired"}, status=HTTP_401_UNAUTHORIZED) except Exception as e: excMsg = "get_notifications API : " + str(error_instance(e)) return excMsg finally: if obj: del obj
def update_algorithm_params(request): """ This function will update the algorithm with the passed json values. :param request: request django object :param algorithm_name : this either can be none or else it will have the algorithm name :return: json response """ obj = None try: if request.method == PUT_REQUEST: loggedin_user_details = _TokenValidation.validate_token(request) permissions = loggedin_user_details['permissions']['Settings'] permission_name = 'Module On/OFF' if permission_name in permissions: if loggedin_user_details: request_payload = json.loads( request.body.decode(UTF8_FORMAT)) obj = UpdateAlgorithmParams(request_payload) return obj.update_algorithms() else: return JsonResponse({MESSAGE_KEY: "Forbidden Error"}, status=HTTP_403_FORBIDDEN) log_debug(METHOD_NOT_ALLOWED) return json_MethodNotAllowed except jwt.ExpiredSignatureError: token = request.META[HTTP_AUTHORIZATION_TOKEN].split(" ")[1] role = jwt.decode(token, verify=False) ob = HashingSalting() if role['role'] == 'Admin': ob.decreasing_admin_login_count() if role['role'] == 'Non Admin': ob.decreasing_Non_Admin_login_count() if role['role'] == 'Super Admin': ob.decreasing_super_Admin_login_count() return JsonResponse({MESSAGE_KEY: "Token Expired"}, status=HTTP_401_UNAUTHORIZED) except Exception as e: return error_instance(e) finally: if obj: del obj
def get_user_data(request): """ This function will get the values for the equipment level as well as console level dynamic benchmarking :param request: request django object :param unit: unit name :param console: console name will be provided :param equipment: equipment name will be provided :return: json response """ obj = None try: if request.method == GET_REQUEST: loggedin_user_details = _TokenValidation.validate_token(request) r_name = loggedin_user_details['role'] names = ['Super Admin'] if r_name in names: if loggedin_user_details: obj = user_get() return obj.get_user_values() else: return JsonResponse({MESSAGE_KEY: "FORBIDDEN ERROR"}, status=HTTP_403_FORBIDDEN) log_debug(METHOD_NOT_ALLOWED) return json_MethodNotAllowed except jwt.ExpiredSignatureError: token = request.META[HTTP_AUTHORIZATION_TOKEN].split(" ")[1] role = jwt.decode(token, verify=False) ob = HashingSalting() if role['role'] == 'Admin': ob.decreasing_admin_login_count() if role['role'] == 'Non Admin': ob.decreasing_Non_Admin_login_count() if role['role'] == 'Super Admin': ob.decreasing_super_Admin_login_count() return JsonResponse({MESSAGE_KEY: "Token Expired"}, status=HTTP_401_UNAUTHORIZED) except Exception as e: excMsg = "get_all_users_data API : " + str(error_instance(e)) return excMsg finally: if obj: del obj
def delete_user(request, login_id=None): """ This function will delete the existing user :param login_id: it will give the log_in id of the deleting user :param request: request django object :param username : username that need to be deleted :return: json object """ obj = None try: if request.method == DELETE_REQUEST: loggedin_user_details = _TokenValidation.validate_token(request) r_name = loggedin_user_details['role'] names = ['Super Admin'] if r_name in names: if loggedin_user_details: obj = DeleteUser(loggedin_user_details, login_id) return obj.delete_user() else: return JsonResponse({MESSAGE_KEY: "FORBIDDEN ERROR"}, status=HTTP_403_FORBIDDEN) log_debug(METHOD_NOT_ALLOWED) return json_MethodNotAllowed except jwt.ExpiredSignatureError: token = request.META[HTTP_AUTHORIZATION_TOKEN].split(" ")[1] role = jwt.decode(token, verify=False) ob = HashingSalting() if role['role'] == 'Admin': ob.decreasing_admin_login_count() if role['role'] == 'Non Admin': ob.decreasing_Non_Admin_login_count() if role['role'] == 'Super Admin': ob.decreasing_super_Admin_login_count() return JsonResponse({MESSAGE_KEY: "Token Expired"}, status=HTTP_401_UNAUTHORIZED) except Exception as e: excMsg = "delete_users_data API : " + str(error_instance(e)) return excMsg finally: if obj: del obj
def get_benchmarking_graph(request): """ This function will return the graph data for the selected module :param request: request django object :return: json response """ query_params, obj = None, None try: query_params = request except: pass try: if request.method == GET_REQUEST: loggedin_user_details = _TokenValidation.validate_token(request) if loggedin_user_details: obj = BenchMarkingGraph(query_params) return obj.get_benchmark_graph() log_debug(METHOD_NOT_ALLOWED) return json_MethodNotAllowed except jwt.ExpiredSignatureError: token = request.META[HTTP_AUTHORIZATION_TOKEN].split(" ")[1] role = jwt.decode(token, verify=False) ob = HashingSalting() if role['role'] == 'Admin': ob.decreasing_admin_login_count() if role['role'] == 'Non Admin': ob.decreasing_Non_Admin_login_count() if role['role'] == 'Super Admin': ob.decreasing_super_Admin_login_count() return JsonResponse({MESSAGE_KEY: "Token Expired"}, status=HTTP_401_UNAUTHORIZED) except Exception as e: excMsg = "benchmarking_graph API : " + str(error_instance(e)) return excMsg finally: if obj: del obj
def upload_algorithm_file(request, algorithm_name): """ This function will upload csv and xml files, file name and description and will return error if generated. :param request: request django object :param algorithm_name : this will have the algorithm name :return: json response """ obj = None try: if request.method == POST_REQUEST: loggedin_user_details = _TokenValidation.validate_token(request) if loggedin_user_details: obj = UploadAlgorithmFile(request.FILES.getlist('files'), algorithm_name, request.POST.get('description'), request.POST.get('file_names')) return obj.upload_file() log_debug(METHOD_NOT_ALLOWED) return JsonResponse({MESSAGE_KEY: METHOD_NOT_ALLOWED}, status=HTTP_405_METHOD_NOT_ALLOWED) except jwt.ExpiredSignatureError: token = request.META[HTTP_AUTHORIZATION_TOKEN].split(" ")[1] role = jwt.decode(token, verify=False) ob = HashingSalting() if role['role'] == 'Admin': ob.decreasing_admin_login_count() if role['role'] == 'Non Admin': ob.decreasing_Non_Admin_login_count() if role['role'] == 'Super Admin': ob.decreasing_super_Admin_login_count() return JsonResponse({MESSAGE_KEY: "Token Expired"}, status=HTTP_401_UNAUTHORIZED) except Exception as e: return error_instance(e) finally: if obj: del obj
def clear_notifications_data(request): """ This function will get the values for dynamic benchmarking :param request: request django object :return: json response """ obj = None try: if request.method == POST_REQUEST: loggedin_user_details = _TokenValidation.validate_token(request) if loggedin_user_details: request_payload = json.loads(request.body.decode(UTF8_FORMAT)) obj = ClearNotifications(loggedin_user_details, request_payload) return obj.clear_notifications() else: return JsonResponse({MESSAGE_KEY: "FORBIDDEN ERROR"}, status=HTTP_403_FORBIDDEN) log_debug(METHOD_NOT_ALLOWED) return json_MethodNotAllowed except jwt.ExpiredSignatureError: token = request.META[HTTP_AUTHORIZATION_TOKEN].split(" ")[1] role = jwt.decode(token, verify=False) ob = HashingSalting() if role['role'] == 'Admin': ob.decreasing_admin_login_count() if role['role'] == 'Non Admin': ob.decreasing_Non_Admin_login_count() if role['role'] == 'Super Admin': ob.decreasing_super_Admin_login_count() return JsonResponse({MESSAGE_KEY: "Token Expired"}, status=HTTP_401_UNAUTHORIZED) except Exception as e: excMsg = "clear_notifications API : " + str(error_instance(e)) return excMsg finally: if obj: del obj
def get_configscreen_data(request): print("hi") """ This function will get the values for the equipment level as well as console level dynamic benchmarking :param request: request django object :param unit: unit name :param console: console name will be provided :param equipment: equipment name will be provided :return: json response """ obj = None try: if request.method == GET_REQUEST: loggedin_user_details = _TokenValidation.validate_token(request) if loggedin_user_details: obj = ConfigScreen() return obj.get_values() log_debug(METHOD_NOT_ALLOWED) return JsonResponse({MESSAGE_KEY: METHOD_NOT_ALLOWED}, status=HTTP_405_METHOD_NOT_ALLOWED) except jwt.ExpiredSignatureError: token = request.META[HTTP_AUTHORIZATION_TOKEN].split(" ")[1] role = jwt.decode(token, verify=False) ob = HashingSalting() if role['role'] == 'Admin': ob.decreasing_admin_login_count() if role['role'] == 'Non Admin': ob.decreasing_Non_Admin_login_count() if role['role'] == 'Super Admin': ob.decreasing_super_Admin_login_count() return JsonResponse({MESSAGE_KEY: "Token Expired"}, status=HTTP_401_UNAUTHORIZED) except Exception as e: return error_instance(e) finally: if obj: del obj
def get_user_list(request): """ This function will help to get all the users :param request: request django object :param username : for particular username :return: json object """ obj = None try: if request.method == GET_REQUEST: loggedin_user_details = _TokenValidation.validate_token(request) r_name = loggedin_user_details['role'] names = ['Super Admin', 'Admin'] if r_name in names: if loggedin_user_details: obj = GetUSerData(loggedin_user_details) return obj.getuser_list() else: return JsonResponse({MESSAGE_KEY: "FORBIDDEN ERROR"}, status=HTTP_403_FORBIDDEN) log_debug(METHOD_NOT_ALLOWED) return json_MethodNotAllowed except jwt.ExpiredSignatureError: token = request.META[HTTP_AUTHORIZATION_TOKEN].split(" ")[1] role = jwt.decode(token, verify=False) ob = HashingSalting() if role['role'] == 'Admin': ob.decreasing_admin_login_count() if role['role'] == 'Non Admin': ob.decreasing_Non_Admin_login_count() if role['role'] == 'Super Admin': ob.decreasing_super_Admin_login_count() return JsonResponse({MESSAGE_KEY: "Token Expired"}, status=HTTP_401_UNAUTHORIZED) except Exception as e: excMsg = "user_list API : " + str(error_instance(e)) return excMsg finally: if obj: del obj
def get_hgi_overview(request, equipment_name=None, module_name=None): """ This function will return the hgi module level overview :param module_name: module name :param equipment_name: equipment name :param request: request django object :return: json response """ obj = None try: if request.method == GET_REQUEST: loggedin_user_details = _TokenValidation.validate_token(request) if loggedin_user_details: obj = HgiOverview(equipment_name, module_name) return obj.get_hgi_data() log_debug(METHOD_NOT_ALLOWED) return json_MethodNotAllowed except jwt.ExpiredSignatureError: token = request.META[HTTP_AUTHORIZATION_TOKEN].split(" ")[1] role = jwt.decode(token, verify=False) ob = HashingSalting() if role['role'] == 'Admin': ob.decreasing_admin_login_count() if role['role'] == 'Non Admin': ob.decreasing_Non_Admin_login_count() if role['role'] == 'Super Admin': ob.decreasing_super_Admin_login_count() return JsonResponse({MESSAGE_KEY: "Token Expired"}, status=HTTP_401_UNAUTHORIZED) except Exception as e: excMsg = "get_hgi_overview API : " + str(error_instance(e)) return excMsg finally: if obj: del obj
def update_hgi_target(request, algorithm_name): """ This function will update the target with the passed json values. :param request: request django object :param algorithm_name : this either can be none or else it will have the target name :return: json response """ obj = None try: if request.method == PUT_REQUEST: request_payload = json.loads(request.body.decode(UTF8_FORMAT)) loggedin_user_details = _TokenValidation.validate_token(request) if loggedin_user_details: obj = HgiTargetUpdateParams(request_payload, algorithm_name) return obj.update_targets() log_debug(METHOD_NOT_ALLOWED) return json_MethodNotAllowed except jwt.ExpiredSignatureError: token = request.META[HTTP_AUTHORIZATION_TOKEN].split(" ")[1] role = jwt.decode(token, verify=False) ob = HashingSalting() if role['role'] == 'Admin': ob.decreasing_admin_login_count() if role['role'] == 'Non Admin': ob.decreasing_Non_Admin_login_count() if role['role'] == 'Super Admin': ob.decreasing_super_Admin_login_count() return JsonResponse({MESSAGE_KEY: "Token Expired"}, status=HTTP_401_UNAUTHORIZED) except Exception as e: excMsg = "get_hgi_list API : " + str(error_instance(e)) return excMsg finally: if obj: del obj
def get_equipment_names(request): """ This function will return the names for all the equipment and module :param request: request django object :return: json response """ obj = None try: if request.method == GET_REQUEST: loggedin_user_details = _TokenValidation.validate_token(request) if loggedin_user_details: obj = EquipmentNames(loggedin_user_details) return obj.get_names_values() log_debug(METHOD_NOT_ALLOWED) return JsonResponse({MESSAGE_KEY: METHOD_NOT_ALLOWED}, status=HTTP_405_METHOD_NOT_ALLOWED) except jwt.ExpiredSignatureError: token = request.META[HTTP_AUTHORIZATION_TOKEN].split(" ")[1] role = jwt.decode(token, verify=False) ob = HashingSalting() if role['role'] == 'Admin': ob.decreasing_admin_login_count() if role['role'] == 'Non Admin': ob.decreasing_Non_Admin_login_count() if role['role'] == 'Super Admin': ob.decreasing_super_Admin_login_count() return JsonResponse({MESSAGE_KEY: "Token Expired"}, status=HTTP_401_UNAUTHORIZED) except Exception as e: return error_instance(e) finally: if obj: del obj
def __add_user_query(self): """ This function will execute the query for creating a new user :return: Json paylaod """ self._psql_session.execute("select email_id from users") email = self._psql_session.fetchall() e_i = pd.DataFrame(email) em = list(e_i["email_id"]) if self._request_payload[USEREMAIL_KEY] not in em: try: with transaction.atomic(): obj = HashingSalting() hash_value, salt_value = obj.get_hashed_password( self._request_payload[USERPASSWORD_KEY]) self._psql_session.execute( "INSERT INTO users (first_name, middle_name,last_name, email_id,password, salt, " "gender, age, " "mobile, address,status,created_at)VALUES ('{}','{}','{}','{}','{}','{}','{}','{}','{}','{}'," "'{}', " "now())".format( self._request_payload[USERFIRSTNAME_KEY], self._request_payload[USERMIDDLENAME_KEY], self._request_payload[USERLASTNAME_KEY], self._request_payload[USEREMAIL_KEY], hash_value, salt_value, self._request_payload[GENDER_KEY], self._request_payload[AGE_KEY], self._request_payload[PHONE_KEY], self._request_payload[ADDRESS_KEY], self._request_payload[STATUS_KEY])) self._psql_session.execute( "select * from users where email_id='{}'".format( self._request_payload[USEREMAIL_KEY])) result_set = self._psql_session.fetchall() s = pd.DataFrame(result_set) userid = s['id'].iloc[0] self._psql_session.execute( "insert into role_users(role_id,user_id,created_at)VALUES({},{},now())" .format(self._request_payload[ROLE_ID], userid)) self._psql_session.execute( "select permission_id from role_permission where role_id={}" .format(self._request_payload[ROLE_ID])) result = self._psql_session.fetchall() p = pd.DataFrame(result) pid = list(p['permission_id']) data = [] for i in pid: data.append((userid, i)) execute_values( self._psql_session, "INSERT INTO user_permission (user_id,permission_id) VALUES %s", data) return JsonResponse({MESSAGE_KEY: CREATED_SUCCESSFULLY}) except IntegrityError as e: log_error("Exception due to : %s" + str(e)) return JsonResponse({MESSAGE_KEY: traceback.format_exc()}, status=HTTP_500_INTERNAL_SERVER_ERROR) except Exception as e: log_error("Exception due to : %s" + str(e)) return JsonResponse( { MESSAGE_KEY: INTERNAL_ERROR.format( traceback.format_exc()) }, status=HTTP_500_INTERNAL_SERVER_ERROR) else: return JsonResponse({MESSAGE_KEY: "Email is all ready registered"})
def handle_login(self): """ This will get query from the Database for the username and validation :return: Json Response """ try: assert self._db_connection, { STATUS_KEY: HTTP_500_INTERNAL_SERVER_ERROR, MESSAGE_KEY: DB_ERROR } if ENV: self._psql_session.execute( USER_AUTHETICATION_QUERY.format( self._request_payload[USEREMAIL_KEY])) else: self._psql_session.execute( USER_PROD_AUTHETICATION_QUERY.format( self._request_payload[USEREMAIL_KEY])) result_set = self._psql_session.fetchone() if result_set: obj = HashingSalting() if obj.check_password(self._request_payload[USERPASSWORD_KEY], result_set[SALT_KEY], result_set[USERPASSWORD_KEY]): if not result_set['status']: return JsonResponse({MESSAGE_KEY: STATUS_VALUE}, status=HTTP_401_UNAUTHORIZED) self._psql_session.execute( "select permission_name, role_name, first_name, last_name from users inner join role_users on " "role_users.user_id " "=users.id inner join role on role.id = role_users.role_id inner join user_permission on " "user_permission.user_id = users.id inner join permission on permission.id = " "user_permission.permission_id where users.email_id='{}'" .format(result_set[USEREMAIL_KEY])) df = pd.DataFrame(self._psql_session.fetchall()) jwt_token = None if not df.empty: jwt_token = TokenManagement().add_jwt({ LOGGEDINUSERID_KEY: result_set[USERID_KEY], LOGGEDINUSEREMAIL_KEY: result_set[USEREMAIL_KEY], "permission": list(df["permission_name"]), "role": str(df["role_name"].iloc[0]), "first_name": str(df["first_name"].iloc[0]), "last_name": str(df["last_name"].iloc[0]), 'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=86400) }) return JsonResponse({TOKEN_KEY: jwt_token}) return JsonResponse({MESSAGE_KEY: PASSWORD_WRONG}, status=HTTP_401_UNAUTHORIZED) return JsonResponse({MESSAGE_KEY: USERNAME_NOT_REGISTERED}, status=HTTP_401_UNAUTHORIZED) except AssertionError as e: log_error("Exception due to : %s" + str(e)) return JsonResponse({MESSAGE_KEY: e.args[0][MESSAGE_KEY]}, status=e.args[0][STATUS_KEY]) except Exception as e: log_error("Exception due to : %s" + str(e)) return JsonResponse( {MESSAGE_KEY: EXCEPTION_CAUSE.format(traceback.format_exc())}, status=HTTP_500_INTERNAL_SERVER_ERROR)
def __reset_user_password_query(self): """ This function will execute the query for resetting the user password :return: Json object """ try: with transaction.atomic(): try: decode_jwt = TokenManagement.is_valid_jwt( self._request_payload[TOKEN]) login_id = decode_jwt['login_id'] self._psql_session.execute( CHECK_AUTHENTICATION_QUERY.format(login_id)) admin = pd.DataFrame(self._psql_session.fetchall()) check_admin = None if not admin.empty: check_admin = admin[USER_TYPE].iloc[0] receiver = admin['email_id'].iloc[0] else: return JsonResponse( {MESSAGE_KEY: "USER IS NOT REGISTER WITH US"}) if check_admin == 'Admin' or check_admin == 'Super Admin': self._psql_session.execute(CHECK_LOGIN_ID) loginids = self._psql_session.fetchall() login_ids = pd.DataFrame(loginids) log_in_id = list(login_ids["login_id"]) if login_id in log_in_id: obj = HashingSalting() hash_value, salt = obj.get_hashed_password( self._request_payload[USERPASSWORD_KEY]) self._psql_session.execute( CHANGE_RESET_USER_PASSWORD_QUERY.format( SALT_KEY, salt, USERPASSWORD_KEY, hash_value, LOGIN_ID, login_id)) # s = smtplib.SMTP('smtp.gmail.com', 587) # s.starttls() # sender = '*****@*****.**' # s.login(sender, 'Mdevendra@1996') # receiver_mail = receiver # msg = MIMEMultipart('alternative') # msg['Subject'] = "Password" # msg['From'] = sender # msg['To'] = receiver_mail # context = """Hi.\n Here is the you are Password .\n {}""".format( # self._request_payload[USERPASSWORD_KEY]) # part1 = MIMEText(context, 'plain') # msg.attach(part1) # s.sendmail(sender, '*****@*****.**', msg.as_string()) # s.quit() port = 465 # For SSL smtp_server = "smtpout.ingenero.com" context = ssl.create_default_context() with smtplib.SMTP_SSL(smtp_server, port, context=context) as server: print( server.login('*****@*****.**', 'Ap5sn%k*20')) msg = MIMEMultipart('alternative') msg['Subject'] = "Reset Password" msg['From'] = '*****@*****.**' msg['To'] = '*****@*****.**' context = """Hi.\n Here is the you are Password .\n {}""".format( self._request_payload[USERPASSWORD_KEY]) part1 = MIMEText(context, 'plain') msg.attach(part1) server.sendmail('*****@*****.**', '*****@*****.**', msg.as_string()) except jwt.ExpiredSignatureError: return JsonResponse({MESSAGE_KEY: "Token Expired"}) if not self._psql_session.rowcount: return JsonResponse({MESSAGE_KEY: CHANGE_ERROR}, status=HTTP_400_BAD_REQUEST) return JsonResponse({MESSAGE_KEY: RESET_SUCCESSFULLY}) except IntegrityError as e: log_error("Exception due to : %s" + str(e)) return json_InternalServerError except Exception as e: log_error("Exception due to : %s" + str(e)) return json_InternalServerError
def __add_user_query(self): """ This function will execute the query for creating a new user :return: Json paylaod """ self._psql_session.execute( CHECK_AUTHENTICATION_QUERY.format( self.loggedin_user_details[LOGIN_ID])) result_set = self._psql_session.fetchall() if not self._psql_session.rowcount: return JsonResponse({MESSAGE_KEY: "LOGIN ID NOT REGISTER WITH US"}, status=HTTP_400_BAD_REQUEST) Permission = pd.DataFrame(result_set) if Permission[USER_TYPE].iloc[0] == 'Super Admin': if self._request_payload[USER_TYPE] == 'Admin': self._psql_session.execute(GET_ADMIN_COUNT) all_admin = pd.DataFrame(self._psql_session.fetchall()) if not all_admin.empty: admin_count = all_admin['count'].iloc[0].item() else: admin_count = None self._psql_session.execute(GET_ADMIN_USER) admin = pd.DataFrame(self._psql_session.fetchall()) if not admin.empty: admin_user = admin['limit_value'].iloc[0].item() else: admin_user = None if admin_user <= admin_count: return JsonResponse({ MESSAGE_KEY: "MAXIMUM NUMBER OF ADMIN USER COUNT EXCEEDED" }) self._psql_session.execute(CHECK_LOGIN_ID) loginids = self._psql_session.fetchall() login_ids = pd.DataFrame(loginids) log_in_id = list(login_ids["login_id"]) email_id = list(login_ids["email_id"]) if self._request_payload[ LOGIN_ID] not in log_in_id and self._request_payload[ USEREMAIL_KEY] not in email_id: try: with transaction.atomic(): obj = HashingSalting() hash_value, salt_value = obj.get_hashed_password( self._request_payload[USERPASSWORD_KEY]) self._psql_session.execute( ADD_USER.format( self._request_payload[NAME], self._request_payload[LOGIN_ID], self._request_payload[USEREMAIL_KEY], self._request_payload[DESIGNATION], self._request_payload[USER_TYPE], self._request_payload[EAMIL_NOTIFICATION], hash_value, salt_value)) return JsonResponse( {MESSAGE_KEY: CREATED_SUCCESSFULLY}) except IntegrityError as e: log_error("Exception due to : %s" + str(e)) return json_InternalServerError except Exception as e: log_error("Exception due to : %s" + str(e)) return json_InternalServerError else: return JsonResponse( {MESSAGE_KEY: "User is all ready registered"}) else: return JsonResponse( {MESSAGE_KEY: "User is not have permission to add"})
def __change_user_password_query(self): """ This function will execute the query for resetting the user password :return: Json object """ try: with transaction.atomic(): if DEVELOPMENT: self._psql_session.execute( CHECK_AUTHENTICATION_QUERY.format( self.loggedin_userid_details[LOGIN_ID])) else: self._psql_session.execute( CHECK_AUTHENTICATION_QUERY.format( self.loggedin_userid_details[LOGIN_ID])) if not self._psql_session.rowcount: return JsonResponse({MESSAGE_KEY: USERNAME_NOT_REGISTERED}, status=HTTP_400_BAD_REQUEST) result_set = self._psql_session.fetchall() Permission = pd.DataFrame(result_set) self._psql_session.execute( CHECK_AUTHENTICATION_QUERY.format( self._request_payload[LOGIN_ID])) admin = pd.DataFrame(self._psql_session.fetchall()) if not admin.empty: check_admin = admin[USER_TYPE].iloc[0] receiver = admin['email_id'].iloc[0] else: return JsonResponse( {MESSAGE_KEY: "USER IS NOT REGISTER WITH US"}) if Permission[USER_TYPE].iloc[0] == 'Super Admin': self._psql_session.execute(CHECK_LOGIN_ID) loginids = self._psql_session.fetchall() login_ids = pd.DataFrame(loginids) log_in_id = list(login_ids["login_id"]) if self._request_payload[LOGIN_ID] in log_in_id: obj = HashingSalting() hash, salt = obj.get_hashed_password( self._request_payload[USERPASSWORD_KEY]) self._psql_session.execute( CHANGE_RESET_USER_PASSWORD_QUERY.format( SALT_KEY, salt, USERPASSWORD_KEY, hash, LOGIN_ID, self._request_payload[LOGIN_ID])) port = 465 # For SSL smtp_server = "smtpout.ingenero.com" context = ssl.create_default_context() with smtplib.SMTP_SSL(smtp_server, port, context=context) as server: print( server.login('*****@*****.**', 'Ap5sn%k*20')) msg = MIMEMultipart('alternative') msg['Subject'] = "Reset Password" msg['From'] = '*****@*****.**' msg['To'] = '*****@*****.**' context = """Hi.\n Here is the you are Password .\n {}""".format( self._request_payload[USERPASSWORD_KEY]) part1 = MIMEText(context, 'plain') msg.attach(part1) server.sendmail('*****@*****.**', '*****@*****.**', msg.as_string()) server.quit() if self._psql_session.rowcount: return JsonResponse({ MESSAGE_KEY: "PASSWORD UPDATED SUCCESSFULLY AND PASSWORD SENT TO " "MAIL" }) return JsonResponse({MESSAGE_KEY: RESET_ERROR}, status=HTTP_400_BAD_REQUEST) return JsonResponse( {MESSAGE_KEY: "USER IS NOT REGISTER WITH US"}) else: return JsonResponse({ MESSAGE_KEY: "NON ADMIN USER IS NOT ACCESS TO CHANGE PASSWORD" }) except IntegrityError as e: log_error("Exception due to : %s" + str(e)) return json_InternalServerError except Exception as e: log_error("Exception due to : %s" + str(e)) return json_InternalServerError
def handle_login(self): """ This will get query from the database for the username and validation :return: Json Response """ try: assert self._db_connection, { STATUS_KEY: HTTP_500_INTERNAL_SERVER_ERROR, MESSAGE_KEY: DB_ERROR } session_count = None active_sessions = 0 standard_user_count = 0 active_standard = 0 if ENV: self._psql_session.execute( USER_AUTHETICATION_QUERY.format( self._request_payload[LOGIN_ID])) else: self._psql_session.execute( USER_PROD_AUTHETICATION_QUERY.format( self._request_payload[LOGIN_ID])) result_set = self._psql_session.fetchone() if result_set: obj = HashingSalting() self._psql_session.execute(GET_PARALLEL_SESSION_COUNT) s_count = pd.DataFrame(self._psql_session.fetchall()) if not s_count.empty: session_count = s_count['limit_value'].iloc[0] self._psql_session.execute(GET_ACTIVE_SESSIONS_COUNT) active_count = pd.DataFrame(self._psql_session.fetchall()) if not active_count.empty: active_sessions = active_count['value'].iloc[0] if active_sessions < session_count: user_type = result_set['user_type'] if user_type == 'Non Admin': self._psql_session.execute(GET_STANDARD_USER_COUNT) all_operator = pd.DataFrame( self._psql_session.fetchall()) if not all_operator.empty: standard_user_count = all_operator[ 'limit_value'].iloc[0].item() else: standard_user_count = None self._psql_session.execute( GET_ACTIVE_STANDARD_USER_COUNT) active_operator = pd.DataFrame( self._psql_session.fetchall()) if not active_operator.empty: active_standard = active_operator['value'].iloc[0] else: active_standard = None if active_standard < standard_user_count: obj.active_parallel_standard_sessions_increase() else: return JsonResponse( { MESSAGE_KEY: 'Could not login as the maximum number of parallel user logins have ' 'been exceeded' }, status=HTTP_403_FORBIDDEN) if user_type == 'Super Admin': obj.active_parallel_sessions_increase() if user_type == 'Admin': obj.active_parallel_admin_sessions_increase() self._psql_session.execute( PASSWORD_RESET_EXPIRY_CHECK.format( PASSWORD_EXPIRY_PERIOD)) password = pd.DataFrame(self._psql_session.fetchall()) if not password.empty: expiry = password['value'].iloc[0] else: expiry = None self._psql_session.execute( USER_PASSWORD_EXPIRY_CHECK.format( self._request_payload[LOGIN_ID])) expiry_value = pd.DataFrame(self._psql_session.fetchall()) if not expiry_value.empty: user_pwd_expiry = expiry_value['value'].iloc[0] else: user_pwd_expiry = None if user_pwd_expiry <= expiry: if obj.check_password( self._request_payload[USERPASSWORD_KEY], result_set[SALT_KEY], result_set[USERPASSWORD_KEY]): if not result_set['status']: return JsonResponse( {MESSAGE_KEY: STATUS_VALUE}, status=HTTP_401_UNAUTHORIZED) self._psql_session.execute( PERMISSION_QUERY_1.format( result_set['user_type'])) permissions = pd.DataFrame( self._psql_session.fetchall()) role = str(result_set['user_type']) dict_data = {} if not permissions.empty: data_now = permissions.groupby('section') for name, group in data_now: dict_data[name] = list(group['feature']) jwt_token = TokenManagement().add_jwt({ LOGGEDINUSERID_KEY: result_set[USERID_KEY], LOGIN_ID: result_set[LOGIN_ID], USERNAME_KEY: result_set['name'], 'role': role, 'permissions': dict_data, 'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=86400) }) return JsonResponse({TOKEN_KEY: jwt_token}) return JsonResponse({MESSAGE_KEY: PASSWORD_WRONG}, status=HTTP_401_UNAUTHORIZED) return JsonResponse( { MESSAGE_KEY: "PASSWORD EXPIRED! PLEASE CONTACT YOUR SUPER ADMIN" }, status=HTTP_403_FORBIDDEN) return JsonResponse( { MESSAGE_KEY: 'Could not login as the maximum number of parallel user logins have been exceeded' }, status=HTTP_403_FORBIDDEN) return JsonResponse({MESSAGE_KEY: USERNAME_NOT_REGISTERED}, status=HTTP_401_UNAUTHORIZED) except AssertionError as e: log_error("Exception due to : %s" + str(e)) return asert_res(e) except Exception as e: log_error("Exception due to : %s" + str(e)) return json_InternalServerError