Skip to content

Commit

Permalink
code linting and formating
Browse files Browse the repository at this point in the history
  • Loading branch information
kash committed Apr 11, 2023
1 parent 7357d6b commit e908948
Show file tree
Hide file tree
Showing 10 changed files with 304 additions and 162 deletions.
6 changes: 4 additions & 2 deletions Common/breach_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,17 @@
import ipaddress
from Config.config import configure_logging
import logging

configure_logging()

# import argparse
# import asyncio


class BreachChecker:
def is_valid_email(self, email):
# Verify email format
# TODO: Add a list of email domains accepted..may be
# Verify email format
# TODO: Add a list of email domains accepted..may be
if re.match(r"[^@]+@[^@]+\.[^@]+", email):
logging.debug("Input is a valid email address.")
return True
Expand Down
64 changes: 33 additions & 31 deletions Common/utils.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
# Utils file to:
# fetch the relevant API keys of different services
# validate keys
# process non critical and fatal errors
# TODO: Logging to file
# fetch the relevant API keys of different services
# validate keys
# process non critical and fatal errors
# TODO: Logging to file
import requests
import json
import re
import ipaddress
from termcolor import colored
from termcolor import colored
import sys
import configparser
from . import utils
Expand All @@ -17,19 +17,22 @@

configure_logging()


def error_message(errormsg):
logging.error(colored("Error: "+errormsg, 'red'))
logging.error(colored("Error: " + errormsg, "red"))
# TODO: Extend error module to log to error log file
# print(errormsg)


def exit_message(exitmsg):
logging.critical("\033[91m{}\033[0m".format("Fatal Error: "+exitmsg))
logging.critical("\033[91m{}\033[0m".format("Fatal Error: " + exitmsg))
exit()


class Validator:
def is_valid_email(self, email):
# Verify email format
# TODO: Add a list of email domains accepted..may be
# Verify email format
# TODO: Add a list of email domains accepted..may be
if re.match(r"[^@]+@[^@]+\.[^@]+", email):
# print("Email address validation: \033[92m{}\033[0m".format("Success"))
return True
Expand All @@ -44,8 +47,8 @@ def is_valid_ip(self, ip):
return False

def is_valid_username(self, username):
# Verify username format
# TODO: Add a list of username domains accepted..may be
# Verify username format
# TODO: Add a list of username domains accepted..may be
if re.match(r"^[a-zA-Z0-9\-\_\!\@\#\$\%\^\&\*\(\)]+", username):
logging.debug("Input is a valid username")
return True
Expand All @@ -57,61 +60,60 @@ def is_valid_username(self, username):
def check_VTAPIkey(self, VT_APIKey):
# Google IP just for validating key
ip = "8.8.8.8"
url = "https://www.virustotal.com/api/v3/ip_addresses/"+ip
payload={}
headers = {
'x-apikey': VT_APIKey
}
url = "https://www.virustotal.com/api/v3/ip_addresses/" + ip
payload = {}
headers = {"x-apikey": VT_APIKey}
response = requests.request("GET", url, headers=headers, data=payload).text
data = json.loads(response)
if 'error' not in data:
if "error" not in data:
# Print pretty json response
# print(json.dumps(data, indent=4, sort_keys=True))
logging.info("Virus Total Key Validation: \033[92m{}\033[0m".format("Success"))
logging.info(
"Virus Total Key Validation: \033[92m{}\033[0m".format("Success")
)
return True
else:
error_message(json.dumps(data['error'], indent=4, sort_keys=True))
error_message(json.dumps(data["error"], indent=4, sort_keys=True))
exit_message("Virus Total Key Validation failed")
return False

# def check_VTAPIkey(self, VT_APIKey):
# instead of wasting a call to HIBP API just to check validity of key,
# execute the call for the actual query and then throw error if key is
# invalid (since likelihood of key being wrong is slim)
# instead of wasting a call to HIBP API just to check validity of key,
# execute the call for the actual query and then throw error if key is
# invalid (since likelihood of key being wrong is slim)


class KeyFetcher:
def getVTAPIKey(self):

config = configparser.ConfigParser()
if config.read('Config/config.ini', encoding='utf-8'):

if config.read("Config/config.ini", encoding="utf-8"):
pass
else:
exit_message("Config file not found")
try:
VT_APIKey = config['APIKeys']['VT_APIKey']
VT_APIKey = config["APIKeys"]["VT_APIKey"]
except Exception as er:
error_message(str(er))
exit_message("VT API Key not found in config file")
if VT_APIKey == '':
if VT_APIKey == "":
exit_message("VT API Key could not be retrieved")
else:
return VT_APIKey

def getHIBPAPIKey(self):

config = configparser.ConfigParser()
if config.read('Config/config.ini', encoding='utf-8'):
if config.read("Config/config.ini", encoding="utf-8"):
# print("Reading config file...")
pass
else:
exit_message("Config file not found")
try:
HIBP_APIKey = config['APIKeys']['HIBP_APIKey']
HIBP_APIKey = config["APIKeys"]["HIBP_APIKey"]
except Exception as er:
error_message(str(er))
exit_message("HIBP API Key not found in config file")
if HIBP_APIKey == '':
if HIBP_APIKey == "":
exit_message("HIBP API Key could not be retrieved")
else:
return HIBP_APIKey
Expand Down
23 changes: 11 additions & 12 deletions Config/check_config_validity.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,22 @@
import configparser

config = configparser.ConfigParser()
config.read('Config/logger.ini')
config.read("Config/logger.ini")

# check if the required sections are present
if 'loggers' not in config.sections() or 'handlers' not in config.sections():
raise ValueError('Missing required section in config.ini')
if "loggers" not in config.sections() or "handlers" not in config.sections():
raise ValueError("Missing required section in config.ini")

if 'keys' not in config['loggers'] or 'suspicious' not in config['loggers']:
raise ValueError('Missing required key in loggers section in config.ini')
if "keys" not in config["loggers"] or "suspicious" not in config["loggers"]:
raise ValueError("Missing required key in loggers section in config.ini")

# check if the required keys are present in the 'handlers' section
if 'keys' not in config['handlers'] or 'console' not in config['handlers']['keys']:
raise ValueError('Missing required key in handlers section in config.ini')
if "keys" not in config["handlers"] or "console" not in config["handlers"]["keys"]:
raise ValueError("Missing required key in handlers section in config.ini")

# check if the values of the keys are in the expected format
if not isinstance(config.getint('handlers', 'console.level'), int):
raise ValueError('Invalid value for console.level in config.ini')

if not isinstance(config.getint('loggers', 'keys.suspicious.level'), int):
raise ValueError('Invalid value for keys.suspicious.level in config.ini')
if not isinstance(config.getint("handlers", "console.level"), int):
raise ValueError("Invalid value for console.level in config.ini")

if not isinstance(config.getint("loggers", "keys.suspicious.level"), int):
raise ValueError("Invalid value for keys.suspicious.level in config.ini")
6 changes: 3 additions & 3 deletions Config/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ def get_config(config_file_path):
config.__dict__

# read from environment variables
for key in config['ENVIRONMENT']:
for key in config["ENVIRONMENT"]:
env_var = os.environ.get(key)
if env_var is not None:
config['ENVIRONMENT'][key] = env_var
config["ENVIRONMENT"][key] = env_var

return config

Expand All @@ -41,7 +41,7 @@ def get_logging_config(file_location="Config/logger.ini"):
logging.critical(f"File location invalid: {file_location}")
sys.exit(1)

config = get_config('Config/logger.ini')
config = get_config("Config/logger.ini")
return config


Expand Down
15 changes: 7 additions & 8 deletions Config/formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,17 @@ def __init__(self, fmt=None, datefmt=None, levels=None):
self.levels = levels or {}

def format(self, record):
record.levelprefix = self.levels.get(record.levelno, '')
emoji = ''
record.levelprefix = self.levels.get(record.levelno, "")
emoji = ""
if record.levelno == logging.CRITICAL:
emoji = '💣'
emoji = "💣"
elif record.levelno == logging.ERROR:
emoji = '🔥'
emoji = "🔥"
elif record.levelno == logging.WARNING:
emoji = '⚠️'
emoji = "⚠️"
elif record.levelno == logging.INFO:
emoji = 'ℹ️'
emoji = "ℹ️"
elif record.levelno == logging.DEBUG:
emoji = '🔍'
emoji = "🔍"
record.emoji = emoji
return super().format(record)

Loading

0 comments on commit e908948

Please sign in to comment.