fix
[cas.git] / src / accounts / views.py
1 from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin
2 from django.contrib.auth.models import User
3 from django.contrib import messages
4 from django.core.mail import send_mail
5 from django.urls import reverse_lazy
6 from django.utils.translation import gettext as _
7 from django.views.generic.edit import UpdateView, FormView
8 from accounts.forms import UserBasicForm, OnboardingForm
9 from accounts.models import OnboardingEmail
10 from .utils import make_random_password
11
12
13 class ProfileView(LoginRequiredMixin, UpdateView):
14     form_class = UserBasicForm
15     template_name = "account/profile.html"
16     success_url = '/accounts/'
17
18     def get_object(self):
19         return self.request.user
20
21     def form_valid(self, form):
22         retval = super().form_valid(form)
23         messages.add_message(self.request, messages.INFO, _("Profile has been changed."))
24         return retval
25
26
27 class OnboardingView(PermissionRequiredMixin, FormView):
28     permission_required = 'auth.add_user'
29     form_class = OnboardingForm
30     template_name = "account/onboarding.html"
31     success_url = reverse_lazy('onboarding')
32
33     def form_valid(self, form):
34         # Generate random password
35         password = make_random_password(length=12)
36
37         # Create user
38         user = User.objects.create_user(
39             username=form.cleaned_data['username'],
40             email=form.cleaned_data['email'],
41             password=password,
42             first_name=form.cleaned_data['first_name'],
43             last_name=form.cleaned_data['last_name'],
44         )
45
46         # Send onboarding email
47         template = OnboardingEmail.objects.first()
48         if template:
49             body = template.body.format(
50                 username=user.username,
51                 password=password,
52                 first_name=user.first_name,
53                 last_name=user.last_name,
54             )
55             send_mail(
56                 template.subject,
57                 body,
58                 None,  # Use DEFAULT_FROM_EMAIL
59                 [form.cleaned_data['email']],
60             )
61             messages.success(
62                 self.request,
63                 _("User %(username)s has been created and email sent to %(email)s.") % {
64                     'username': user.username,
65                     'email': form.cleaned_data['email'],
66                 }
67             )
68         else:
69             messages.warning(
70                 self.request,
71                 _("User %(username)s has been created, but no email template is configured.") % {
72                     'username': user.username,
73                 }
74             )
75
76         return super().form_valid(form)