Skip to content

Commit

Permalink
securizing user input
Browse files Browse the repository at this point in the history
  • Loading branch information
RobsOnWaves committed Dec 29, 2023
1 parent c7a3fb2 commit ac508c7
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 55 deletions.
98 changes: 49 additions & 49 deletions Code/libs/gold_digger.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@
class GoldDigger:
def __init__(self):
self.__messages__ = Messages()
self.max_length = 1000
self.timeout_duration = 60
self.sup750 = '>750 mil'
self.k750 = '750 mil'
self.k585 = '585 mil'
self.k375 = '375 mil'
self.prix_bas = 'prix (€) bas'
self.prix_haut = 'prix (€) haut'
self.__max_length__ = 1000
self.__timeout_duration__ = 60
self.__sup750__ = '>750 mil'
self.__k750__ = '750 mil'
self.__k585__ = '585 mil'
self.__k375__ = '375 mil'
self.__prix_bas__ = 'prix (€) bas'
self.__prix_haut__ = 'prix (€) haut'

async def docx_table_to_df(self, upload_file: UploadFile, table_index=0):
# Read the content of the uploaded file into a BytesIO object
Expand Down Expand Up @@ -59,13 +59,13 @@ def timeout_handler():
raise TimeoutException()

# Dictionnaire pour stocker les poids
weights = {self.sup750: '', self.k750: '', self.k585: '', self.k375: ''}
weights = {self.__sup750__ : '', self.__k750__: '', self.__k585__: '', self.__k375__: ''}

if len(description) > self.max_length:
if len(description) > self.__max_length__ :
raise ValueError("Entry too long")


timer = threading.Timer(self.timeout_duration, timeout_handler)
timer = threading.Timer(self.__timeout_duration__ , timeout_handler)
try:
timer.start()
weight_parts = re.findall(
Expand All @@ -81,13 +81,13 @@ def timeout_handler():
for part in weight_parts:
category, weight = part
if category == 'superieur a 750 mil' or category == 'Superieur a 750 mil':
weights[self.sup750] = weight
elif category == self.k750:
weights[self.k750] = weight
elif category == self.k585:
weights[self.k585] = weight
elif category == self.k375:
weights[self.k375] = weight
weights[self.__sup750__ ] = weight
elif category == self.__k750__:
weights[self.__k750__] = weight
elif category == self.__k585__:
weights[self.__k585__] = weight
elif category == self.__k375__:
weights[self.__k375__] = weight

return weights

Expand All @@ -100,9 +100,9 @@ def timeout_handler():
raise TimeoutException()

# Initial setup for different fineness categories
weights = {self.sup750: None, self.k750: None, self.k585: None, self.k375: None}
weights = {self.__sup750__ : None, self.__k750__: None, self.__k585__: None, self.__k375__: None}

if len(row['Designation']) > self.max_length:
if len(row['Designation']) > self.__max_length__ :
raise ValueError("L'entrée est trop longue.")

# Regular expressions for finding weight and fineness
Expand All @@ -112,7 +112,7 @@ def timeout_handler():

# Extracting weight
# Crée un timer pour le timeout
timer = threading.Timer(self.timeout_duration, timeout_handler)
timer = threading.Timer(self.__timeout_duration__ , timeout_handler)
try:
timer.start()
# Applique l'expression régulière
Expand Down Expand Up @@ -150,7 +150,7 @@ async def compute_excel_file(self, upload_file: UploadFile, price_per_kg: int, g

df['Platine'] = df['Designation'].apply(lambda x: 'x' if 'platine' in x.lower() else "")
# Créer des colonnes pour chaque titrage dans le DataFrame
for mil in [self.sup750, self.k750, self.k585, self.k375]:
for mil in [self.__sup750__ , self.__k750__, self.__k585__, self.__k375__]:
df[mil] = None

# Appliquer la fonction d'extraction à chaque ligne
Expand All @@ -159,8 +159,8 @@ async def compute_excel_file(self, upload_file: UploadFile, price_per_kg: int, g
for key in weight_info:
df.at[index, key] = weight_info[key]

mask = df[[self.sup750, self.k750, self.k585, self.k375]].isna() | (
df[[self.sup750, self.k750, self.k585, self.k375]] == '')
mask = df[[self.__sup750__ , self.__k750__, self.__k585__, self.__k375__]].isna() | (
df[[self.__sup750__ , self.__k750__, self.__k585__, self.__k375__]] == '')
# Example of usage
# Assuming 'data' is your DataFrame loaded from the Excel file

Expand All @@ -176,33 +176,33 @@ async def compute_excel_file(self, upload_file: UploadFile, price_per_kg: int, g
# Ensuite, remplissez toutes les valeurs NaN par 0.0
df.fillna(0.0, inplace=True)

df[self.k585] = pd.to_numeric(df[self.k585], errors='coerce')
df[self.k375] = pd.to_numeric(df[self.k375], errors='coerce')
df[self.k750] = pd.to_numeric(df[self.k750], errors='coerce')
df[self.sup750] = pd.to_numeric(df[self.sup750], errors='coerce')
df[self.__k585__] = pd.to_numeric(df[self.__k585__], errors='coerce')
df[self.__k375__] = pd.to_numeric(df[self.__k375__], errors='coerce')
df[self.__k750__] = pd.to_numeric(df[self.__k750__], errors='coerce')
df[self.__sup750__ ] = pd.to_numeric(df[self.__sup750__ ], errors='coerce')

# Après la conversion, utilisez fillna pour remplacer les NaN par 0.0 si nécessaire
df[self.k585].fillna(0.0, inplace=True)
df[self.k375].fillna(0.0, inplace=True)
df[self.k750].fillna(0.0, inplace=True)
df[self.sup750].fillna(0.0, inplace=True)

df[self.prix_haut] = ((price_per_g - gold_coeffs['offset_euros']/1000) * \
( df[self.k585] * gold_coeffs['coeff_585_nume']/gold_coeffs['coeff_585_nume']
+ df[self.k375] * gold_coeffs['coeff_375_nume']/gold_coeffs['coeff_375_nume']
+ df[self.k750] * gold_coeffs['coeff_750_nume']/gold_coeffs['coeff_750_nume']
+ df[self.sup750] * gold_coeffs['coeff_22up_nume']/gold_coeffs['coeff_22up_denum'])).round(0)

df[self.prix_bas] = ((price_per_g - gold_coeffs['offset_euros']/1000) * \
( df[self.k585] * gold_coeffs['coeff_585_nume']/gold_coeffs['coeff_585_nume']
+ df[self.k375] * gold_coeffs['coeff_375_nume']/gold_coeffs['coeff_375_nume']
+ df[self.k750] * gold_coeffs['coeff_750_nume']/gold_coeffs['coeff_750_nume']
+ df[self.sup750] * gold_coeffs['coeff_22down_nume']/gold_coeffs['coeff_22down_denum'])).round(0)

df[self.prix_bas] = df[self.prix_bas].astype(object)
df[self.prix_haut] = df[self.prix_haut].astype(object)
df.loc[df['Platine'] == 'x', self.prix_haut] = 'Platine'
df.loc[df['Platine'] == 'x', self.prix_bas] = 'Platine'
df[self.__k585__].fillna(0.0, inplace=True)
df[self.__k375__].fillna(0.0, inplace=True)
df[self.__k750__].fillna(0.0, inplace=True)
df[self.__sup750__ ].fillna(0.0, inplace=True)

df[self.__prix_haut__] = ((price_per_g - gold_coeffs['offset_euros']/1000) * \
( df[self.__k585__] * gold_coeffs['coeff_585_nume']/gold_coeffs['coeff_585_nume']
+ df[self.__k375__] * gold_coeffs['coeff_375_nume']/gold_coeffs['coeff_375_nume']
+ df[self.__k750__] * gold_coeffs['coeff_750_nume']/gold_coeffs['coeff_750_nume']
+ df[self.__sup750__ ] * gold_coeffs['coeff_22up_nume']/gold_coeffs['coeff_22up_denum'])).round(0)

df[self.__prix_bas__] = ((price_per_g - gold_coeffs['offset_euros']/1000) * \
( df[self.__k585__] * gold_coeffs['coeff_585_nume']/gold_coeffs['coeff_585_nume']
+ df[self.__k375__] * gold_coeffs['coeff_375_nume']/gold_coeffs['coeff_375_nume']
+ df[self.__k750__] * gold_coeffs['coeff_750_nume']/gold_coeffs['coeff_750_nume']
+ df[self.__sup750__ ] * gold_coeffs['coeff_22down_nume']/gold_coeffs['coeff_22down_denum'])).round(0)

df[self.__prix_bas__] = df[self.__prix_bas__].astype(object)
df[self.__prix_haut__] = df[self.__prix_haut__].astype(object)
df.loc[df['Platine'] == 'x', self.__prix_haut__] = 'Platine'
df.loc[df['Platine'] == 'x', self.__prix_bas__] = 'Platine'
df.loc[df['Platine'] == 0, 'Platine'] = ''
file_name = './data_out/' + datetime.datetime.now().strftime(
"%Y%m%d%H%M%S") + '_mon_fichier_excel.xlsx'
Expand Down
7 changes: 4 additions & 3 deletions Code/libs/mongo_db_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ def __init__(self, address: str, user: str, password: str):
self.__connection_string__ = "mongodb://" + user + ":" + password + "@" + address
self.__mongo_client__ = MongoClient(self.__connection_string__)
self.__messages__ = Messages()
self.__exception_message__ = "MongoDB error Exception: "

def get_gold_coeffs(self):
db = self.__mongo_client__.gold_coeffs
Expand All @@ -23,7 +24,7 @@ def get_gold_coeffs(self):
return gold_coeffs

except Exception as e:
return "MongoDB error Exception: " + str(e)
return self.__exception_message__+ str(e)

@staticmethod
def from_ged_dict_to_mongodb_dict(ged_handler: GedFileHandler = GedFileHandler(),
Expand Down Expand Up @@ -173,7 +174,7 @@ def get_users(self):
end_cursor = True

except Exception as e:
return "MongoDB error Exception: " + str(e)
return self.__exception_message__+ str(e)

return users

Expand Down Expand Up @@ -227,7 +228,7 @@ def get_collections(self):
return {"collection_names": collection_names}

except Exception as e:
return "MongoDB error Exception: " + str(e)
return self.__exception_message__+ str(e)

def modify_user_password(self,
user_name: str,
Expand Down
7 changes: 4 additions & 3 deletions Code/public_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,10 +241,11 @@ async def create_user(user_name: str = Form(),
role: Roles = Form(),
current_user: User = Depends(get_current_active_user)):
if current_user.role == "admin":
return {'response': mongo_handler.insert_user(user_name, full_name, email, get_password_hash(password),
current_user.username, role)}
mongo_handler.insert_user(user_name, full_name, email, get_password_hash(password),
current_user.username, role)
return {'response': 'User created successfully'}
else:
return {'response': messages.nok_string}
return {'response': 'Access denied'}


@app.post("/ged_file", description="Uploading a ged-file to the database, restricted to admin privileges")
Expand Down

0 comments on commit ac508c7

Please sign in to comment.