Unverified Commit f9d2f8f9 authored by Tharyrok's avatar Tharyrok

Refactore Multi certificat

parent 987008f3
......@@ -22,7 +22,7 @@ l.simple_bind_s(login_dn, login_pw)
#
# Connexion SQL
#
db = postgresql.open("pq://tharyrok:tharyrok@127.0.0.1/ispng")
db = postgresql.open("pq://tharyrok:tharyrok@127.0.0.1/ispng_beta")
#
# Cache certificate
......@@ -41,6 +41,7 @@ for i in glob.glob('/home/tharyrok/developpement/neutrinet/cert/*.crt'):
#
# Clean user is bdd and not ldap
#
print('Clean user is bdd and not ldap')
result = db.prepare('SELECT ovpn_clients."userId" FROM public.ovpn_clients')
......@@ -48,20 +49,27 @@ for i in result:
res = l.search_s("ou=Users,dc=neutrinet,dc=be", ldap.SCOPE_SUBTREE, "(uid=" + str(i["userId"]) + ")")
if len(res) < 1:
db.execute('DELETE FROM ovpn_clients WHERE "userId" = \'%s\';' % str(i["userId"]))
print('Remove %s', str(i["userId"]))
#
# clean serial is bbd and not server
#
print('clean serial is bbd and not server')
results = db.prepare('SELECT certificates.serial, certificates.id FROM public.certificates')
for result in results:
if not any(d.get('serial', None) == str(result['serial']) for d in certificates):
i = next((item for item in certificates if item.get("serial") and item["serial"] == result['serial']), None)
if not i:
db.execute('DELETE FROM certificates WHERE id = %d;' % result["id"])
print('Remove %s', str(result["id"]))
#
# clean certificate not associate ip
#
print('Clean certificate not associate ip')
for cert in certificates:
result = db.prepare(
......@@ -75,13 +83,16 @@ for cert in certificates:
if result is 0:
try:
os.remove(cert.file)
os.remove(cert['file'])
print('Remove %s', str(cert['file']))
except FileNotFoundError:
pass
#
# Liberate ip is not associate member
#
print('Liberate ip is not associate member')
results = db.prepare(
'SELECT '
......@@ -95,10 +106,13 @@ results = db.prepare(
for i in results:
db.execute('UPDATE address_pool SET client_id = -1 WHERE id = %s' % i["id"])
print('Remove %s', str(i["id"]))
#
# Liberate ip is not associate certificate
#
print('Liberate ip is not associate certificate')
result = db.prepare(
'SELECT '
'id '
......@@ -111,99 +125,91 @@ result = db.prepare(
for i in result:
db.execute('UPDATE address_pool SET client_id = -1 WHERE id = %s' % i["id"])
print('Remove %s', str(i["id"]))
#
# Clean old certificate for member if one certificate valid
#
print('Clean old certificate for member if one certificate valid')
member_list_serial = {}
results = db.prepare('SELECT '
'certificates.serial, '
'certificates.client_id '
'FROM '
'public.certificates,'
'public.ovpn_clients '
'WHERE '
'certificates.client_id = ovpn_clients.id')
# restructure result
for i in results:
if i['client_id'] in member_list_serial:
member_list_serial[i['client_id']].append(i['serial'])
else:
member_list_serial[i['client_id']] = []
member_list_serial[i['client_id']].append(i['serial'])
for client, certs_for_member in member_list_serial.items():
if len(certs_for_member) > 1:
for cert_for_member in certs_for_member:
# find certificate not expire
try:
end_date = [element for element in certificates if element['serial'] == cert_for_member][0]
except IndexError:
break
if end_date['end_date'] >= datetime.datetime.now():
# delete other certificate
db.execute(
'DELETE FROM certificates WHERE client_id=%d AND NOT serial=\'%s\';' % (client, cert_for_member))
for cert_old_for_member in certs_for_member:
if cert_old_for_member is not cert_for_member:
try:
try:
os.remove(
[element for element in certificates if element['serial'] == cert_old_for_member][
0]['file'])
except IndexError:
pass
except FileNotFoundError:
pass
#
# Find member for certificate expire to 90 days and expire for 180 days
#
member_list_serial = {}
results = db.prepare('SELECT '
'certificates.serial, '
'certificates.client_id, '
'ovpn_clients."userId" '
'FROM '
'public.certificates,'
'public.ovpn_clients '
'WHERE '
'certificates.client_id = ovpn_clients.id')
'certificates.client_id = ovpn_clients.id ')
# restructure result
for i in results:
if i['userId'] in member_list_serial:
member_list_serial[i['userId']].append(i['serial'])
# Remove certificate not in the server
for result in results:
cert = next((item for item in certificates if item.get("serial") and item["serial"] == result['serial']), None)
if not cert:
# delete other certificate
db.execute(
'DELETE FROM certificates WHERE serial=\'%s\';' % (str(result['serial'])))
print('Remove %s', str(result['serial']))
else:
member_list_serial[i['userId']] = []
member_list_serial[i['userId']].append(i['serial'])
cert['user_id'] = result['userId']
if result['client_id'] in member_list_serial:
member_list_serial[result['client_id']].append(cert)
else:
member_list_serial[result['client_id']] = []
member_list_serial[result['client_id']].append(cert)
# Remove multi certificatr
for members in member_list_serial:
if len(member_list_serial[members]) > 1:
last = datetime.datetime.fromtimestamp(1)
last_elem = None
for member in member_list_serial[members]:
if last < member['end_date']:
if last_elem:
member_list_serial[members].remove(last_elem)
last = member['end_date']
last_elem = member
else:
# delete other certificate
db.execute('DELETE FROM certificates WHERE serial=\'%s\';' % (str(member['serial'])))
try:
os.remove(member['file'])
except FileNotFoundError:
pass
print('Remove %s', str(member['serial']))
member_list_serial[members].remove(member)
for user_id, serials in member_list_serial.items():
end_180 = False
end_90 = False
valid = False
for serial in serials:
try:
end_date = [element for element in certificates if element['serial'] == serial][0]['end_date']
except IndexError:
break
serial_end_180 = False
serial_end_90 = False
serial_valid = False
if end_date <= (datetime.datetime.now() - datetime.timedelta(days=180)):
end_180 = end_date
serial = serials[0]['serial']
end_date = serials[0]['end_date']
user_id = serials[0]['user_id']
elif end_date <= datetime.datetime.now():
end_180 = end_date
if end_date <= (datetime.datetime.now() - datetime.timedelta(days=180)):
end_180 = end_date
serial_end_180 = serial
elif end_date <= (datetime.datetime.now() + datetime.timedelta(days=90)):
end_90 = end_date
elif end_date <= datetime.datetime.now():
end_180 = end_date
serial_end_180 = serial
else:
valid = end_date
elif end_date <= (datetime.datetime.now() + datetime.timedelta(days=90)):
end_90 = end_date
serial_end_90 = serial
else:
valid = end_date
serial_valid = serial
res = l.search_s(
"ou=Users,dc=neutrinet,dc=be",
......@@ -213,14 +219,15 @@ for user_id, serials in member_list_serial.items():
if res:
if end_180 and not (end_90 or valid):
print('L\'user %s à un certificat qui à expiré %s' % (
res[0][1]['mail'][0].decode("utf-8"), (datetime.datetime.now() - end_180)))
print('L\'user %s à un certificat qui à expiré %s :: %s' % (
res[0][1]['mail'][0].decode("utf-8"), (datetime.datetime.now() - end_180), serial_end_180))
if end_90 and not valid:
print('L\'user %s à un certificat qui va expiré %s' % (
res[0][1]['mail'][0].decode("utf-8"), (end_90 - datetime.datetime.now())))
print('L\'user %s à un certificat qui va expiré %s :: %s' % (
res[0][1]['mail'][0].decode("utf-8"), (end_90 - datetime.datetime.now()), serial_end_90))
if valid:
print('L\'user %s n\'à pas un certificat qui va expiré %s' % (res[0][1]['mail'][0].decode("utf-8"), valid))
print('L\'user %s n\'à pas un certificat qui va expiré %s :: %s' % (res[0][1]['mail'][0].decode("utf-8"), valid, serial_valid))
l.unbind()
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment