Changeset - 55377fdc1fc6
[Not reviewed]
default
0 9 0
Marcin Kuzminski - 15 years ago 2010-08-01 18:36:00
marcin@python-works.com
cleared global application settings.
Made it much more extensible by keeping it key/value in the database.
9 files changed with 46 insertions and 36 deletions:
0 comments (0 inline, 0 general)
pylons_app/controllers/admin/settings.py
Show inline comments
 
@@ -29,13 +29,13 @@ from pylons.controllers.util import abor
 
from pylons.i18n.translation import _
 
from pylons_app.lib import helpers as h
 
from pylons_app.lib.auth import LoginRequired, HasPermissionAllDecorator, \
 
    HasPermissionAnyDecorator
 
from pylons_app.lib.base import BaseController, render
 
from pylons_app.lib.utils import repo2db_mapper, invalidate_cache, \
 
    set_hg_app_config
 
    set_hg_app_config, get_hg_settings
 
from pylons_app.model.db import User, UserLog, HgAppSettings
 
from pylons_app.model.forms import UserForm, ApplicationSettingsForm
 
from pylons_app.model.hg_model import HgModel
 
from pylons_app.model.user_model import UserModel
 
import formencode
 
import logging
 
@@ -61,14 +61,14 @@ class SettingsController(BaseController)
 
    
 
    @HasPermissionAllDecorator('hg.admin')    
 
    def index(self, format='html'):
 
        """GET /admin/settings: All items in the collection"""
 
        # url('admin_settings')
 

	
 
        hgsettings = self.sa.query(HgAppSettings).scalar()
 
        defaults = hgsettings.__dict__ if hgsettings else {}
 
        defaults = get_hg_settings()
 

	
 
        return htmlfill.render(
 
            render('admin/settings/settings.html'),
 
            defaults=defaults,
 
            encoding="UTF-8",
 
            force_defaults=False
 
        )  
 
@@ -103,29 +103,31 @@ class SettingsController(BaseController)
 
        
 
        if setting_id == 'global':
 
            
 
            application_form = ApplicationSettingsForm()()
 
            try:
 
                form_result = application_form.to_python(dict(request.POST))
 
                title = form_result['app_title']
 
                realm = form_result['app_auth_realm']
 
            
 
                try:
 
                    hgsettings = self.sa.query(HgAppSettings).get(1)
 
                    hgsettings.app_auth_realm = realm
 
                    hgsettings.app_title = title
 
                    hgsettings1 = self.sa.query(HgAppSettings).filter(HgAppSettings.app_settings_name == 'title').one()
 
                    hgsettings1.app_settings_value = form_result['hg_app_title'] 
 
                    
 
                    self.sa.add(hgsettings)
 
                    hgsettings2 = self.sa.query(HgAppSettings).filter(HgAppSettings.app_settings_name == 'realm').one()
 
                    hgsettings2.app_settings_value = form_result['hg_app_realm'] 
 
                    
 
                    
 
                    self.sa.add(hgsettings1)
 
                    self.sa.add(hgsettings2)
 
                    self.sa.commit()
 
                    set_hg_app_config(config)
 
                    h.flash(_('Updated application settings'),
 
                            category='success')
 
                                    
 
                except:
 
                    log.error(traceback.format_exc())
 
                    h.flash(_('error occured during chaning application settings'),
 
                    h.flash(_('error occured during updating application settings'),
 
                            category='error')
 
                                
 
                    self.sa.rollback()
 
                    
 

	
 
            except formencode.Invalid as errors:
pylons_app/lib/auth.py
Show inline comments
 
@@ -14,28 +14,28 @@
 
# 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, write to the Free Software
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 
# MA  02110-1301, USA.
 
"""
 
Created on April 4, 2010
 

	
 
@author: marcink
 
"""
 
from beaker.cache import cache_region
 
from pylons import config, session, url, request
 
from pylons.controllers.util import abort, redirect
 
from pylons_app.lib.utils import get_repo_slug
 
from pylons_app.model import meta
 
from pylons_app.model.db import User, Repo2Perm, Repository, Permission
 
from sqlalchemy.exc import OperationalError
 
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
 
import crypt
 
from decorator import decorator
 
import logging
 
"""
 
Created on April 4, 2010
 

	
 
@author: marcink
 
"""
 

	
 
log = logging.getLogger(__name__) 
 

	
 
def get_crypt_password(password):
 
    """
 
    Cryptographic function used for password hashing
 
@@ -183,13 +183,12 @@ def get_user(session):
 
    user = session.get('hg_app_user', AuthUser())
 
    if user.is_authenticated:
 
        user = fill_data(user)
 
        user = fill_perms(user)
 
    session['hg_app_user'] = user
 
    session.save()
 
    print user.permissions
 
    return user
 
        
 
#===============================================================================
 
# CHECK DECORATORS
 
#===============================================================================
 
class LoginRequired(object):
pylons_app/lib/base.py
Show inline comments
 
@@ -13,13 +13,13 @@ from pylons_app.model.hg_model import _g
 
    _get_repos_switcher_cached
 

	
 
class BaseController(WSGIController):
 
    
 
    def __before__(self):
 
        c.hg_app_version = __version__
 
        c.hg_app_name = config['hg_app_name']
 
        c.hg_app_name = config['hg_app_title']
 
        c.repo_name = get_repo_slug(request)
 
        c.cached_repo_list = _get_repos_cached()
 
        c.repo_switcher_list = _get_repos_switcher_cached(c.cached_repo_list)
 
        self.sa = meta.Session
 
    
 
    def __call__(self, environ, start_response):
pylons_app/lib/db_manage.py
Show inline comments
 
@@ -118,24 +118,30 @@ class DbManage(object):
 
        paths = HgAppUi()
 
        paths.ui_section = 'paths'
 
        paths.ui_key = '/'
 
        paths.ui_value = os.path.join(path, '*')
 
        
 
        
 
        hgsettings = HgAppSettings()
 
        hgsettings.app_auth_realm = 'hg-app authentication'
 
        hgsettings.app_title = 'hg-app'
 
        hgsettings1 = HgAppSettings()
 
        
 
        hgsettings1.app_settings_name = 'realm'
 
        hgsettings1.app_settings_value = 'hg-app authentication'
 
        
 
        hgsettings2 = HgAppSettings()
 
        hgsettings2.app_settings_name = 'title'
 
        hgsettings2.app_settings_value = 'hg-app'      
 
        
 
        try:
 
            #self.sa.add(hooks)
 
            self.sa.add(web1)
 
            self.sa.add(web2)
 
            self.sa.add(web3)
 
            self.sa.add(web4)
 
            self.sa.add(paths)
 
            self.sa.add(hgsettings)
 
            self.sa.add(hgsettings1)
 
            self.sa.add(hgsettings2)
 
            self.sa.commit()
 
        except:
 
            self.sa.rollback()
 
            raise        
 
        log.info('created ui config')
 
                    
pylons_app/lib/middleware/simplehg.py
Show inline comments
 
@@ -60,13 +60,13 @@ class SimpleHg(object):
 

	
 
        #===================================================================
 
        # AUTHENTICATE THIS MERCURIAL REQUEST
 
        #===================================================================
 
        username = REMOTE_USER(environ)
 
        if not username:
 
            self.authenticate.realm = self.config['hg_app_auth_realm']
 
            self.authenticate.realm = self.config['hg_app_realm']
 
            result = self.authenticate(environ)
 
            if isinstance(result, str):
 
                AUTH_TYPE.update(environ, 'basic')
 
                REMOTE_USER.update(environ, result)
 
            else:
 
                return result.wsgi_application(environ, start_response)
pylons_app/lib/utils.py
Show inline comments
 
@@ -97,19 +97,23 @@ def get_hg_ui_cached():
 
    return ret
 

	
 

	
 
def get_hg_settings():
 
    try:
 
        sa = meta.Session
 
        ret = sa.query(HgAppSettings).scalar()
 
        ret = sa.query(HgAppSettings).all()
 
    finally:
 
        meta.Session.remove()
 
        
 
    if not ret:
 
        raise Exception('Could not get application settings !')
 
    return ret
 
    settings = {}
 
    for each in ret:
 
        settings['hg_app_' + each.app_settings_name] = each.app_settings_value    
 
    
 
    return settings
 
    
 
def make_ui(read_from='file', path=None, checkpaths=True):        
 
    """
 
    A function that will read python rc files or database
 
    and make an mercurial ui object from read options
 
    
 
@@ -152,14 +156,15 @@ def make_ui(read_from='file', path=None,
 
    
 
    return baseui
 

	
 

	
 
def set_hg_app_config(config):
 
    hgsettings = get_hg_settings()
 
    config['hg_app_auth_realm'] = hgsettings.app_auth_realm
 
    config['hg_app_name'] = hgsettings.app_title
 
    
 
    for k, v in hgsettings.items():
 
        config[k] = v
 

	
 
def invalidate_cache(name, *args):
 
    """Invalidates given name cache"""
 
    
 
    from beaker.cache import region_invalidate
 
    log.info('INVALIDATING CACHE FOR %s', name)
pylons_app/model/db.py
Show inline comments
 
@@ -2,16 +2,16 @@ from pylons_app.model.meta import Base
 
from sqlalchemy.orm import relation, backref
 
from sqlalchemy import *
 
from vcs.utils.lazy import LazyProperty
 

	
 
class HgAppSettings(Base):
 
    __tablename__ = 'hg_app_settings'
 
    __table_args__ = {'useexisting':True}
 
    __table_args__ = (UniqueConstraint('app_settings_name'), {'useexisting':True})
 
    app_settings_id = Column("app_settings_id", INTEGER(), nullable=False, unique=True, default=None, primary_key=True)
 
    app_title = Column("app_title", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    app_auth_realm = Column("auth_realm", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    app_settings_name = Column("app_settings_name", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    app_settings_value = Column("app_settings_value", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 

	
 
class HgAppUi(Base):
 
    __tablename__ = 'hg_app_ui'
 
    __table_args__ = {'useexisting':True}
 
    ui_id = Column("ui_id", INTEGER(), nullable=False, unique=True, default=None, primary_key=True)
 
    ui_section = Column("ui_section", TEXT(length=None, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
pylons_app/model/forms.py
Show inline comments
 
@@ -294,13 +294,13 @@ def RepoSettingsForm(edit=False, old_dat
 

	
 

	
 
def ApplicationSettingsForm():
 
    class _ApplicationSettingsForm(formencode.Schema):
 
        allow_extra_fields = True
 
        filter_extra_fields = False
 
        app_title = UnicodeString(strip=True, min=3, not_empty=True)
 
        app_auth_realm = UnicodeString(strip=True, min=3, not_empty=True)
 
        hg_app_title = UnicodeString(strip=True, min=3, not_empty=True)
 
        hg_app_realm = UnicodeString(strip=True, min=3, not_empty=True)
 
        
 
    return _ApplicationSettingsForm
 
 
 

	
 

	
pylons_app/templates/admin/settings/settings.html
Show inline comments
 
@@ -2,14 +2,12 @@
 
<%inherit file="/base/base.html"/>
 

	
 
<%def name="title()">
 
    ${_('Settings administration')}
 
</%def>
 

	
 

	
 

	
 
<%def name="breadcrumbs_links()">
 
    ${h.link_to(_('Admin'),h.url('admin_home'))} &raquo; ${_('Settings')}
 
</%def>
 

	
 
<%def name="page_nav()">
 
	${self.menu('admin')}
 
@@ -27,13 +25,13 @@
 
    <div class="form">
 
        <!-- fields -->
 
        <h3>${_('Remap and rescan repositories')}</h3>
 
        <div class="fields">
 
			<div class="field">
 
		        <div class="label label-checkbox">
 
		            <label for="-button">${_('rescan option')}:</label>
 
		            <label for="destroy">${_('rescan option')}:</label>
 
		        </div>
 
		        <div class="checkboxes">
 
		            <div class="checkbox">
 
		                ${h.checkbox('destroy',True)}
 
		                <label for="checkbox-1">
 
		                <span class="tooltip" tooltip_title="${h.tooltip(_('In case a repository was deleted from filesystem and there are leftovers in the database check this option to scan obsolete data in database and remove it.'))}">
 
@@ -57,22 +55,22 @@
 
             
 
             <div class="field">
 
                <div class="label">
 
                    <label for="input-small">${_('Application name')}:</label>
 
                </div>
 
                <div class="input">
 
                    ${h.text('app_title',size=30)}
 
                    ${h.text('hg_app_title',size=30)}
 
                </div>
 
             </div>
 
                          
 
            <div class="field">
 
                <div class="label">
 
                    <label for="input-small">${_('Realm text')}:</label>
 
                </div>
 
                <div class="input">
 
                    ${h.text('app_auth_realm',size=30)}
 
                    ${h.text('hg_app_realm',size=30)}
 
                </div>
 
            </div>
 
                                     
 
            <div class="buttons">
 
                ${h.submit('save','save settings',class_="ui-button ui-widget ui-state-default ui-corner-all")}
 
           </div>                                                          
0 comments (0 inline, 0 general)