Changeset - cf128ced8c85
[Not reviewed]
beta
0 4 0
Liad Shani - 14 years ago 2011-10-26 21:59:22
liadff@gmail.com
Improved container-based auth implementation and added support for a reverse-proxy setup (using the X-Forwarded-User header)
4 files changed with 29 insertions and 14 deletions:
0 comments (0 inline, 0 general)
rhodecode/config/deployment.ini_tmpl
Show inline comments
 
@@ -51,12 +51,13 @@ index_dir = %(here)s/data/index
 
app_instance_uuid = ${app_instance_uuid}
 
cut_off_limit = 256000
 
force_https = false 
 
commit_parse_limit = 50
 
use_gravatar = true
 
container_auth_enabled = false
 
proxypass_auth_enabled = false
 

	
 
####################################
 
###        CELERY CONFIG        ####
 
####################################
 
use_celery = false
 
broker.host = localhost
rhodecode/lib/auth.py
Show inline comments
 
@@ -220,12 +220,27 @@ def authenticate(username, password):
 
                pass
 
            except (Exception,):
 
                log.error(traceback.format_exc())
 
                pass
 
    return False
 

	
 
def get_container_username(environ, cfg=config):
 
    from paste.httpheaders import REMOTE_USER
 
    from paste.deploy.converters import asbool
 
    username = REMOTE_USER(environ)
 

	
 
    if not username and asbool(cfg.get('proxypass_auth_enabled', False)):
 
        username = environ.get('HTTP_X_FORWARDED_USER')
 

	
 
    if username:
 
        #Removing realm and domain from username
 
        username = username.partition('@')[0]
 
        username = username.rpartition('\\')[2]
 
        log.debug('Received username %s from container', username)
 

	
 
    return username
 

	
 
class  AuthUser(object):
 
    """
 
    A simple object that handles all attributes of user in RhodeCode
 

	
 
    It does lookup based on API key,given user, or user present in session
 
@@ -235,14 +250,14 @@ class  AuthUser(object):
 
    """
 

	
 
    def __init__(self, user_id=None, api_key=None, username=None):
 

	
 
        self.user_id = user_id
 
        self.api_key = None
 

	
 
        self.username = 'None' if username is None else username
 
        self.username = username
 
        
 
        self.name = ''
 
        self.lastname = ''
 
        self.email = ''
 
        self.is_authenticated = False
 
        self.admin = False
 
        self.permissions = {}
 
@@ -260,33 +275,35 @@ class  AuthUser(object):
 
            is_user_loaded = True
 
        elif self.user_id is not None \
 
            and self.user_id != self.anonymous_user.user_id:
 
            log.debug('Auth User lookup by USER ID %s', self.user_id)
 
            user_model.fill_data(self, user_id=self.user_id)
 
            is_user_loaded = True
 
        elif self.username != 'None':
 
            #Removing realm from username
 
            self.username = self.username.partition('@')[0]
 

	
 
        elif self.username:
 
            log.debug('Auth User lookup by USER NAME %s', self.username)
 
            dbuser = User.get_by_username(self.username)
 
            if dbuser is not None and dbuser.active:
 
                for k, v in dbuser.get_dict().items():
 
                    setattr(self, k, v)
 
                self.set_authenticated()
 
                is_user_loaded = True
 
                log.debug('User %s is now logged in', self.username)
 
                dbuser.update_lastlogin()
 

	
 
        if not is_user_loaded:
 
            if self.anonymous_user.active is True:
 
                user_model.fill_data(self,
 
                                     user_id=self.anonymous_user.user_id)
 
                #then we set this user is logged in
 
                self.is_authenticated = True
 
            else:
 
                self.is_authenticated = False
 

	
 
        if not self.username:
 
            self.username = 'None'
 

	
 
        log.debug('Auth User is now %s', self)
 
        user_model.fill_perms(self)
 

	
 
    @property
 
    def is_admin(self):
 
        return self.admin
rhodecode/lib/base.py
Show inline comments
 
@@ -5,18 +5,16 @@ Provides the BaseController class for su
 
import logging
 

	
 
from pylons import config, tmpl_context as c, request, session, url
 
from pylons.controllers import WSGIController
 
from pylons.controllers.util import redirect
 
from pylons.templating import render_mako as render
 

	
 
from paste.deploy.converters import asbool
 
from paste.httpheaders import REMOTE_USER
 

	
 
from rhodecode import __version__
 
from rhodecode.lib.auth import AuthUser
 
from rhodecode.lib.auth import AuthUser, get_container_username
 
from rhodecode.lib.utils import get_repo_slug
 
from rhodecode.model import meta
 
from rhodecode.model.scm import ScmModel
 
from rhodecode import BACKENDS
 
from rhodecode.model.db import Repository
 

	
 
@@ -44,13 +42,13 @@ class BaseController(WSGIController):
 
        # available in environ['pylons.routes_dict']
 
        try:
 
            # putting this here makes sure that we update permissions each time
 
            api_key = request.GET.get('api_key')
 
            user_id = getattr(session.get('rhodecode_user'), 'user_id', None)
 
            if asbool(config.get('container_auth_enabled', False)):
 
                username = REMOTE_USER(environ)
 
                username = get_container_username(environ)
 
            else:
 
                username = None
 

	
 
            self.rhodecode_user = c.rhodecode_user = AuthUser(user_id, api_key, username)
 
            if not self.rhodecode_user.is_authenticated:
 
                self.rhodecode_user.set_authenticated(
rhodecode/lib/middleware/simplehg.py
Show inline comments
 
@@ -32,13 +32,13 @@ from mercurial.error import RepoError
 
from mercurial.hgweb import hgweb_mod
 

	
 
from paste.auth.basic import AuthBasicAuthenticator
 
from paste.httpheaders import REMOTE_USER, AUTH_TYPE
 

	
 
from rhodecode.lib import safe_str
 
from rhodecode.lib.auth import authfunc, HasPermissionAnyMiddleware
 
from rhodecode.lib.auth import authfunc, HasPermissionAnyMiddleware, get_container_username
 
from rhodecode.lib.utils import make_ui, invalidate_cache, \
 
    is_valid_repo, ui_sections
 
from rhodecode.model.db import User
 

	
 
from webob.exc import HTTPNotFound, HTTPForbidden, HTTPInternalServerError
 

	
 
@@ -111,13 +111,13 @@ class SimpleHg(object):
 
                              'authentication')
 
                #==============================================================
 
                # DEFAULT PERM FAILED OR ANONYMOUS ACCESS IS DISABLED SO WE
 
                # NEED TO AUTHENTICATE AND ASK FOR AUTH USER PERMISSIONS
 
                #==============================================================
 

	
 
                if not REMOTE_USER(environ):
 
                if not get_container_username(environ, self.config):
 
                    self.authenticate.realm = \
 
                        safe_str(self.config['rhodecode_realm'])
 
                    result = self.authenticate(environ)
 
                    if isinstance(result, str):
 
                        AUTH_TYPE.update(environ, 'basic')
 
                        REMOTE_USER.update(environ, result)
 
@@ -127,14 +127,13 @@ class SimpleHg(object):
 
                #==============================================================
 
                # CHECK PERMISSIONS FOR THIS REQUEST USING GIVEN USERNAME FROM
 
                # BASIC AUTH
 
                #==============================================================
 

	
 
                if action in ['pull', 'push']:
 
                    #Removing realm from username
 
                    username = REMOTE_USER(environ).partition('@')[0]
 
                    username = get_container_username(environ, self.config)
 
                    try:
 
                        user = self.__get_user(username)
 
                        if user is None:
 
                            return HTTPForbidden()(environ, start_response)
 
                        username = user.username
 
                    except:
0 comments (0 inline, 0 general)