<commit_before>from braces.views import LoginRequiredMixin
from django.contrib import messages
from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth.forms import SetPasswordForm
from django.contrib.auth.models import User
from django.contrib.auth.tokens import default_token_generator
from django.core.exceptions import PermissionDenied
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.utils.decorators import method_decorator
from django.utils.http import urlsafe_base64_decode
from django.utils.safestring import mark_safe
from django.views.decorators.debug import sensitive_post_parameters
from django.views.generic import FormView, UpdateView, DetailView, DeleteView
from ratelimit.exceptions import Ratelimited
from ratelimit.mixins import RatelimitMixin
from ratelimit.utils import is_ratelimited

from ..cc_kapi.serializers import KeyboardListItemSerializer

from .forms import EmailUserCreationForm, PasswordResetForm


class RateLimitedFormView(FormView):
    ratelimit_key = 'ip'
    ratelimit_block = True
    ratelimit_rate = '1/h'
    ratelimit_group = None

    def dispatch(self, *args, **kwargs):
        ratelimited = is_ratelimited(request=self.request,
                                     group=self.ratelimit_group,
                                     key=self.ratelimit_key,
                                     rate=self.ratelimit_rate,
                                     increment=False)
        if ratelimited and self.ratelimit_block:
            raise Ratelimited()
        return super(RateLimitedFormView, self).dispatch(*args, **kwargs)


class RegistrationView(RateLimitedFormView):
    template_name = 'accounts/register.html'
    form_class = EmailUserCreationForm
    ratelimit_group = 'registration'

    def form_valid(self, form):
        user = form.save()
        messages.success(self.request,
                         mark_safe(
                             "Successfully registered, you are now logged in! <a href='%s'>View your profile</a>" %
                             reverse('user-detail', kwargs={'pk': user.id})))
        user = authenticate(username=form.cleaned_data['username'],
                            password=form.cleaned_data['password1'])
        login(self.request, user)
        is_ratelimited(request=self.request, group=self.ratelimit_group, key=self.ratelimit_key,
                       rate=self.ratelimit_rate, increment=True)
        return super(RegistrationView, self).form_valid(form)

    def get_success_url(self):
        return reverse('new_count')


class PasswordChangeView(LoginRequiredMixin, FormView):
    template_name = 'accounts/password_change.html'
    form_class = PasswordChangeForm

    def get_form_kwargs(self):
        kwargs = super(PasswordChangeView, self).get_form_kwargs()
        kwargs['user'] = self.request.user
        return kwargs

    def form_valid(self, form):
        form.save()
        messages.success(self.request, "Password changed successfully")
        return HttpResponseRedirect(reverse('new_count'))


class UserDetailView(LoginRequiredMixin, DetailView):
    model = User
    context_object_name = 'user_detail'
    template_name = 'accounts/user_detail.html'

    def get_object(self, queryset=None):
        if self.request.user.id == int(self.kwargs['pk']):
            return super(UserDetailView, self).get_object()
        else:
            raise PermissionDenied

    def get_context_data(self, **kwargs):
        context = super(UserDetailView, self).get_context_data(**kwargs)
        user_keyboards = self.object.keyboard_set.all().order_by('-device_type')
        if hasattr(self.request.user, 'defaultkeyboards'):
            default_desktop = self.request.user.defaultkeyboards.desktop
            default_mobile = self.request.user.defaultkeyboards.mobile
            if default_desktop:
                [user_keyboard._set_default() for user_keyboard in user_keyboards if user_keyboard.id == default_desktop.id]
            if default_mobile:
                [user_keyboard._set_default() for user_keyboard in user_keyboards if user_keyboard.id == default_mobile.id]

        keyboard_list = KeyboardListItemSerializer(user_keyboards, many=True)
        context['keyboards'] = keyboard_list.data

        return context


class UserDeleteView(LoginRequiredMixin, DeleteView):
    model = User
    context_object_name = 'user_object'
    template_name = 'accounts/user_check_delete.html'

    def get_object(self, queryset=None):<commit_msg>Use keyboard marshall to retrieve keyboards<commit_after>from braces.views import LoginRequiredMixin
from django.contrib import messages
from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth.forms import SetPasswordForm
from django.contrib.auth.models import User
from django.contrib.auth.tokens import default_token_generator
from django.core.exceptions import PermissionDenied
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.utils.decorators import method_decorator
from django.utils.http import urlsafe_base64_decode
from django.utils.safestring import mark_safe
from django.views.decorators.debug import sensitive_post_parameters
from django.views.generic import FormView, UpdateView, DetailView, DeleteView
from ratelimit.exceptions import Ratelimited
from ratelimit.mixins import RatelimitMixin
from ratelimit.utils import is_ratelimited

from ..cc_kapi.marshalls import KeyboardLayoutsMarshall

from .forms import EmailUserCreationForm, PasswordResetForm


class RateLimitedFormView(FormView):
    ratelimit_key = 'ip'
    ratelimit_block = True
    ratelimit_rate = '1/h'
    ratelimit_group = None

    def dispatch(self, *args, **kwargs):
        ratelimited = is_ratelimited(request=self.request,
                                     group=self.ratelimit_group,
                                     key=self.ratelimit_key,
                                     rate=self.ratelimit_rate,
                                     increment=False)
        if ratelimited and self.ratelimit_block:
            raise Ratelimited()
        return super(RateLimitedFormView, self).dispatch(*args, **kwargs)


class RegistrationView(RateLimitedFormView):
    template_name = 'accounts/register.html'
    form_class = EmailUserCreationForm
    ratelimit_group = 'registration'

    def form_valid(self, form):
        user = form.save()
        messages.success(self.request,
                         mark_safe(
                             "Successfully registered, you are now logged in! <a href='%s'>View your profile</a>" %
                             reverse('user-detail', kwargs={'pk': user.id})))
        user = authenticate(username=form.cleaned_data['username'],
                            password=form.cleaned_data['<PASSWORD>'])
        login(self.request, user)
        is_ratelimited(request=self.request, group=self.ratelimit_group, key=self.ratelimit_key,
                       rate=self.ratelimit_rate, increment=True)
        return super(RegistrationView, self).form_valid(form)

    def get_success_url(self):
        return reverse('new_count')


class PasswordChangeView(LoginRequiredMixin, FormView):
    template_name = 'accounts/password_change.html'
    form_class = PasswordChangeForm

    def get_form_kwargs(self):
        kwargs = super(PasswordChangeView, self).get_form_kwargs()
        kwargs['user'] = self.request.user
        return kwargs

    def form_valid(self, form):
        form.save()
        messages.success(self.request, "Password changed successfully")
        return HttpResponseRedirect(reverse('new_count'))


class UserDetailView(LoginRequiredMixin, DetailView):
    model = User
    context_object_name = 'user_detail'
    template_name = 'accounts/user_detail.html'

    def get_object(self, queryset=None):
        if self.request.user.id == int(self.kwargs['pk']):
            return super(UserDetailView, self).get_object()
        else:
            raise PermissionDenied

    def get_context_data(self, **kwargs):
        context = super(UserDetailView, self).get_context_data(**kwargs)

        keyboards = KeyboardLayoutsMarshall(self.request.user).get_all()

        # sort keyboards by device_type
        keyboards.sort(key=lambda e: e.device_type)

        # serialize the keyboards
        keyboard_data = []
        for kb in keyboards:
            keyboard_data.append(kb.serialize(many=True))

        context['keyboards'] = keyboard_data

        return context


class UserDeleteView(LoginRequiredMixin, DeleteView):
    model = User
    context_object_name = 'user_object'
    template_name = 'accounts/user_check_delete.html'

    def get_object(self, queryset=None):
{'fraction_non_alphanumeric': 0.08204491592371065, 'fraction_numerical': 0.0007899785577248617, 'mean_word_length': 3.1664315937940763, 'pattern_counts': {'":': 0, '<': 8, '<?xml version=': 0, '>': 8, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7032081', 'n_tokens_mistral': 2474, 'n_tokens_neox': 2408, 'n_words': 514}