Changeset - 1ae319cb41b1
[Not reviewed]
default
0 3 0
Anton Schur - 9 years ago 2017-04-06 15:55:55
tonich.sh@gmail.com
middleware: convert check_locking_state to be a separate function

Prepare for use with SSH.
3 files changed with 40 insertions and 40 deletions:
0 comments (0 inline, 0 general)
kallithea/lib/base.py
Show inline comments
 
@@ -139,24 +139,60 @@ def log_in_user(user, remember, is_exter
 

	
 
    session.save()
 

	
 
    log.info('user %s is now authenticated and stored in '
 
             'session, session attrs %s', user.username, cookie)
 

	
 
    # dumps session attrs back to cookie
 
    session._update_cookie_out()
 

	
 
    return auth_user
 

	
 

	
 
def check_locking_state(action, repo_name, user):
 
    """
 
    Checks locking on this repository, if locking is enabled, and if lock
 
    is present. Returns a tuple of make_lock, locked, locked_by. make_lock
 
    can have 3 states: None (do nothing), True (make lock), and False
 
    (release lock). This value is later propagated to hooks, telling them
 
    what to do.
 
    """
 
    locked = False  # defines that locked error should be thrown to user
 
    make_lock = None
 
    repo = Repository.get_by_repo_name(repo_name)
 
    locked_by = repo.locked
 
    if repo and repo.enable_locking:
 
        if action == 'push':
 
            # Check if repo already is locked !, if it is compare users
 
            user_id, _date = locked_by
 
            if user.user_id == user_id:
 
                log.debug('Got push from user %s, now unlocking', user)
 
                # Unlock if we have push from the user who locked
 
                make_lock = False
 
            else:
 
                # Another used tried to push - deny access with something like 423 Locked!
 
                locked = True
 
        if action == 'pull':
 
            if repo.locked[0] and repo.locked[1]:
 
                locked = True
 
            else:
 
                log.debug('Setting lock on repo %s by %s', repo, user)
 
                make_lock = True
 
    else:
 
        log.debug('Repository %s does not have locking enabled', repo)
 
    log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
 
              make_lock, locked, locked_by)
 
    return make_lock, locked, locked_by
 

	
 

	
 
class BasicAuth(paste.auth.basic.AuthBasicAuthenticator):
 

	
 
    def __init__(self, realm, authfunc, auth_http_code=None):
 
        self.realm = realm
 
        self.authfunc = authfunc
 
        self._rc_auth_http_code = auth_http_code
 

	
 
    def build_authentication(self):
 
        head = paste.httpheaders.WWW_AUTHENTICATE.tuples('Basic realm="%s"' % self.realm)
 
        if self._rc_auth_http_code and self._rc_auth_http_code == '403':
 
            # return 403 if alternative http return code is specified in
 
            # Kallithea config
 
@@ -315,60 +351,24 @@ class BaseVCSController(object):
 
            #any other action need at least read permission
 
            if not HasPermissionAnyMiddleware('repository.read',
 
                                              'repository.write',
 
                                              'repository.admin')(user,
 
                                                                  repo_name):
 
                return False
 

	
 
        return True
 

	
 
    def _get_ip_addr(self, environ):
 
        return _get_ip_addr(environ)
 

	
 
    def _check_locking_state(self, action, repo_name, user):
 
        """
 
        Checks locking on this repository, if locking is enabled, and if lock
 
        is present. Returns a tuple of make_lock, locked, locked_by. make_lock
 
        can have 3 states: None (do nothing), True (make lock), and False
 
        (release lock). This value is later propagated to hooks, telling them
 
        what to do.
 
        """
 
        locked = False  # defines that locked error should be thrown to user
 
        make_lock = None
 
        repo = Repository.get_by_repo_name(repo_name)
 
        locked_by = repo.locked
 
        if repo and repo.enable_locking:
 
            if action == 'push':
 
                # Check if repo already is locked !, if it is compare users
 
                user_id, _date = locked_by
 
                if user.user_id == user_id:
 
                    log.debug('Got push from user %s, now unlocking', user)
 
                    # Unlock if we have push from the user who locked
 
                    make_lock = False
 
                else:
 
                    # Another used tried to push - deny access with something like 423 Locked!
 
                    locked = True
 
            if action == 'pull':
 
                if repo.locked[0] and repo.locked[1]:
 
                    locked = True
 
                else:
 
                    log.debug('Setting lock on repo %s by %s', repo, user)
 
                    make_lock = True
 

	
 
        else:
 
            log.debug('Repository %s does not have locking enabled', repo)
 
        log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
 
                  make_lock, locked, locked_by)
 
        return make_lock, locked, locked_by
 

	
 
    def __call__(self, environ, start_response):
 
        start = time.time()
 
        try:
 
            return self._handle_request(environ, start_response)
 
        finally:
 
            log = logging.getLogger('kallithea.' + self.__class__.__name__)
 
            log.debug('Request time: %.3fs', time.time() - start)
 
            meta.Session.remove()
 

	
 

	
 
class BaseController(TGController):
 

	
kallithea/lib/middleware/simplegit.py
Show inline comments
 
@@ -31,25 +31,25 @@ Original author and date, and relevant c
 
import os
 
import re
 
import logging
 
import traceback
 

	
 
from paste.httpheaders import REMOTE_USER, AUTH_TYPE
 
from webob.exc import HTTPNotFound, HTTPForbidden, HTTPInternalServerError, \
 
    HTTPNotAcceptable
 
from kallithea.model.db import Ui
 

	
 
from kallithea.lib.utils2 import safe_str, safe_unicode, fix_PATH, get_server_url, \
 
    _set_extras
 
from kallithea.lib.base import BaseVCSController, WSGIResultCloseCallback
 
from kallithea.lib.base import BaseVCSController, WSGIResultCloseCallback, check_locking_state
 
from kallithea.lib.utils import make_ui, is_valid_repo
 
from kallithea.lib.exceptions import HTTPLockedRC
 
from kallithea.lib.hooks import pre_pull
 
from kallithea.lib import auth_modules
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
GIT_PROTO_PAT = re.compile(r'^/(.+)/(info/refs|git-upload-pack|git-receive-pack)')
 

	
 

	
 
def is_git(environ):
 
@@ -115,25 +115,25 @@ class SimpleGit(BaseVCSController):
 
            'locked_by': [None, None]
 
        }
 

	
 
        #===================================================================
 
        # GIT REQUEST HANDLING
 
        #===================================================================
 
        repo_path = os.path.join(safe_str(self.basepath),str_repo_name)
 
        log.debug('Repository path is %s', repo_path)
 

	
 
        # CHECK LOCKING only if it's not ANONYMOUS USER
 
        if not user.is_default_user:
 
            log.debug('Checking locking on repository')
 
            make_lock, locked, locked_by = self._check_locking_state(action, repo_name, user)
 
            make_lock, locked, locked_by = check_locking_state(action, repo_name, user)
 
            # store the make_lock for later evaluation in hooks
 
            extras.update({'make_lock': make_lock,
 
                           'locked_by': locked_by})
 

	
 
        fix_PATH()
 
        log.debug('HOOKS extras is %s', extras)
 
        baseui = make_ui('db')
 
        self.__inject_extras(repo_path, baseui, extras)
 

	
 
        try:
 
            self._handle_githooks(repo_name, action, baseui, environ)
 
            log.info('%s action on Git repo "%s" by "%s" from %s',
kallithea/lib/middleware/simplehg.py
Show inline comments
 
@@ -28,25 +28,25 @@ Original author and date, and relevant c
 
"""
 

	
 

	
 
import os
 
import logging
 
import traceback
 

	
 
from webob.exc import HTTPNotFound, HTTPForbidden, HTTPInternalServerError, \
 
    HTTPNotAcceptable, HTTPBadRequest
 

	
 
from kallithea.lib.utils2 import safe_str, safe_unicode, fix_PATH, get_server_url, \
 
    _set_extras
 
from kallithea.lib.base import BaseVCSController, WSGIResultCloseCallback
 
from kallithea.lib.base import BaseVCSController, WSGIResultCloseCallback, check_locking_state
 
from kallithea.lib.utils import make_ui, is_valid_repo, ui_sections
 
from kallithea.lib.vcs.utils.hgcompat import RepoError, hgweb_mod
 
from kallithea.lib.exceptions import HTTPLockedRC
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
def is_mercurial(environ):
 
    """
 
    Returns True if request's target is mercurial server - header
 
    ``HTTP_ACCEPT`` of such request would start with ``application/mercurial``.
 
    """
 
@@ -124,25 +124,25 @@ class SimpleHg(BaseVCSController):
 
        #======================================================================
 
        repo_path = os.path.join(safe_str(self.basepath), str_repo_name)
 
        log.debug('Repository path is %s', repo_path)
 

	
 
        # A Mercurial HTTP server will see listkeys operations (bookmarks,
 
        # phases and obsolescence marker) in a different request - we don't
 
        # want to check locking on those
 
        if environ['QUERY_STRING'] == 'cmd=listkeys':
 
            pass
 
        # CHECK LOCKING only if it's not ANONYMOUS USER
 
        elif not user.is_default_user:
 
            log.debug('Checking locking on repository')
 
            make_lock, locked, locked_by = self._check_locking_state(action, repo_name, user)
 
            make_lock, locked, locked_by = check_locking_state(action, repo_name, user)
 
            # store the make_lock for later evaluation in hooks
 
            extras.update({'make_lock': make_lock,
 
                           'locked_by': locked_by})
 

	
 
        fix_PATH()
 
        log.debug('HOOKS extras is %s', extras)
 
        baseui = make_ui('db')
 
        self.__inject_extras(repo_path, baseui, extras)
 

	
 
        try:
 
            log.info('%s action on Mercurial repo "%s" by "%s" from %s',
 
                     action, str_repo_name, safe_str(user.username), ip_addr)
0 comments (0 inline, 0 general)