ldap-python-webui/libs/helper.py

77 lines
2.1 KiB
Python
Raw Normal View History

2022-04-16 23:13:00 +02:00
#!/usr/bin/python3
import sqlite3
2022-04-25 13:10:25 +02:00
import re
2023-11-16 13:17:59 +01:00
from onetimepass import valid_totp
from secrets import choice
2023-11-18 20:44:06 +01:00
import segno
2023-11-18 23:03:40 +01:00
from os import path
2023-11-20 13:01:32 +01:00
import uuid
2022-04-16 23:13:00 +02:00
class Tools():
2023-04-11 18:19:16 +02:00
def __init__(self):
self.username = ''
#check code
def code_is_valid(self, code, db):
con = sqlite3.connect(db)
cur = con.cursor()
codes=[]
for row in cur.execute('SELECT * FROM codes WHERE valid = 1'):
codes.append(row[0])
return(bool(code in codes))
def mark_code_as_used(self, code, db):
con = sqlite3.connect(db)
cur = con.cursor()
cur.execute('''UPDATE codes SET valid=? WHERE code==?''',(0, code))
con.commit()
#form validation
def input_validation(self, e, ws=None):
if ws:
#accepts whitespaces
regex = r'^\w+( \w+)*$'
else:
regex = r'^\w+$'
return(bool(re.fullmatch(regex, e)))
def email_validation(self, e):
regex = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
return(bool(re.fullmatch(regex, e)))
def pwd_validation(self, e):
regex = r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!#%*?&]{8,18}$'
return(bool(re.fullmatch(regex, e)))
2023-11-18 20:44:06 +01:00
# 2FA
2023-11-18 23:03:40 +01:00
def gen_qr(self, secret):
if(not path.isfile('static/tmp/'+secret+'.png')):
qrcode = segno.make(secret, micro=False)
qrcode.save('static/tmp/'+secret+'.png', scale=10)
def gen_secret(self): # Function to return a random string with length 16.
2023-11-16 13:17:59 +01:00
secret = ''
while len(secret) < 16:
secret += choice('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567')
2023-11-18 23:03:40 +01:00
self.gen_qr(secret)
2023-11-16 13:17:59 +01:00
return secret
2023-11-20 11:45:49 +01:00
def _2fa_validation(self, otp, secret):
2023-11-18 23:03:40 +01:00
authenticated = valid_totp(otp, secret)
if authenticated:
print('Correct otp, Authenticated!')
return True
elif not authenticated:
print('Wrong otp, please try again.')
return False
2023-11-20 13:01:32 +01:00
def session_id(self):
return uuid.uuid4().hex
2023-11-20 11:45:49 +01:00
tools = Tools()