<commit_before># -*- coding: utf-8 -*-

import logging

from django.conf import settings
from django.contrib import messages
from django.contrib.auth.models import Group
from django.urls import reverse, reverse_lazy
from django.http import HttpResponseRedirect
from django.shortcuts import redirect
from django.utils.decorators import method_decorator
from django.utils.translation import gettext_lazy as _
from django.views.decorators.debug import sensitive_post_parameters
from django.views.generic.base import View, TemplateView
from django.views.generic.edit import FormView

from keystoneclient import exceptions

from storage.utils import delete_swift_account
from actionlogger.actionlogger import ActionLogger
from identity.keystone import Keystone
from identity.forms import (UserForm, CreateUserForm, UpdateUserForm,
                            ProjectForm, DeleteProjectConfirm)

from vault.jsoninfo import JsonInfo
from vault import utils
from vault.models import GroupProjects
from vault.views import (SuperUserMixin, JSONResponseMixin,
                         LoginRequiredMixin, ProjectCheckMixin)


log = logging.getLogger(__name__)
actionlog = ActionLogger()


class WithKeystoneMixin:

    def __init__(self, *args, **kwargs):
        self.keystone = None
        super(WithKeystoneMixin, self).__init__(*args, **kwargs)

    def dispatch(self, request, *args, **kwargs):
        try:
            self.keystone = Keystone(request)
        except exceptions.AuthorizationFailure:
            msg = _('Unable to retrieve Keystone data')
            messages.add_message(request, messages.ERROR, msg)
            log.error(f'{request.user}: {msg}')

            # Redirects user back to previous page
            return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))

        if self.keystone.conn is None:
            msg = _('Authorization error')
            messages.add_message(request, messages.ERROR, msg)
            log.error('Keystone: {}'.format(msg))

        return super(WithKeystoneMixin, self).dispatch(request, *args, **kwargs)


class ListUserView(SuperUserMixin, WithKeystoneMixin, ProjectCheckMixin, TemplateView):
    template_name = "identity/users.html"

    def get_context_data(self, **kwargs):
        context = super(ListUserView, self).get_context_data(**kwargs)
        page = self.request.GET.get('page', 1)

        users = []

        try:
            users = self.keystone.user_list()
        except Exception as e:
            log.exception('{}{}'.format(_('Exception:').encode('UTF-8'), e))
            messages.add_message(self.request, messages.ERROR,
                                 _('Unable to list users'))

        sorted_users = sorted(users, key=lambda l: l.name.lower())
        context['users'] = utils.generic_pagination(sorted_users, page)

        return context


class BaseUserView(SuperUserMixin, WithKeystoneMixin, FormView):
    form_class = UserForm
    success_url = reverse_lazy('change_project')

    def _fill_project_choices(self, form):
        if self.keystone and 'project' in form.fields:
            items = [('', '---')]

            for i in self.keystone.project_list():
                if getattr(i, 'enabled', None):
                    items.append((i.id, i.name))

            form.fields['project'].choices = items

    def _fill_role_choices(self, form):
        if self.keystone and 'role' in form.fields:
            items = [('', '---')]

            for i in self.keystone.role_list():
                items.append((i.id, i.name))

            index = [items.index(item) for item in items if '_member_' in item]

            if index:
                items.pop(index[0])

            form.fields['role'].choices = items

    @method_decorator(sensitive_post_parameters('password', 'password_confirm'))
    def dispatch(self, *args, **kwargs):
        return super(BaseUserView, self).dispatch(*args, **kwargs)

    def get(self, request, *args, **kwargs):
        form = self.get_form(self.form_class)

        self._fill_project_choices(form)
        self._fill_role_choices(form)

        return self.render_to_response(
            self.get_context_data(form=form, **kwargs)
        )

    def get_context_data(self, **kwargs):
        context = super(BaseUserView, self).get_context_data(**kwargs)
        user_id = kwargs.get('user_id')
        form = kwargs.get('form')
<commit_msg>Fixed success_url of form views related to Keystone users<commit_after># -*- coding: utf-8 -*-

import logging

from django.conf import settings
from django.contrib import messages
from django.contrib.auth.models import Group
from django.urls import reverse, reverse_lazy
from django.http import HttpResponseRedirect
from django.shortcuts import redirect
from django.utils.decorators import method_decorator
from django.utils.translation import gettext_lazy as _
from django.views.decorators.debug import sensitive_post_parameters
from django.views.generic.base import View, TemplateView
from django.views.generic.edit import FormView

from keystoneclient import exceptions

from storage.utils import delete_swift_account
from actionlogger.actionlogger import ActionLogger
from identity.keystone import Keystone
from identity.forms import (UserForm, CreateUserForm, UpdateUserForm,
                            ProjectForm, DeleteProjectConfirm)

from vault.jsoninfo import JsonInfo
from vault import utils
from vault.models import GroupProjects
from vault.views import (SuperUserMixin, JSONResponseMixin,
                         LoginRequiredMixin, ProjectCheckMixin)


log = logging.getLogger(__name__)
actionlog = ActionLogger()


class WithKeystoneMixin:

    def __init__(self, *args, **kwargs):
        self.keystone = None
        super(WithKeystoneMixin, self).__init__(*args, **kwargs)

    def dispatch(self, request, *args, **kwargs):
        try:
            self.keystone = Keystone(request)
        except exceptions.AuthorizationFailure:
            msg = _('Unable to retrieve Keystone data')
            messages.add_message(request, messages.ERROR, msg)
            log.error(f'{request.user}: {msg}')

            # Redirects user back to previous page
            return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))

        if self.keystone.conn is None:
            msg = _('Authorization error')
            messages.add_message(request, messages.ERROR, msg)
            log.error('Keystone: {}'.format(msg))

        return super(WithKeystoneMixin, self).dispatch(request, *args, **kwargs)


class ListUserView(SuperUserMixin, WithKeystoneMixin, ProjectCheckMixin, TemplateView):
    template_name = "identity/users.html"

    def get_context_data(self, **kwargs):
        context = super(ListUserView, self).get_context_data(**kwargs)
        page = self.request.GET.get('page', 1)

        users = []

        try:
            users = self.keystone.user_list()
        except Exception as e:
            log.exception('{}{}'.format(_('Exception:').encode('UTF-8'), e))
            messages.add_message(self.request, messages.ERROR,
                                 _('Unable to list users'))

        sorted_users = sorted(users, key=lambda l: l.name.lower())
        context['users'] = utils.generic_pagination(sorted_users, page)

        return context


class BaseUserView(SuperUserMixin, WithKeystoneMixin, FormView):
    form_class = UserForm

    def _fill_project_choices(self, form):
        if self.keystone and 'project' in form.fields:
            items = [('', '---')]

            for i in self.keystone.project_list():
                if getattr(i, 'enabled', None):
                    items.append((i.id, i.name))

            form.fields['project'].choices = items

    def _fill_role_choices(self, form):
        if self.keystone and 'role' in form.fields:
            items = [('', '---')]

            for i in self.keystone.role_list():
                items.append((i.id, i.name))

            index = [items.index(item) for item in items if '_member_' in item]

            if index:
                items.pop(index[0])

            form.fields['role'].choices = items

    @method_decorator(sensitive_post_parameters('password', 'password_confirm'))
    def dispatch(self, request, *args, **kwargs):
        project_name = request.session.get('project_name')
        self.success_url = reverse_lazy('admin_list_users',
                                   kwargs={'project': project_name})
        return super(BaseUserView, self).dispatch(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        form = self.get_form(self.form_class)

        self._fill_project_choices(form)
        self._fill_role_choices(form)

        return self.render_to_response(
            self.get_context_data(form=form, **kwargs)
        )

    def get_context_data(self, **kwargs):
        context = super(BaseUserView, self).get_context_data(**kwargs)
        user_id = kwargs.get('user_id')
        form = kwargs.get('form')

{'fraction_non_alphanumeric': 0.10599488377266154, 'fraction_numerical': 0.0008897786675564454, 'mean_word_length': 2.889273356401384, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2529716', 'n_tokens_mistral': 2562, 'n_tokens_neox': 2458, 'n_words': 598}