#!/usr/bin/python

# vim:expandtab ts=4
# in order to use the embedded vim commands "set modeline" is required in your .vimrc file

import cgi
#import cgitb
import os
import sqlite3
import time
import hashlib
import base64
#cgitb.enable(display=0, logdir="/tmp")
import subprocess
import datetime
import urllib
from urlparse import urlparse

"""
################
# page templates
################
"""
SCRIPT_PATH='/cgi-bin/override-admin'

title = ''

loginpageerrorhtml="""
                <div id="errormessage">
                    <h1>%s</h1>
                </div>

"""

loginpagehtml="""
<!DOCTYPE html>
<html class="no-js" lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        
        <title>${TITLE}</title>
        
        <meta name="description" content="${TITLE}" />
        <meta name="viewport" content="width=device-width" />
        
        <link rel="icon" href="/favicon.png" type="image/x-icon" />
        
        <link rel="stylesheet" href="/lib/wifi.css?fwauthdlocal=yes"/>
        
        <script src="/lib/modernizr-custom.js?fwauthdlocal=yes"></script>
    </head>
    <body>
        <!--[if lt IE 9]>
    <div class="browser-warning">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">activate Google Chrome Frame</a> to improve your experience.</div>
        <![endif]-->
    
        <div id="wrapper">
            <div id="login">
    
                <div id="header">
                    <img src="/lib/barracuda-logo-header.png?fwauthdlocal=yes" alt="${TITLE}"/>
                </div>
    
                <form action="${SCRIPT_PATH}" method="POST" >
    
                <div id="message">
                    <h1>${TITLE}</h1>
                </div>
    
                %s
                
                <div id="form">
    
                    <input 
                        type="text" 
                        name="user" 
                        size="20" 
                        placeholder="Username"
                        class="formfield"
                        autofocus required
                        accesskey="u"/>
                    <input 
                        type="password" 
                        name="password" 
                        size="20" 
                        placeholder="Password"
                        class="formfield"
                        required
                        autocomplete="off"
                        accesskey="p"/>
    
                    <input 
                        type="submit"
                        value="Login"/>
                </div>
    
                </form>
            </div>
        </div>
    
        <div id="branding"></div>
    </body>
</html>    
"""

ticketingpageheaderhtml="""
<!DOCTYPE html>
<html class="no-js" lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        
        <title>${TITLE}</title>
        
        <meta name="description" content="${TITLE}" />
        <meta name="viewport" content="width=device-width" />
        
        <link rel="icon" href="/favicon.png" type="image/x-icon" />
        
        <link rel="stylesheet" href="/lib/wifi.css?fwauthdlocal=yes"/>
        <link rel="stylesheet" href="/lib/override-admin.css?fwauthdlocal=yes"/>
        
        <script src="/lib/modernizr-custom.js?fwauthdlocal=yes"></script>
    </head>
    <body>
        <!--[if lt IE 9]>
    <div class="browser-warning">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">activate Google Chrome Frame</a> to improve your experience.</div>
        <![endif]-->

        <div id="wrapper">
            <div id="ticketing">
                <noscript>
                <div class="warning">The Override Administration works best with JavaScript enabled.</div>
                </noscript>

                <div id="header">
                    <img src="/lib/barracuda-logo-header.png?fwauthdlocal=yes" alt="${TITLE}"/>
                    <div>${TITLE}</div>
                    <a href="${SCRIPT_PATH}?logout" title="Logout" class="logout"><span>Logout</span></a>
                </div>

                <div id="tickettable">
                    <table >
                        <thead>
                            <tr>
                                <th class="check-column"><input type="checkbox"></th>
                                <th style="width:25%">User name</th>
                                <th>Domain</th>
                                <th style="width:10%">Category</th>
                                <th style="width:10%">Date/time</th>
                                <th style="width:1%">&nbsp;</th>
                            </tr>
                        </thead>
                        <tbody>
"""

ticketingpageformbottomhtml="""
                        </tbody>
                    </table>
                    <div id="selection-actions">
                        <span class="approve-control">
                            <span class="approve-minutes"><input type="number" min="1" max="10080" value="10" step="1"> min.</span>
                            <span class="approve" title="Approve selected requests">
                                <span class="icons"></span>
                                Approve
                            </span>
                            <span class="reject" title="Reject selected requests">
                                <span class="icons"></span>
                                Reject
                            </span>
                        </span>
                    </div>
                </div>
            </div>
        </div>
    
        <div id="branding"></div>
    
        <script src="/lib/jquery-1.9.1.min.js?fwauthdlocal=yes"></script>
        <script src="/lib/override-admin.js?fwauthdlocal=yes"></script>
    </body>
</html>
"""

"""
##################
# helper functions
##################
"""

# Taken from dev/apps/trunk/fwauthd/src/fwauthd/fwauthd_urlfilter.cc
categoryString = [
    "streaming-media", 
    "streaming-radio-tv",
    "advertisements-popups",
    "media-downloads",
    "media-sharing",
    "auctions-classifieds",
    "business",
    "finance-investment",
    "real-estate",
    "shopping",
    "stock-trading",
    "chat",
    "peer-to-peer",
    "web-based-email",
    "instant-messaging",
    "messaging",
    "mobile-communications",
    "online-meetings",
    "web-based-telephony",
    "education-reference",
    "forums-newsgroups",
    "government-legal",
    "health-medicine",
    "job-search-career-development",
    "motor-vehicles",
    "news",
    "advocacy-ngo",
    "religion",
    "history",
    "moderated-forums",
    "political-issues",
    "professional-networking",
    "public-information",
    "technical-business-forums",
    "usenet-news",
    "marketing-merchandising",
    "blogs-wikis",
    "arts-society-culture",
    "comics-humor-jokes",
    "entertainment",
    "food-dining",
    "game-playing-game-media",
    "hobbies-recreation",
    "kids-sites",
    "personals-dating",
    "social-networking",
    "sports",
    "travel",
    "digital-cards",
    "fashion-beauty",
    "hosted-personal-pages",
    "criminal-activity",
    "illegal-drugs",
    "illegal-software",
    "academic-cheating",
    "text-audio-only",
    "adult-content",
    "alcohol-tobacco",
    "gambling",
    "intimate-apparel-swimwear",
    "intolerance-hate",
    "pornography",
    "tasteless-offensive",
    "violence-terrorism",
    "weapons",
    "extremely-offensive",
    "gambling-related",
    "game-cartoon-violence",
    "historical-opinion",
    "incidental-nudity",
    "nudity",
    "profanity",
    "hacking",
    "phishing-fraud",
    "proxies",
    "spam",
    "spyware",
    "proxy-utilities",
    "information-security",
    "malicious-sites",
    "suspicious-sites",
    "computing-technology",
    "content-server",
    "downloads",
    "parked-sites",
    "visual-search",
    "search-engines-portals",
    "software-hardware",
    "interactive-web-applications",
    "online-services",
    "online-storage",
    "remote-access",
    "resource-sharing",
    "technical-information",
    "translators",
    "url-redirectors",
]

def acpfConfirmUserOverride(user, category, ttlMinutes):
    args=['/opt/phion/bin/acpfctrl', 'user', 'confirmcat', 'user', user, str(category), str(ttlMinutes*60)]
    f=open('/dev/null','r+')
    subprocess.call(args, stdin=f, stdout=f, stderr=f)
    f.close()

def acpfConfirmIpOverride(ip, category, ttlMinutes):
    args=['/opt/phion/bin/acpfctrl', 'user', 'confirmcat', 'addr4', ip, str(category), str(ttlMinutes*60)]
    f=open('/dev/null','r+')
    subprocess.call(args, stdin=f, stdout=f, stderr=f)
    f.close()

def escapeJson(message):
    messageNew=''
    for chr in message:
        if chr == '"':
            messageNew+=('\\"')
        elif chr == '\\':
            messageNew+=('\\\\')
        else:
            messageNew+=(chr)    
    return messageNew    

def humanizeTime(timestamp):
    now = time.time()
    delta = int(now - timestamp)
    if delta < 5:
        return 'right now'
    elif delta < 55:
        return str(delta) + ' seconds ago'
    elif delta < 115:
        return 'a minute ago'
    elif delta < 3570:
        return str(int((delta + 5) / 60)) + ' minutes ago'
    elif delta < 3900:
        return 'an hour ago'
    elif delta < 6900:
        return 'one hour and ' + str(int((delta - 3600) / 60)) + ' minutes ago'
    elif delta < 86400:
        return str(int((delta+1800) / 3600)) + ' hours ago'
    elif delta < 172800:
        # TODO: Convert from UTC to local time zone
        return 'yesterday ' + datetime.datetime.utcfromtimestamp(int(timestamp)).strftime('%H:%M')
    else:
        # TODO: Convert from UTC to local time zone
        return datetime.datetime.utcfromtimestamp(int(timestamp)).strftime('%d-%m-%Y %H:%M:%S')

class ScriptException(Exception):
    pass

"""
##################
# HTTP Request parsing
##################
"""
class HttpRequest:
    def __init__(self, form, env):
        self.cookies = {'TicketingAuth':''}
        self.form = form
        self.peerIp = ''
        self.queryString = ''
        self.params = {}        
        
        for cookie in env.get('HTTP_COOKIE',"").split(';'):
            if cookie.find('=')<0: continue
            self.cookies[cookie[0:cookie.find('=')].strip()]=cookie[cookie.find('=')+1:].strip()
        
        
        self.peerIp = env.get('PEERIP',"")        
        
        self.queryString = env.get('QUERY_STRING',"")
        self.params = cgi.parse_qs(self.queryString,True)        
     

"""
##################
# Session management (login/logout and cookie)
##################
"""
class Session:
    def __init__(self, httpRequest, db):
        self.user = ''
        self.cookie = httpRequest.cookies['TicketingAuth']
        self.sessionTimeout = 600
        self.credentialsSent = False
        self.loggedIn = False
        self.loginMessage = ''
                
        # special character handling: db.text_factory = str
        db.text_factory = str
        cursor = db.cursor()

        now = int(time.time())

        if len(self.cookie):
            cursor = db.execute('SELECT user,maxage FROM cookies WHERE cookieid=? LIMIT 1;', (self.cookie,))
            for row in cursor:
                if row[1] < now:       # Cookie expired
                    self.logout(db)
                    self.loginMessage = 'Session expired.'
                    break
                else:
                    self.user = row[0]
                    self.loggedIn = True
                    self.refreshSession(db)
                    break

        cursor.execute('DELETE FROM cookies WHERE maxage<?;', (now,))
        db.commit()

        if self.loggedIn and httpRequest.params.has_key('logout'):            
            self.logout(db)
            self.loginMessage = 'Logged out.'

        elif not self.loggedIn and httpRequest.form.has_key('user') and httpRequest.form.has_key('password'):
            self.login(httpRequest.form, db)

    def checkPassword(self, user, password, db):
        cursor = db.cursor()

        user = user.replace('%', '')
        user = user.replace('\'', '')
        user = user.replace('*', '')
        cursor = db.execute('SELECT password, salt FROM users WHERE username=?;', (user,))
        for row in cursor:
            if row[0] == self.passwordHash(password, row[1]):
                return True
            else:
                return False
        return False

    def createCookie(self):        
        self.cookie = base64.b64encode(os.urandom(10))
      

    def login(self, form, db):
        # special character handling: db.text_factory = str
        db.text_factory = str
        cursor = db.cursor()

        if len(form['user'].value) == 0 or len(form['password'].value) == 0:
            self.user = ''
            self.loggedIn = False
            self.loginMessage = ''
        elif self.checkPassword(form['user'].value, form['password'].value, db):
            self.user = form['user'].value
            self.credentialsSent = True
            self.loggedIn = True
            self.createCookie()
            self.refreshSession(db)
        else:
            self.user = ''
            self.loggedIn = False
            self.loginMessage = 'Wrong username/password'

    def logout(self, db):
        # special character handling: db.text_factory = str
        db.text_factory = str
        cursor = db.cursor()

        cursor.execute('DELETE FROM cookies WHERE cookieid=?;', (self.cookie,))
        db.commit()
        self.user = ''
        self.loggedIn = False
        self.cookie = ''

    def passwordHash(self, password, salt):
        m = hashlib.sha512()
        m.update(password + salt)
        return base64.b64encode(m.digest())

    def refreshSession(self, db):
        # special character handling: db.text_factory = str
        db.text_factory = str
        cursor = db.cursor()

        cursor.execute('INSERT OR REPLACE INTO cookies (cookieid,maxage,user) VALUES (?, ?, ?);', \
        (self.cookie, int(time.time()+self.sessionTimeout), self.user))

        db.commit()

"""
##################
# Responses
##################
"""
class Response:
    def printContent(self, content):
        print self.responseHeader(len(content))
        print content

    def printJsonContent(self, content):
        print self.responseHeader(len(content), 'application/json')
        print content

    def responseHeader(self, contentLength, contentType = 'text/html; charset=ISO-8859-1'):
        result  = 'HTTP/1.1 200 OK\r\n'        
        result += 'Cache-Control: no-cache, no-store\r\n'
        result += 'Content-Type: %s\r\n' % contentType
        result += 'Connection: Close\r\n'
        result += 'Content-Length: %d\r\n' % contentLength
        result += 'X-Frame-Options: SAMEORIGIN\r\n'
        if getattr(self,'cookie',None) and len(self.cookie)>0:
            result += 'Set-Cookie: TicketingAuth=%s; HttpOnly\r\n' % self.cookie
        result += '\r'
        return result

    def send(self):
        pass


class LoginPageResponse(Response):
    def __init__(self, loginMessage):
        self.loginMessage = loginMessage

    def send(self):
        if len(self.loginMessage):
                content = loginpagehtml.replace('${TITLE}', title) % loginpageerrorhtml % self.loginMessage
        else:
                content = loginpagehtml.replace('${TITLE}', title) % self.loginMessage
        content = content.replace('${SCRIPT_PATH}', SCRIPT_PATH)
        self.printContent(content)


class TicketRedirectResponse(Response):
    def send(self):
        content  = '<html>\r\n'
        content += '<body>\r\n'
        content += '  <script>document.location="%s";</script>\r\n' % SCRIPT_PATH
        content += '  <p><a href="%s">Click here to continue.</a></p>\r\n' % SCRIPT_PATH
        content += '</body>\r\n'
        content += '</html>'

        result  = 'HTTP/1.1 302 Found\r\n'
        result += 'Location: %s\r\n' % SCRIPT_PATH
        result += 'Cache-Control: no-cache, no-store\r\n'
        result += 'Content-Type: text/html; charset=ISO-8859-1\r\n'
        result += 'Connection: Close\r\n'
        result += 'Content-Length: %d\r\n' % len(content)
        result += 'X-Frame-Options: SAMEORIGIN\r\n'
        if getattr(self,'cookie',None) and len(self.cookie)>0:
            result += 'Set-Cookie: TicketingAuth=%s; HttpOnly\r\n' % self.cookie
        result += '\r\n'
        result += content

        print result


class TicketResponse(Response):
    def __init__(self, user, db):
        self.user = user
        self.db = db

    def executeQuery(self):
        return self.db.execute('SELECT hash, url, user, source_ip, category, daytime, ttl ' \
                               'FROM request ' \
                               'WHERE request_status=0 AND daytime<=?1 AND daytime+(ttl*60)>=?1 AND (tag IS NULL OR tag=?2) ' \
                               'ORDER BY daytime;', \
                               (int(time.time()),self.user))


class TicketJsonResponse(TicketResponse):
    def overrideJson(self):
        json = '{ "requests": [\n'
        cursor = self.executeQuery()        
        for rownumber,row in enumerate(cursor):
            hash = row[0]
            url = row[1]
            user = row[2]
            sourceIp = row[3]
            category = int(row[4]) - 1
            daytime = row[5]
            ttlMinutes = row[6]

            visibleUser = user
            if visibleUser is None:
                visibleUser = str(sourceIp)
            else:
                if sourceIp is not None and len(sourceIp): visibleUser += ' ('
                visibleUser += sourceIp
                if sourceIp is not None and len(sourceIp): visibleUser += ')'
            
            if category >= 0 and category < len(categoryString):
                friendlyCategory = categoryString[category].replace('_', ' ')
            else:
                friendlyCategory = "Unknown"
                
            friendlyDate = humanizeTime(daytime)
            
            if rownumber > 0:                
                json += ',\n'

            json += '    { "hash": "%s",' % escapeJson(hash)
            json +=      ' "user": "%s",' % escapeJson(visibleUser)
            json +=      ' "url": "%s",' % escapeJson(url)
            json +=      ' "category": "%s",' % escapeJson(friendlyCategory)
            json +=      ' "date": "%s",' % escapeJson(friendlyDate)
            json +=      ' "ttl": %d' % ttlMinutes
            json +=      ' }'

        json += '\n'
        json += ']}'
        return json

    def send(self):
        self.printJsonContent(self.overrideJson())

    
class TicketPageResponse(TicketResponse):
    def overrideList(self):
        html = ''
        cursor = self.executeQuery()
        emptyTable = True
        for row in cursor:
            emptyTable = False
            hash = row[0]
            parsed_uri = urlparse(str(row[1]))
            url = str(parsed_uri.scheme) + "://" + str(parsed_uri.netloc)
            user = row[2]
            sourceIp = row[3]
            category = int(row[4]) - 1
            daytime = row[5]
            ttlMinutes = row[6]

            visibleUser = user
            if visibleUser is None:
                visibleUser = str(sourceIp)
            else:
                if sourceIp is not None and len(sourceIp): visibleUser += ' ('
                visibleUser += sourceIp
                if sourceIp is not None and len(sourceIp): visibleUser += ')'
                
            if category >= 0 and category < len(categoryString):            
                friendlyCategory = categoryString[category].replace('_', ' ')
            else:
                friendlyCategory = "Unknown"
                
            friendlyDate = humanizeTime(daytime)

            # The strange indenting is to prevent spaces between elements that would add margins.
            html += '                            <tr data-override="%s">\n' % escapeJson(hash)
            html += '                                <td><input type="checkbox"></td>\n'
            html += '                                <td>%s</td>\n' % cgi.escape(visibleUser)
            html += '                                <td>%s</td>\n' % cgi.escape(url)
            html += '                                <td>%s</td>\n' % cgi.escape(friendlyCategory)
            html += '                                <td>%s</td>\n' % cgi.escape(friendlyDate)
            html += '                                <td>\n'
            html += '                                    <span class="approve-control">'
            html +=                                         '<span class="approve-minutes">'
            html +=                                             '<input type="number" min="1" max="10080" value="%d" step="1">' % int(ttlMinutes)
            html +=                                             ' min.'
            html +=                                         '</span>\n'
            html += '                                        <a class="approve" href="%s?approve=%s" title="Approve this request">' % (SCRIPT_PATH, escapeJson(hash))
            html +=                                             '<span class="icons">Approve</span>'
            html +=                                         '</a>\n'
            html += '                                        <a class="reject" href="%s?reject=%s" title="Reject this request">' % (SCRIPT_PATH, escapeJson(hash))
            html +=                                             '<span class="icons">Reject</span>'
            html +=                                         '</a>'
            html +=                                     '</span>'
            html +=                                 '</td>\n'
            html += '                            </tr>\n'

        if emptyTable:
            html += '                            <tr id="empty-list-row">\n'
            html += '                                <td colspan="5">No override requests.</td>\n'
            html += '                            </tr>\n'
        return html

    def send(self):
        content = ticketingpageheaderhtml.replace('${TITLE}', title) \
                                         .replace('${SCRIPT_PATH}', SCRIPT_PATH)
        content += self.overrideList()
        content += ticketingpageformbottomhtml
        self.printContent(content)


class JsonSuccessResponse(Response):
    def send(self):
        self.printJsonContent('{ "success": true }\n')


class JsonErrorResponse(Response):
    def __init__(self, errorMessage):
        self.errorMessage = errorMessage

    def send(self):
        # The version of python we have lacks the json module, so we can't use json.dumps() :-(
        if len(self.errorMessage):
            self.printJsonContent('{ "errorMessage": "%s" }\n' % escapeJson(self.errorMessage))
        else:
            self.printJsonContent('{ "errorMessage": "Unknown error." }\n')


"""
##################
# API methods
##################
"""
class Method:
    def isRequested(self, httpRequest):
        return False

    def invoke(self, httpRequest, format, session, db):
        pass


class RequestModificationMethod(Method):
    def invokeModification(self, requestHashes, ttl, format, session, db):
        ttlMinutes = None                                   
        if ttl and len(ttl):
            try:
                ttlMinutes = int(ttl.strip())
                if ttlMinutes < 1 or ttlMinutes > 10080:      # 10080 = 7 days
                    return JsonErrorResponse('The specified number of minutes is not valid. The range should be within 1 and 10080 minutes')
            except:
                return JsonErrorResponse('The specified number of minutes is not valid.')              

        for requestHash in requestHashes.split(','):
            decodedHash = urllib.unquote(requestHash.strip()).decode('utf8')
            errorMessage = self.modifyRequest(decodedHash, ttlMinutes, session.user, db)
            if len(errorMessage):
                if format == 'json':
                    return JsonErrorResponse(errorMessage)
                else:
                    return TicketRedirectResponse()

        if format == 'json':
            return JsonSuccessResponse()
        else:
            return TicketPageResponse(session.user, db)

    def logAction(self, action, requestUser, requestIp, requestCategory, user):
        import phionlibs
        cplog = phionlibs.CPLog("/var/phion/logs/")
        cplogger = phionlibs.CPLogger("box_Firewall_Acknowledged",0,cplog,"")
        cplogger.ILOG(("firewall: [Override] action=%s adminuser=%s user=%s srcIP=%s category=%s" % (action, user, requestUser, requestIp, categoryString[int(requestCategory)-1])).replace("%","%%"))

    def modifyRequest(self, requestHash, ttlMinutes, user, db):
        pass

    def readRequest(self, requestHash, user, db):
        cursor = db.execute('SELECT user, source_ip, category, ttl FROM request WHERE hash=? AND request_status=0 AND (tag IS NULL OR tag=?);', \
                            (requestHash, user));
        for row in cursor:
            requestUser = row[0]
            requestIp = row[1]
            requestCategory = row[2]
            requestTtlMinutes = row[3]
            return (row[0], row[1], row[2], row[3])
        else:
            raise ScriptException('Request not found.')

    def setRequestStatus(self, requestHash, status, ttlMinutes, user, db):
        now = int(time.time())
        if ttlMinutes:
            cursor = db.cursor().execute('UPDATE request SET request_status=?,daytime=?,ttl=? WHERE hash=? AND (tag IS NULL OR tag=?);', \
                                         (status, now, ttlMinutes, requestHash, user))
        else:
            cursor = db.cursor().execute('UPDATE request SET request_status=?,daytime=? WHERE hash=? AND (tag IS NULL OR tag=?);', \
                                         (status, now, requestHash, user))

        affectedRows = cursor.rowcount
        db.commit()
        if affectedRows <= 0:
            raise ScriptException('Request not found.')


class ApproveRequestMethod(RequestModificationMethod):
    def isRequested(self, httpRequest):
        return httpRequest.params.has_key('approve')

    def invoke(self, httpRequest, format, session, db):
        return self.invokeModification(urllib.unquote(''.join(httpRequest.params.get('approve',''))), urllib.unquote(''.join(httpRequest.params.get('ttl',''))), format, session, db)

    def modifyRequest(self, requestHash, ttlMinutes, user, db):
        try:
            (requestUser, requestIp, requestCategory, requestTtlMinutes) = self.readRequest(requestHash, user, db)

            if ttlMinutes:
                requestTtlMinutes = ttlMinutes

            if requestUser is not None and len(requestUser):
                acpfConfirmUserOverride(requestUser, requestCategory, requestTtlMinutes)
            elif len(requestIp):
                acpfConfirmIpOverride(requestIp, requestCategory, requestTtlMinutes)
            else:
                raise ScriptException('The request does not have any requestor user/IP.')

            self.setRequestStatus(requestHash, 1, ttlMinutes, user, db)
            self.logAction('grant', requestUser, requestIp, requestCategory, user)

        except ScriptException, error:
            return str(error)

        return ''


class RejectRequestMethod(RequestModificationMethod):
    def isRequested(self, httpRequest):
        return httpRequest.params.has_key('reject')

    def invoke(self, httpRequest, format, session, db):
        return self.invokeModification(urllib.unquote(''.join(httpRequest.params.get('reject',''))), urllib.unquote(''.join(httpRequest.params.get('ttl',''))), format, session, db)

    def modifyRequest(self, requestHash, ttlMinutes, user, db):
        try:
            (requestUser, requestIp, requestCategory, requestTtlMinutes) = self.readRequest(requestHash, user, db)

            if ttlMinutes:
                requestTtlMinutes = ttlMinutes

            self.setRequestStatus(requestHash, 2, ttlMinutes, user, db)
            self.logAction('reject', requestUser, requestIp, requestCategory, user)

        except ScriptException, error:
            return str(error)

        return ''


class RefreshListMethod(Method):
    def isRequested(self, httpRequest):
        return httpRequest.params.has_key('refresh')

    def invoke(self, httpRequest, format, session, db):
        return TicketJsonResponse(session.user, db)

# This is a chain-of-responsibility design pattern
apiMethods = [ ApproveRequestMethod(), RejectRequestMethod(), RefreshListMethod() ]
        
"""
##################
# Main request processing class
##################
"""
class Request:
    def __init__(self):
        self.httpRequest = HttpRequest(cgi.FieldStorage(), os.environ)
        self.format = ''.join(self.httpRequest.params.get('format', ''))         

    def process(self):
        try:
            db = sqlite3.Connection('/var/phion/preserve/fwauthd/override.db')

            session = Session(self.httpRequest, db)
            if session.loggedIn:
                if session.credentialsSent:
                    response = TicketRedirectResponse()
                else:
                    response = None
                    for method in apiMethods:
                        if method.isRequested(self.httpRequest):                                                       
                            response = method.invoke(self.httpRequest, self.format, session, db)                            
                            if response:
                                break
                    if not response:
                        if self.format == 'json':
                            response = JsonErrorResponse('Unknown method.')
                        else:
                            response = TicketPageResponse(session.user, db)
            else:
                if self.format == 'json':
                    response = JsonErrorResponse('Not logged in.')
                else:
                    response = LoginPageResponse(session.loginMessage)

            response.cookie = session.cookie
            response.send()
            db.close()

        except sqlite3.OperationalError, e:
            if(self.format == 'json'):
                response = JsonErrorResponse(str(e))
            else:
                response = LoginPageResponse(str(e))
            response.send()

"""
#############
# the program
#############
"""
if __name__=="__main__":
    
    title = 'Barracuda CloudGen Firewall Override Administration'
    request = Request()
    request.process()
