Vithon Forum / viforum / forum.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Contributors:
#   Nam T. Nguyen -- 2010
#   Huy Phan      -- 2010
#
# Copyright 2010 vithon.org
# All rights reserved
#

from viforum.util import root_path, BeakerAuthenticationPlugin, \
	IntegerConverter, ConditionList, IdentifierRemover
from os import path
from werkzeug import script, SharedDataMiddleware
from routes.middleware import RoutesMiddleware
from repoze.who.interfaces import IIdentifier
from repoze.who.interfaces import IChallenger
from repoze.who.plugins.openid import make_identification_plugin as make_openid_plugin
from repoze.who.plugins.openid.classifiers import openid_challenge_decider
from repoze.what.middleware import setup_auth as setup_what
from repoze.what.plugins.xml import XMLGroupsAdapter, XMLPermissionsAdapter
from routes import Mapper

import os
import sys
from viforum import config
import logging

beaker_rememberer = BeakerAuthenticationPlugin()
openid = make_openid_plugin(store='mem',
        #store_file_path=r'/tmp/openidstore',
        session_name='beaker.session',
        openid_field='openid',
        login_form_url=os.environ.get('SCRIPT_NAME', '') + '/User/prepare_login',
        login_handler_path=os.environ.get('SCRIPT_NAME', '') + '/User/login',
        logout_handler_path=os.environ.get('SCRIPT_NAME', '') + '/User/logout',
        logged_in_url=os.environ.get('SCRIPT_NAME', '') + '/Forum/list',
        logged_out_url=os.environ.get('SCRIPT_NAME', '') + '/Forum/list',
        rememberer_name='beaker')
openid.classifications = { IIdentifier:['browser'],
                         IChallenger:['browser'] } # only for browser
identifiers = [('openid', openid), ('beaker', beaker_rememberer)]
authenticators = [('openid', openid)]
challengers = [('openid', openid)]
mdproviders = []

groups = {'all': XMLGroupsAdapter(config.GROUP_FILE)}
permissions = {'all': XMLPermissionsAdapter(config.PERMISSION_FILE)}

class DummyWritter(object):
    def write(self, msg):
        pass

def make_auth(app):

    log_stream = DummyWritter()
    import os
    if os.environ.get('WHO_LOG'):
        log_stream = sys.stdout

    middleware = setup_what(
        app = app,
        group_adapters = groups,
        permission_adapters = permissions,
        identifiers = identifiers,
        authenticators = authenticators,
        challengers = challengers,
        mdproviders = mdproviders,
        log_stream = log_stream,
        log_level = logging.DEBUG,
        challenge_decider = openid_challenge_decider,
        )
    return middleware

def make_session(app):
    from beaker.middleware import SessionMiddleware
    opts = {
        'session.timeout': 60 * 30,
        'session.key': config.SESSION_COOKIE_NAME,
        'session.secret': config.COOKIE_SECRET,
        'session.type': 'file',
        'session.data_dir': config.SESSION_STORAGE_PATH,
    }
    app = SessionMiddleware(app, opts)
    return app

def make_app():
    from viforum.application import Application
    return Application(config.DATABASE_URL)

def weave_app():
    # make app
    application = make_app()
        
    # add RoutesMiddleware
    application = RoutesMiddleware(application, url_map,
        use_method_override=False)

    # encapsulate it in a PAS
    application = make_auth(application)
    
    # wrap in a session middleware
    application = make_session(application)

    # Apply a WSGI middleware for static file serving
    application = SharedDataMiddleware(application, {
        '/static':  config.STATIC_CONTENT_PATH,
    })
    
    return application

def make_shell():
    from viforum import model, util
    application = make_app()
    return locals()

url_map = Mapper(controller_scan=['Forum', 'User', 'Thread', 'Post', 'Feed']) # TODO this list must be filled
url_map.connect(None, '/', controller='Forum', action='list')
url_map.connect(None, '/{controller}/{action}', controller='Forum', action='list')
url_map.connect(None, '/{controller}/{action}/{id}',
    controller='Forum', action='show', conditions=dict(function=IntegerConverter(['id'])))
url_map.connect(None, '/{controller}/{action}/{id}/{filename:.*?}{.extension:html}',
    controller='Forum', action='show', conditions=dict(function=\
        ConditionList(
            [IdentifierRemover(['filename', 'extension']), \
            IntegerConverter(['id'])]
            )
        ))

if __name__ == "__main__":
    def close_index():
        print 'Closing index writer'
        from viforum import indexing
        if indexing.writer:
            indexing.writer.commit()
            indexing.writer.close()
    import atexit
    atexit.register(close_index)
    action_runserver = script.make_runserver(weave_app, use_reloader=True)
    action_shell = script.make_shell(make_shell)
    action_initdb = lambda: make_app().init_database()
    script.run()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.