#!/usr/bin/env python

'''
delete all django sessions:
* if pfsenseid exists in session but is not in captiveportal.db
* if session is expired
'''

# initialise django environnement for pffedportal
# note : the script must be launch into the pffedportal direcory
import os
os.environ['DJANGO_SETTINGS_MODULE'] = "settings"

import csv
import datetime
from django.conf import settings
from django.contrib.sessions.backends.file import SessionStore

# load pfsenseid list from captiveportal.db
pfsenseids = [l[5] for l in csv.reader(open('/var/db/captiveportal.db'))]

storage_path = settings.SESSION_FILE_PATH
file_prefix = settings.SESSION_COOKIE_NAME

for session_file in os.listdir(storage_path):
    if not session_file.startswith(file_prefix):
        continue
    session_key = session_file[len(file_prefix):]
    session = SessionStore(session_key)
    # When an expired session is loaded, its file is removed, and a
    # new file is immediately created. Prevent this by disabling
    # the create() method.
    session.create = lambda: None

    session_data = session.load()

    # pfsenseid doesn't exist in captiveportal.db
    if session_data.get('pfsenseid') and session_data['pfsenseid'] not in pfsenseids:
        session.delete()
        continue

    # expired
    modification = os.stat(session._key_to_file()).st_ctime
    age = datetime.datetime.now() - datetime.datetime.fromtimestamp(modification)
    if age.seconds > session.get_expiry_age():
        session.delete()
        continue

