Changeset - 1bb0fcdec895
[Not reviewed]
beta
0 6 0
Marcin Kuzminski - 15 years ago 2010-11-18 03:29:23
marcin@python-works.com
fixed #72 show warning on removal when user still is owner of existing repositories
cleaned up exceptions
6 files changed with 52 insertions and 25 deletions:
0 comments (0 inline, 0 general)
rhodecode/controllers/admin/users.py
Show inline comments
 
@@ -24,18 +24,19 @@ users controller for pylons
 
"""
 

	
 
from formencode import htmlfill
 
from pylons import request, session, tmpl_context as c, url
 
from pylons.controllers.util import abort, redirect
 
from pylons.i18n.translation import _
 
from rhodecode.lib.exceptions import *
 
from rhodecode.lib import helpers as h
 
from rhodecode.lib.auth import LoginRequired, HasPermissionAllDecorator
 
from rhodecode.lib.base import BaseController, render
 
from rhodecode.model.db import User, UserLog
 
from rhodecode.model.db import User
 
from rhodecode.model.forms import UserForm
 
from rhodecode.model.user import UserModel, DefaultUserException
 
from rhodecode.model.user import UserModel
 
import formencode
 
import logging
 
import traceback
 

	
 
log = logging.getLogger(__name__)
 

	
 
@@ -132,13 +133,13 @@ class UsersController(BaseController):
 
        #           method='delete')
 
        # url('user', id=ID)
 
        user_model = UserModel()
 
        try:
 
            user_model.delete(id)
 
            h.flash(_('sucessfully deleted user'), category='success')
 
        except DefaultUserException, e:
 
        except (UserOwnsReposException, DefaultUserException), e:
 
            h.flash(str(e), category='warning')
 
        except Exception:
 
            h.flash(_('An error occured during deletion of user'),
 
                    category='error')
 
        return redirect(url('users'))
 

	
rhodecode/lib/auth.py
Show inline comments
 
@@ -21,14 +21,15 @@
 
Created on April 4, 2010
 

	
 
@author: marcink
 
"""
 
from pylons import config, session, url, request
 
from pylons.controllers.util import abort, redirect
 
from rhodecode.lib.exceptions import *
 
from rhodecode.lib.utils import get_repo_slug
 
from rhodecode.lib.auth_ldap import AuthLdap, UsernameError, PasswordError
 
from rhodecode.lib.auth_ldap import AuthLdap
 
from rhodecode.model import meta
 
from rhodecode.model.user import UserModel
 
from rhodecode.model.caching_query import FromCache
 
from rhodecode.model.db import User, RepoToPerm, Repository, Permission, \
 
    UserToPerm
 
import bcrypt
 
@@ -126,13 +127,13 @@ def authfunc(environ, username, password
 
                authenticated = res[1]['uid'][0] == username
 

	
 
                if authenticated and user_model.create_ldap(username, password):
 
                    log.info('created new ldap user')
 

	
 
                return authenticated
 
            except (UsernameError, PasswordError):
 
            except (LdapUsernameError, LdapPasswordError):
 
                return False
 
            except:
 
                log.error(traceback.format_exc())
 
                return False
 
    return False
 

	
rhodecode/lib/auth_ldap.py
Show inline comments
 
#==============================================================================
 
# LDAP
 
#Name     = Just a description for the auth modes page
 
#Host     = DepartmentName.OrganizationName.local/ IP
 
#Port     = 389 default for ldap
 
#LDAPS    = no set True if You need to use ldaps
 
#Account  = DepartmentName\UserName (or UserName@MyDomain depending on AD server)
 
#Password = <password>
 
#Base DN  = DC=DepartmentName,DC=OrganizationName,DC=local
 
#!/usr/bin/env python
 
# encoding: utf-8
 
# ldap authentication lib
 
# Copyright (C) 2009-2010 Marcin Kuzminski <marcin@python-works.com>
 
#
 
# This program is free software; you can redistribute it and/or
 
# modify it under the terms of the GNU General Public License
 
# as published by the Free Software Foundation; version 2
 
# of the License or (at your opinion) any later version of the license.
 
# 
 
# This program is distributed in the hope that it will be useful,
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
# 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 Nov 17, 2010
 

	
 
#==============================================================================
 
@author: marcink
 
"""
 

	
 
from rhodecode.lib.exceptions import LdapImportError, UsernameError, \
 
    PasswordError, ConnectionError
 
from rhodecode.lib.exceptions import *
 
import logging
 

	
 
log = logging.getLogger(__name__)
 

	
 
try:
 
    import ldap
 
@@ -58,13 +70,13 @@ class AuthLdap(object):
 
        from rhodecode.lib.helpers import chop_at
 

	
 
        uid = chop_at(username, "@%s" % self.LDAP_SERVER_ADDRESS)
 
        dn = self.AUTH_DN % (uid, self.BASE_DN)
 
        log.debug("Authenticating %r at %s", dn, self.LDAP_SERVER)
 
        if "," in username:
 
            raise UsernameError("invalid character in username: ,")
 
            raise LdapUsernameError("invalid character in username: ,")
 
        try:
 
            ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, '/etc/openldap/cacerts')
 
            ldap.set_option(ldap.OPT_NETWORK_TIMEOUT, 10)
 
            server = ldap.initialize(self.LDAP_SERVER)
 
            if self.ldap_version == 2:
 
                server.protocol = ldap.VERSION2
 
@@ -79,15 +91,15 @@ class AuthLdap(object):
 
            server.simple_bind_s(dn, password)
 
            properties = server.search_s(dn, ldap.SCOPE_SUBTREE)
 
            if not properties:
 
                raise ldap.NO_SUCH_OBJECT()
 
        except ldap.NO_SUCH_OBJECT, e:
 
            log.debug("LDAP says no such user '%s' (%s)", uid, username)
 
            raise UsernameError()
 
            raise LdapUsernameError()
 
        except ldap.INVALID_CREDENTIALS, e:
 
            log.debug("LDAP rejected password for user '%s' (%s)", uid, username)
 
            raise PasswordError()
 
            raise LdapPasswordError()
 
        except ldap.SERVER_DOWN, e:
 
            raise ConnectionError("LDAP can't access authentication server")
 
            raise LdapConnectionError("LDAP can't access authentication server")
 

	
 
        return properties[0]
 

	
rhodecode/lib/exceptions.py
Show inline comments
 
@@ -20,10 +20,13 @@
 
"""
 
Created on Nov 17, 2010
 
Custom Exceptions modules
 
@author: marcink
 
"""
 

	
 
class UsernameError(Exception):pass
 
class PasswordError(Exception):pass
 
class ConnectionError(Exception):pass
 
class LdapUsernameError(Exception):pass
 
class LdapPasswordError(Exception):pass
 
class LdapConnectionError(Exception):pass
 
class LdapImportError(Exception):pass
 

	
 
class DefaultUserException(Exception):pass
 
class UserOwnsReposException(Exception):pass
rhodecode/model/db.py
Show inline comments
 
@@ -45,12 +45,14 @@ class User(Base):
 
    last_login = Column("last_login", DATETIME(timezone=False), nullable=True, unique=None, default=None)
 
    is_ldap = Column("is_ldap", BOOLEAN(), nullable=False, unique=None, default=False)
 

	
 
    user_log = relation('UserLog', cascade='all')
 
    user_perms = relation('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
 

	
 
    repositories = relation('Repository')
 

	
 
    @LazyProperty
 
    def full_contact(self):
 
        return '%s %s <%s>' % (self.name, self.lastname, self.email)
 

	
 
    def __repr__(self):
 
        return "<User('id:%s:%s')>" % (self.user_id, self.username)
rhodecode/model/user.py
Show inline comments
 
@@ -24,18 +24,19 @@ Model for users
 
"""
 

	
 
from pylons.i18n.translation import _
 
from rhodecode.model.caching_query import FromCache
 
from rhodecode.model.db import User
 
from rhodecode.model.meta import Session
 
from rhodecode.lib.exceptions import *
 
import logging
 
import traceback
 

	
 
log = logging.getLogger(__name__)
 

	
 
class DefaultUserException(Exception):pass
 

	
 

	
 
class UserModel(object):
 

	
 
    def __init__(self):
 
        self.sa = Session()
 

	
 
@@ -125,12 +126,13 @@ class UserModel(object):
 
        try:
 
            new_user = self.get(user_id, cache=False)
 
            if new_user.username == 'default':
 
                raise DefaultUserException(
 
                                _("You can't Edit this user since it's"
 
                                  " crucial for entire application"))
 

	
 
            for k, v in form_data.items():
 
                if k == 'new_password' and v != '':
 
                    new_user.password = v
 
                else:
 
                    setattr(new_user, k, v)
 

	
 
@@ -166,12 +168,18 @@ class UserModel(object):
 
        try:
 
            user = self.get(user_id, cache=False)
 
            if user.username == 'default':
 
                raise DefaultUserException(
 
                                _("You can't remove this user since it's"
 
                                  " crucial for entire application"))
 
            if user.repositories:
 
                raise UserOwnsReposException(_('This user still owns %s '
 
                                               'repositories and cannot be '
 
                                               'removed. Switch owners or '
 
                                               'remove those repositories') \
 
                                               % user.repositories)
 
            self.sa.delete(user)
 
            self.sa.commit()
 
        except:
 
            log.error(traceback.format_exc())
 
            self.sa.rollback()
 
            raise
0 comments (0 inline, 0 general)