Exemplo n.º 1
0
    def delete(self, user, cur_user=None):
        if cur_user is None:
            cur_user = getattr(get_current_authuser(), 'username', None)
        user = User.guess_instance(user)

        if user.is_default_user:
            raise DefaultUserException(
                _("You can't remove this user since it is"
                  " crucial for the entire application"))
        if user.repositories:
            repos = [x.repo_name for x in user.repositories]
            raise UserOwnsReposException(
                _('User "%s" still owns %s repositories and cannot be '
                  'removed. Switch owners or remove those repositories: %s')
                % (user.username, len(repos), ', '.join(repos)))
        if user.repo_groups:
            repogroups = [x.group_name for x in user.repo_groups]
            raise UserOwnsReposException(_(
                'User "%s" still owns %s repository groups and cannot be '
                'removed. Switch owners or remove those repository groups: %s')
                % (user.username, len(repogroups), ', '.join(repogroups)))
        if user.user_groups:
            usergroups = [x.users_group_name for x in user.user_groups]
            raise UserOwnsReposException(
                _('User "%s" still owns %s user groups and cannot be '
                  'removed. Switch owners or remove those user groups: %s')
                % (user.username, len(usergroups), ', '.join(usergroups)))
        Session().delete(user)

        from kallithea.lib.hooks import log_delete_user
        log_delete_user(user.get_dict(), cur_user)
Exemplo n.º 2
0
    def create(self, form_data, cur_user=None):
        if not cur_user:
            cur_user = getattr(get_current_authuser(), 'username', None)

        from kallithea.lib.hooks import log_create_user, \
            check_allowed_create_user
        _fd = form_data
        user_data = {
            'username': _fd['username'],
            'password': _fd['password'],
            'email': _fd['email'],
            'firstname': _fd['firstname'],
            'lastname': _fd['lastname'],
            'active': _fd['active'],
            'admin': False
        }
        # raises UserCreationError if it's not allowed
        check_allowed_create_user(user_data, cur_user)
        from kallithea.lib.auth import get_crypt_password

        new_user = User()
        for k, v in form_data.items():
            if k == 'password':
                v = get_crypt_password(v)
            if k == 'firstname':
                k = 'name'
            setattr(new_user, k, v)

        new_user.api_key = generate_api_key()
        Session().add(new_user)
        Session().flush() # make database assign new_user.user_id

        log_create_user(new_user.get_dict(), cur_user)
        return new_user
Exemplo n.º 3
0
    def delete(self, repo, forks=None, fs_remove=True, cur_user=None):
        """
        Delete given repository, forks parameter defines what do do with
        attached forks. Throws AttachedForksError if deleted repo has attached
        forks

        :param repo:
        :param forks: str 'delete' or 'detach'
        :param fs_remove: remove(archive) repo from filesystem
        """
        if not cur_user:
            cur_user = getattr(get_current_authuser(), 'username', None)
        repo = Repository.guess_instance(repo)
        if repo is not None:
            if forks == 'detach':
                for r in repo.forks:
                    r.fork = None
            elif forks == 'delete':
                for r in repo.forks:
                    self.delete(r, forks='delete')
            elif [f for f in repo.forks]:
                raise AttachedForksError()

            old_repo_dict = repo.get_dict()
            try:
                Session().delete(repo)
                if fs_remove:
                    self._delete_filesystem_repo(repo)
                else:
                    log.debug('skipping removal from filesystem')
                log_delete_repository(old_repo_dict, deleted_by=cur_user)
            except Exception:
                log.error(traceback.format_exc())
                raise
Exemplo n.º 4
0
    def create(self, form_data, cur_user=None):
        if not cur_user:
            cur_user = getattr(get_current_authuser(), 'username', None)

        from kallithea.lib.hooks import log_create_user, check_allowed_create_user
        _fd = form_data
        user_data = {
            'username': _fd['username'], 'password': _fd['password'],
            'email': _fd['email'], 'firstname': _fd['firstname'], 'lastname': _fd['lastname'],
            'active': _fd['active'], 'admin': False
        }
        # raises UserCreationError if it's not allowed
        check_allowed_create_user(user_data, cur_user)
        from kallithea.lib.auth import get_crypt_password

        new_user = User()
        for k, v in form_data.items():
            if k == 'password':
                v = get_crypt_password(v)
            if k == 'firstname':
                k = 'name'
            setattr(new_user, k, v)

        new_user.api_key = generate_api_key(form_data['username'])
        self.sa.add(new_user)

        log_create_user(new_user.get_dict(), cur_user)
        return new_user
Exemplo n.º 5
0
    def delete(self, user, cur_user=None):
        if not cur_user:
            cur_user = getattr(get_current_authuser(), 'username', None)
        user = self._get_user(user)

        if user.username == User.DEFAULT_USER:
            raise DefaultUserException(
                _(u"You can't remove this user since it's"
                  " crucial for entire application")
            )
        if user.repositories:
            repos = [x.repo_name for x in user.repositories]
            raise UserOwnsReposException(
                _(u'User "%s" still owns %s repositories and cannot be '
                  'removed. Switch owners or remove those repositories: %s')
                % (user.username, len(repos), ', '.join(repos))
            )
        if user.repo_groups:
            repogroups = [x.group_name for x in user.repo_groups]
            raise UserOwnsReposException(
                _(u'User "%s" still owns %s repository groups and cannot be '
                  'removed. Switch owners or remove those repository groups: %s')
                % (user.username, len(repogroups), ', '.join(repogroups))
            )
        if user.user_groups:
            usergroups = [x.users_group_name for x in user.user_groups]
            raise UserOwnsReposException(
                _(u'User "%s" still owns %s user groups and cannot be '
                  'removed. Switch owners or remove those user groups: %s')
                % (user.username, len(usergroups), ', '.join(usergroups))
            )
        self.sa.delete(user)

        from kallithea.lib.hooks import log_delete_user
        log_delete_user(user.get_dict(), cur_user)
Exemplo n.º 6
0
    def delete(self, repo, forks=None, fs_remove=True, cur_user=None):
        """
        Delete given repository, forks parameter defines what do do with
        attached forks. Throws AttachedForksError if deleted repo has attached
        forks

        :param repo:
        :param forks: str 'delete' or 'detach'
        :param fs_remove: remove(archive) repo from filesystem
        """
        if not cur_user:
            cur_user = getattr(get_current_authuser(), 'username', None)
        repo = Repository.guess_instance(repo)
        if repo is not None:
            if forks == 'detach':
                for r in repo.forks:
                    r.fork = None
            elif forks == 'delete':
                for r in repo.forks:
                    self.delete(r, forks='delete')
            elif [f for f in repo.forks]:
                raise AttachedForksError()

            old_repo_dict = repo.get_dict()
            try:
                Session().delete(repo)
                if fs_remove:
                    self._delete_filesystem_repo(repo)
                else:
                    log.debug('skipping removal from filesystem')
                log_delete_repository(old_repo_dict,
                                      deleted_by=cur_user)
            except Exception:
                log.error(traceback.format_exc())
                raise
Exemplo n.º 7
0
def action_logger(user, action, repo, ipaddr='', sa=None, commit=False):
    """
    Action logger for various actions made by users

    :param user: user that made this action, can be a unique username string or
        object containing user_id attribute
    :param action: action to log, should be on of predefined unique actions for
        easy translations
    :param repo: string name of repository or object containing repo_id,
        that action was made on
    :param ipaddr: optional IP address from what the action was made
    :param sa: optional sqlalchemy session

    """

    if not sa:
        sa = meta.Session()
    # if we don't get explicit IP address try to get one from registered user
    # in tmpl context var
    if not ipaddr:
        ipaddr = getattr(get_current_authuser(), 'ip_addr', '')

    if getattr(user, 'user_id', None):
        user_obj = User.get(user.user_id)
    elif isinstance(user, basestring):
        user_obj = User.get_by_username(user)
    else:
        raise Exception('You have to provide a user object or a username')

    if getattr(repo, 'repo_id', None):
        repo_obj = Repository.get(repo.repo_id)
        repo_name = repo_obj.repo_name
    elif isinstance(repo, basestring):
        repo_name = repo.lstrip('/')
        repo_obj = Repository.get_by_repo_name(repo_name)
    else:
        repo_obj = None
        repo_name = u''

    user_log = UserLog()
    user_log.user_id = user_obj.user_id
    user_log.username = user_obj.username
    user_log.action = safe_unicode(action)

    user_log.repository = repo_obj
    user_log.repository_name = repo_name

    user_log.action_date = datetime.datetime.now()
    user_log.user_ip = ipaddr
    sa.add(user_log)

    log.info('Logging action:%s on %s by user:%s ip:%s',
             action, safe_unicode(repo), user_obj, ipaddr)
    if commit:
        sa.commit()
Exemplo n.º 8
0
def action_logger(user, action, repo, ipaddr='', sa=None, commit=False):
    """
    Action logger for various actions made by users

    :param user: user that made this action, can be a unique username string or
        object containing user_id attribute
    :param action: action to log, should be on of predefined unique actions for
        easy translations
    :param repo: string name of repository or object containing repo_id,
        that action was made on
    :param ipaddr: optional ip address from what the action was made
    :param sa: optional sqlalchemy session

    """

    if not sa:
        sa = meta.Session()
    # if we don't get explicit IP address try to get one from registered user
    # in tmpl context var
    if not ipaddr:
        ipaddr = getattr(get_current_authuser(), 'ip_addr', '')

    if getattr(user, 'user_id', None):
        user_obj = User.get(user.user_id)
    elif isinstance(user, basestring):
        user_obj = User.get_by_username(user)
    else:
        raise Exception('You have to provide a user object or a username')

    if getattr(repo, 'repo_id', None):
        repo_obj = Repository.get(repo.repo_id)
        repo_name = repo_obj.repo_name
    elif isinstance(repo, basestring):
        repo_name = repo.lstrip('/')
        repo_obj = Repository.get_by_repo_name(repo_name)
    else:
        repo_obj = None
        repo_name = ''

    user_log = UserLog()
    user_log.user_id = user_obj.user_id
    user_log.username = user_obj.username
    user_log.action = safe_unicode(action)

    user_log.repository = repo_obj
    user_log.repository_name = repo_name

    user_log.action_date = datetime.datetime.now()
    user_log.user_ip = ipaddr
    sa.add(user_log)

    log.info('Logging action:%s on %s by user:%s ip:%s' %
             (action, safe_unicode(repo), user_obj, ipaddr))
    if commit:
        sa.commit()
Exemplo n.º 9
0
    def create_or_update(self, username, password, email, firstname='',
                         lastname='', active=True, admin=False,
                         extern_type=None, extern_name=None, cur_user=None):
        """
        Creates a new instance if not found, or updates current one

        :param username:
        :param password:
        :param email:
        :param active:
        :param firstname:
        :param lastname:
        :param active:
        :param admin:
        :param extern_name:
        :param extern_type:
        :param cur_user:
        """
        if not cur_user:
            cur_user = getattr(get_current_authuser(), 'username', None)

        from kallithea.lib.auth import get_crypt_password, check_password
        from kallithea.lib.hooks import log_create_user, \
            check_allowed_create_user
        user_data = {
            'username': username, 'password': password,
            'email': email, 'firstname': firstname, 'lastname': lastname,
            'active': active, 'admin': admin
        }
        # raises UserCreationError if it's not allowed
        check_allowed_create_user(user_data, cur_user)

        log.debug('Checking for %s account in Kallithea database', username)
        user = User.get_by_username(username, case_insensitive=True)
        if user is None:
            log.debug('creating new user %s', username)
            new_user = User()
            edit = False
        else:
            log.debug('updating user %s', username)
            new_user = user
            edit = True

        try:
            new_user.username = username
            new_user.admin = admin
            new_user.email = email
            new_user.active = active
            new_user.extern_name = extern_name
            new_user.extern_type = extern_type
            new_user.name = firstname
            new_user.lastname = lastname

            if not edit:
                new_user.api_key = generate_api_key()

            # set password only if creating an user or password is changed
            password_change = new_user.password and \
                not check_password(password, new_user.password)
            if not edit or password_change:
                reason = 'new password' if edit else 'new user'
                log.debug('Updating password reason=>%s', reason)
                new_user.password = get_crypt_password(password) \
                    if password else ''

            if user is None:
                Session().add(new_user)
                Session().flush() # make database assign new_user.user_id

            if not edit:
                log_create_user(new_user.get_dict(), cur_user)

            return new_user
        except (DatabaseError,):
            log.error(traceback.format_exc())
            raise
Exemplo n.º 10
0
    def create_or_update(self, username, password, email, firstname='',
                         lastname='', active=True, admin=False,
                         extern_type=None, extern_name=None, cur_user=None):
        """
        Creates a new instance if not found, or updates current one

        :param username:
        :param password:
        :param email:
        :param active:
        :param firstname:
        :param lastname:
        :param active:
        :param admin:
        :param extern_name:
        :param extern_type:
        :param cur_user:
        """
        if not cur_user:
            cur_user = getattr(get_current_authuser(), 'username', None)

        from kallithea.lib.auth import get_crypt_password, check_password
        from kallithea.lib.hooks import log_create_user, check_allowed_create_user
        user_data = {
            'username': username, 'password': password,
            'email': email, 'firstname': firstname, 'lastname': lastname,
            'active': active, 'admin': admin
        }
        # raises UserCreationError if it's not allowed
        check_allowed_create_user(user_data, cur_user)

        log.debug('Checking for %s account in Kallithea database' % username)
        user = User.get_by_username(username, case_insensitive=True)
        if user is None:
            log.debug('creating new user %s' % username)
            new_user = User()
            edit = False
        else:
            log.debug('updating user %s' % username)
            new_user = user
            edit = True

        try:
            new_user.username = username
            new_user.admin = admin
            new_user.email = email
            new_user.active = active
            new_user.extern_name = safe_unicode(extern_name) if extern_name else None
            new_user.extern_type = safe_unicode(extern_type) if extern_type else None
            new_user.name = firstname
            new_user.lastname = lastname

            if not edit:
                new_user.api_key = generate_api_key(username)

            # set password only if creating an user or password is changed
            password_change = new_user.password and not check_password(password,
                                                            new_user.password)
            if not edit or password_change:
                reason = 'new password' if edit else 'new user'
                log.debug('Updating password reason=>%s' % (reason,))
                new_user.password = get_crypt_password(password) if password else None

            self.sa.add(new_user)

            if not edit:
                log_create_user(new_user.get_dict(), cur_user)
            return new_user
        except (DatabaseError,):
            log.error(traceback.format_exc())
            raise