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 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
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 __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' or 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 self._request_payload[LOGIN_ID] in log_in_id: obj = HashingSalting() if obj.check_password( self._request_payload[USERPASSWORD_KEY], Permission[SALT_KEY].iloc[0], Permission[USERPASSWORD_KEY].iloc[0]): 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, LOGIN_ID, self._request_payload[LOGIN_ID])) else: self._psql_session.execute( CHANGE_RESET_USER_PASSWORD_QUERY.format( SALT_KEY, salt_value, USERPASSWORD_KEY, hash_value, LOGIN_ID, self._request_payload[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[USERFUTUREPASSWORD_KEY]) # part1 = MIMEText(context, 'plain') # msg.attach(part1) # s.sendmail(sender, '*****@*****.**', msg.as_string()) 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 your password .\n {}""".format( self. _request_payload[USERFUTUREPASSWORD_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: PASSWORD_WRONG}, 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