Files
mini-flees/code/utils/misc.py
2024-01-14 09:25:24 +02:00

51 lines
1.1 KiB
Python

import fnmatch
import secrets
import string
from datetime import datetime
import passlib.hash
VALID_TOKEN_CHARS = string.digits + string.ascii_letters
def random_token(n=8):
return "".join(secrets.choice(VALID_TOKEN_CHARS) for i in range(n))
def file_date_human(num):
return datetime.fromtimestamp(num).strftime("%y-%m-%d")
def file_time_human(num):
return datetime.fromtimestamp(num).strftime("%y-%m-%d %H:%M")
def file_size_human(num, HTML=True):
space = " " if HTML else " "
for x in [space + "B", "KB", "MB", "GB", "TB"]:
if num < 1024.0:
if x == space + "B":
return "%d%s%s" % (num, space, x)
return "%3.1f%s%s" % (num, space, x)
num /= 1024.0
def file_size_MB(num):
return "{:,.2f}".format(num / (1024 * 1024))
def hash_password(password):
return passlib.hash.argon2.hash(password)
def verify_password(password, hash):
return passlib.hash.argon2.verify(password, hash)
def is_ip_allowed(allowed_ip, ip, app):
for rule in allowed_ip.split(","):
rule = rule.strip()
if fnmatch.fnmatch(ip, rule):
return True
return False