Changeset - aefc371a2531
[Not reviewed]
beta
0 2 0
Marcin Kuzminski - 15 years ago 2010-11-05 18:38:25
marcin@python-works.com
propagate changes for #48 into simplegit.
Removed obsolete print
2 files changed with 31 insertions and 26 deletions:
0 comments (0 inline, 0 general)
rhodecode/lib/middleware/simplegit.py
Show inline comments
 
@@ -60,89 +60,98 @@ dulserver.DEFAULT_HANDLERS = {
 

	
 
from dulwich.repo import Repo
 
from dulwich.web import HTTPGitApplication
 
from paste.auth.basic import AuthBasicAuthenticator
 
from paste.httpheaders import REMOTE_USER, AUTH_TYPE
 
from rhodecode.lib.auth import authfunc, HasPermissionAnyMiddleware
 
from rhodecode.lib.utils import action_logger, is_git, invalidate_cache, \
 
    check_repo_fast
 
from rhodecode.lib.utils import is_git, invalidate_cache, check_repo_fast
 
from rhodecode.model.user import UserModel
 
from webob.exc import HTTPNotFound, HTTPForbidden, HTTPInternalServerError
 
import logging
 
import os
 
import traceback
 

	
 

	
 
log = logging.getLogger(__name__)
 

	
 
class SimpleGit(object):
 

	
 
    def __init__(self, application, config):
 
        self.application = application
 
        self.config = config
 
        #authenticate this git request using 
 
        self.authenticate = AuthBasicAuthenticator('', authfunc)
 

	
 
        self.ipaddr = '0.0.0.0'
 
        self.repository = None
 
        self.username = None
 
        self.action = None
 
        
 
    def __call__(self, environ, start_response):
 
        if not is_git(environ):
 
            return self.application(environ, start_response)
 

	
 
        
 
        proxy_key = 'HTTP_X_REAL_IP'
 
        def_key = 'REMOTE_ADDR'
 
        self.ipaddr = environ.get(proxy_key, environ.get(def_key, '0.0.0.0'))
 
        
 
        #===================================================================
 
        # AUTHENTICATE THIS GIT REQUEST
 
        #===================================================================
 
        username = REMOTE_USER(environ)
 
        if not username:
 
            self.authenticate.realm = self.config['rhodecode_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)
 

	
 
            
 
        #=======================================================================
 
        # GET REPOSITORY
 
        #=======================================================================
 
        try:
 
            self.repo_name = environ['PATH_INFO'].split('/')[1]
 
            if self.repo_name.endswith('/'):
 
                self.repo_name = self.repo_name.rstrip('/')
 
            repo_name = '/'.join(environ['PATH_INFO'].split('/')[1:])
 
            if repo_name.endswith('/'):
 
                repo_name = repo_name.rstrip('/')
 
            self.repository = repo_name
 
        except:
 
            log.error(traceback.format_exc())
 
            return HTTPInternalServerError()(environ, start_response)
 

	
 
        #===================================================================
 
        # CHECK PERMISSIONS FOR THIS REQUEST
 
        #===================================================================
 
        action = self.__get_action(environ)
 
        if action:
 
        self.action = self.__get_action(environ)
 
        if self.action:
 
            username = self.__get_environ_user(environ)
 
            try:
 
                user = self.__get_user(username)
 
                self.username = user.username
 
            except:
 
                log.error(traceback.format_exc())
 
                return HTTPInternalServerError()(environ, start_response)
 

	
 
            #check permissions for this repository
 
            if action == 'push':
 
            if self.action == 'push':
 
                if not HasPermissionAnyMiddleware('repository.write',
 
                                                  'repository.admin')\
 
                                                    (user, self.repo_name):
 
                                                    (user, repo_name):
 
                    return HTTPForbidden()(environ, start_response)
 

	
 
            else:
 
                #any other action need at least read permission
 
                if not HasPermissionAnyMiddleware('repository.read',
 
                                                  'repository.write',
 
                                                  'repository.admin')\
 
                                                    (user, self.repo_name):
 
                                                    (user, repo_name):
 
                    return HTTPForbidden()(environ, start_response)
 

	
 
            #log action
 
            if action in ('push', 'pull', 'clone'):
 
                proxy_key = 'HTTP_X_REAL_IP'
 
                def_key = 'REMOTE_ADDR'
 
                ipaddr = environ.get(proxy_key, environ.get(def_key, '0.0.0.0'))
 
                self.__log_user_action(user, action, self.repo_name, ipaddr)
 
        self.extras = {'ip':self.ipaddr,
 
                       'username':self.username,
 
                       'action':self.action,
 
                       'repository':self.repository}
 

	
 
        #===================================================================
 
        # GIT REQUEST HANDLING
 
        #===================================================================
 
        self.basepath = self.config['base_path']
 
        self.repo_path = os.path.join(self.basepath, self.repo_name)
 
@@ -153,13 +162,13 @@ class SimpleGit(object):
 
            app = self.__make_app()
 
        except:
 
            log.error(traceback.format_exc())
 
            return HTTPInternalServerError()(environ, start_response)
 

	
 
        #invalidate cache on push
 
        if action == 'push':
 
        if self.action == 'push':
 
            self.__invalidate_cache(self.repo_name)
 
            messages = []
 
            messages.append('thank you for using rhodecode')
 
            return app(environ, start_response)
 
        else:
 
            return app(environ, start_response)
 
@@ -190,15 +199,12 @@ class SimpleGit(object):
 
                       }
 

	
 
            return mapping.get(service_cmd, service_cmd if service_cmd else 'other')
 
        else:
 
            return 'other'
 

	
 
    def __log_user_action(self, user, action, repo, ipaddr):
 
        action_logger(user, action, repo, ipaddr)
 

	
 
    def __invalidate_cache(self, repo_name):
 
        """we know that some change was made to repositories and we should
 
        invalidate the cache to see the changes right away but only for
 
        push requests"""
 
        invalidate_cache('cached_repo_list')
 
        invalidate_cache('full_changelog', repo_name)
rhodecode/lib/middleware/simplehg.py
Show inline comments
 
@@ -32,13 +32,12 @@ from paste.auth.basic import AuthBasicAu
 
from paste.httpheaders import REMOTE_USER, AUTH_TYPE
 
from rhodecode.lib.auth import authfunc, HasPermissionAnyMiddleware
 
from rhodecode.lib.utils import is_mercurial, make_ui, invalidate_cache, \
 
    check_repo_fast, ui_sections
 
from rhodecode.model.user import UserModel
 
from webob.exc import HTTPNotFound, HTTPForbidden, HTTPInternalServerError
 
from rhodecode.lib.utils import action_logger
 
import logging
 
import os
 
import traceback
 

	
 
log = logging.getLogger(__name__)
 

	
 
@@ -117,13 +116,13 @@ class SimpleHg(object):
 
                    return HTTPForbidden()(environ, start_response)
 
                
 
        self.extras = {'ip':self.ipaddr,
 
                       'username':self.username,
 
                       'action':self.action,
 
                       'repository':self.repository}
 
        print self.extras
 

	
 
        #===================================================================
 
        # MERCURIAL REQUEST HANDLING
 
        #===================================================================
 
        environ['PATH_INFO'] = '/'#since we wrap into hgweb, reset the path
 
        self.baseui = make_ui('db')
 
        self.basepath = self.config['base_path']
0 comments (0 inline, 0 general)