# Copyright (C) 2005 JanRain, Inc.
# Copyright (C) 2009, 2010 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

__all__ = ['action', 'handlers', 'logging', 'request', 'response', 'template']

from apache_openid import handlers
from apache_openid.utils import Session
from request import Request
from response import Response


def protect(apache_request):
    options = apache_request.get_options()
    if options.get('debug', '0') == '1':
        logging.debug_mode = True
    session = Session(apache_request, timeout=3600, lock=False)
    action_path = get_action_path(options, apache_request)
    request = Request(apache_request, action_path, session)
    response = Response(request, action_path, session)
    handler = handlers.Factory(
        request,
        response,
        options,
        session,
        action_path).get_handler(options.get('handler', 'openid'))
    try:
        return handler.protect()
    finally:
        session.save()


def get_action_path(options, apache_request):
    return options.get('action-path', apache_request.hlist.location)
