| 1 |
|
| 2 |
"""Backend classes should provide common interface""" |
| 3 |
|
| 4 |
import email.utils |
| 5 |
import inspect |
| 6 |
import uuid |
| 7 |
from typing import ClassVar |
| 8 |
from typing import Optional |
| 9 |
from typing import Text |
| 10 |
|
| 11 |
from django.conf import settings |
| 12 |
from django.contrib.auth import authenticate |
| 13 |
from django.contrib.auth import get_user_model |
| 14 |
from django.contrib.auth import login |
| 15 |
from django.contrib.auth.tokens import PasswordResetTokenGenerator |
| 16 |
from django.core.mail import EmailMessage |
| 17 |
from django.http import Http404 |
| 18 |
from django.shortcuts import redirect |
| 19 |
from django.shortcuts import render |
| 20 |
from django.template import loader |
| 21 |
from django.urls import path |
| 22 |
from django.urls import reverse |
| 23 |
from django.utils.translation import gettext as _ |
| 24 |
|
| 25 |
from organizations.backends.forms import UserRegistrationForm |
| 26 |
from organizations.backends.forms import org_registration_form |
| 27 |
from organizations.utils import create_organization |
| 28 |
from organizations.utils import default_org_model |
| 29 |
from organizations.utils import model_field_attr |
| 30 |
|
| 31 |
|
| 32 |
class BaseBackend: |
| 33 |
""" |
| 34 |
Base backend class for registering and inviting users to an organization |
| 35 |
""" |
| 36 |
|
| 37 |
registration_form_template = "organizations/register_form.html" |
| 38 |
activation_success_template = "organizations/register_success.html" |
| 39 |
|
| 40 |
def __init__(self, org_model=None, namespace=None): |
| 41 |
|
| 42 |
self.user_model = get_user_model() |
| 43 |
self.org_model = org_model or default_org_model() |
| 44 |
self.namespace = namespace |
| 45 |
|
| 46 |
def namespace_preface(self): |
| 47 |
return "" if not self.namespace else "{}:".format(self.namespace) |
| 48 |
|
| 49 |
def get_urls(self): |
| 50 |
raise NotImplementedError |
| 51 |
|
| 52 |
def get_success_url(self): |
| 53 |
"""Will return the class's `success_url` attribute unless overridden""" |
| 54 |
raise NotImplementedError |
| 55 |
|
| 56 |
def get_form(self, **kwargs): |
| 57 |
"""Returns the form for registering or inviting a user""" |
| 58 |
if not getattr(self, "form_class", None): |
| 59 |
raise AttributeError("You must define a form_class") |
| 60 |
return self.form_class(**kwargs) |
| 61 |
|
| 62 |
def get_token(self, user, **kwargs): |
| 63 |
"""Returns a unique token for the given user""" |
| 64 |
return PasswordResetTokenGenerator().make_token(user) |
| 65 |
|
| 66 |
def get_username(self): |
| 67 |
""" |
| 68 |
Returns a UUID-based 'random' and unique username. |
| 69 |
|
| 70 |
This is required data for user models with a username field. |
| 71 |
""" |
| 72 |
return str(uuid.uuid4())[ |
| 73 |
: model_field_attr(self.user_model, "username", "max_length") |
| 74 |
] |
| 75 |
|
| 76 |
def activate_organizations(self, user): |
| 77 |
""" |
| 78 |
Activates the related organizations for the user. |
| 79 |
|
| 80 |
It only activates the related organizations by model type - that is, if |
| 81 |
there are multiple types of organizations then only organizations in |
| 82 |
the provided model class are activated. |
| 83 |
""" |
| 84 |
try: |
| 85 |
relation_name = self.org_model().user_relation_name |
| 86 |
except TypeError: |
| 87 |
|
| 88 |
|
| 89 |
relation_name = "organizations_organization" |
| 90 |
organization_set = getattr(user, relation_name) |
| 91 |
for org in organization_set.filter(is_active=False): |
| 92 |
org.is_active = True |
| 93 |
org.save() |
| 94 |
|
| 95 |
def activate_view(self, request, user_id, token): |
| 96 |
""" |
| 97 |
View function that activates the given User by setting `is_active` to |
| 98 |
true if the provided information is verified. |
| 99 |
""" |
| 100 |
try: |
| 101 |
user = self.user_model.objects.get(id=user_id, is_active=False) |
| 102 |
except self.user_model.DoesNotExist: |
| 103 |
raise Http404(_("Your URL may have expired.")) |
| 104 |
|
| 105 |
if not PasswordResetTokenGenerator().check_token(user, token): |
| 106 |
raise Http404(_("Your URL may have expired.")) |
| 107 |
form = self.get_form( |
| 108 |
data=request.POST or None, files=request.FILES or None, instance=user |
| 109 |
) |
| 110 |
if form.is_valid(): |
| 111 |
form.instance.is_active = True |
| 112 |
user = form.save() |
| 113 |
user.set_password(form.cleaned_data["password1"]) |
| 114 |
user.save() |
| 115 |
self.activate_organizations(user) |
| 116 |
user = authenticate( |
| 117 |
username=form.cleaned_data["username"], |
| 118 |
password=form.cleaned_data["password1"], |
| 119 |
) |
| 120 |
if user is None: |
| 121 |
raise Http404(_("Can't authenticate user")) |
| 122 |
login(request, user) |
| 123 |
return redirect(self.get_success_url()) |
| 124 |
return render(request, self.registration_form_template, {"form": form}) |
| 125 |
|
| 126 |
def send_reminder(self, user, sender=None, **kwargs): |
| 127 |
"""Sends a reminder email to the specified user""" |
| 128 |
if user.is_active: |
| 129 |
return False |
| 130 |
token = PasswordResetTokenGenerator().make_token(user) |
| 131 |
kwargs.update({"token": token}) |
| 132 |
self.email_message( |
| 133 |
user, self.reminder_subject, self.reminder_body, sender, **kwargs |
| 134 |
).send() |
| 135 |
|
| 136 |
def email_message( |
| 137 |
self, |
| 138 |
user, |
| 139 |
subject_template, |
| 140 |
body_template, |
| 141 |
sender=None, |
| 142 |
message_class=EmailMessage, |
| 143 |
**kwargs |
| 144 |
): |
| 145 |
""" |
| 146 |
Returns an email message for a new user. This can be easily overridden. |
| 147 |
For instance, to send an HTML message, use the EmailMultiAlternatives message_class |
| 148 |
and attach the additional conent. |
| 149 |
""" |
| 150 |
if sender: |
| 151 |
try: |
| 152 |
display_name = sender.get_full_name() |
| 153 |
except (AttributeError, TypeError): |
| 154 |
display_name = sender.get_username() |
| 155 |
from_email = "%s <%s>" % ( |
| 156 |
display_name, |
| 157 |
email.utils.parseaddr(settings.DEFAULT_FROM_EMAIL)[1], |
| 158 |
) |
| 159 |
reply_to = "%s <%s>" % (display_name, sender.email) |
| 160 |
else: |
| 161 |
from_email = settings.DEFAULT_FROM_EMAIL |
| 162 |
reply_to = from_email |
| 163 |
|
| 164 |
headers = {"Reply-To": reply_to} |
| 165 |
kwargs.update({"sender": sender, "user": user}) |
| 166 |
|
| 167 |
subject_template = loader.get_template(subject_template) |
| 168 |
body_template = loader.get_template(body_template) |
| 169 |
subject = subject_template.render( |
| 170 |
kwargs |
| 171 |
).strip() |
| 172 |
body = body_template.render(kwargs) |
| 173 |
return message_class(subject, body, from_email, [user.email], headers=headers) |
| 174 |
|
| 175 |
|
| 176 |
class RegistrationBackend(BaseBackend): |
| 177 |
""" |
| 178 |
A backend for allowing new users to join the site by creating a new user |
| 179 |
associated with a new organization. |
| 180 |
""" |
| 181 |
|
| 182 |
|
| 183 |
|
| 184 |
activation_subject = "organizations/email/activation_subject.txt" |
| 185 |
activation_body = "organizations/email/activation_body.html" |
| 186 |
reminder_subject = "organizations/email/reminder_subject.txt" |
| 187 |
reminder_body = "organizations/email/reminder_body.html" |
| 188 |
form_class = UserRegistrationForm |
| 189 |
|
| 190 |
def get_success_url(self): |
| 191 |
return reverse("registration_success") |
| 192 |
|
| 193 |
def get_urls(self): |
| 194 |
return [ |
| 195 |
path("complete/", view=self.success_view, name="registration_success"), |
| 196 |
path( |
| 197 |
"<int:user_id>-<token>/", |
| 198 |
view=self.activate_view, |
| 199 |
name="registration_register", |
| 200 |
), |
| 201 |
path("", view=self.create_view, name="registration_create"), |
| 202 |
] |
| 203 |
|
| 204 |
@property |
| 205 |
def urls(self): |
| 206 |
return self.get_urls(), self.namespace or "registration" |
| 207 |
|
| 208 |
def register_by_email(self, email, sender=None, request=None, **kwargs): |
| 209 |
""" |
| 210 |
Returns a User object filled with dummy data and not active, and sends |
| 211 |
an invitation email. |
| 212 |
""" |
| 213 |
try: |
| 214 |
user = self.user_model.objects.get(email=email) |
| 215 |
except self.user_model.DoesNotExist: |
| 216 |
user = self.user_model.objects.create( |
| 217 |
username=self.get_username(), |
| 218 |
email=email, |
| 219 |
password=self.user_model.objects.make_random_password(), |
| 220 |
) |
| 221 |
user.is_active = False |
| 222 |
user.save() |
| 223 |
self.send_activation(user, sender, **kwargs) |
| 224 |
return user |
| 225 |
|
| 226 |
def send_activation(self, user, sender=None, **kwargs): |
| 227 |
""" |
| 228 |
Invites a user to join the site |
| 229 |
""" |
| 230 |
if user.is_active: |
| 231 |
return False |
| 232 |
token = self.get_token(user) |
| 233 |
kwargs.update({"token": token}) |
| 234 |
self.email_message( |
| 235 |
user, self.activation_subject, self.activation_body, sender, **kwargs |
| 236 |
).send() |
| 237 |
|
| 238 |
def create_view(self, request): |
| 239 |
""" |
| 240 |
Initiates the organization and user account creation process |
| 241 |
""" |
| 242 |
if request.user.is_authenticated: |
| 243 |
return redirect("organization_add") |
| 244 |
form = org_registration_form(self.org_model)(request.POST or None) |
| 245 |
if form.is_valid(): |
| 246 |
try: |
| 247 |
user = self.user_model.objects.get(email=form.cleaned_data["email"]) |
| 248 |
except self.user_model.DoesNotExist: |
| 249 |
user = self.user_model.objects.create( |
| 250 |
username=self.get_username(), |
| 251 |
email=form.cleaned_data["email"], |
| 252 |
password=self.user_model.objects.make_random_password(), |
| 253 |
) |
| 254 |
user.is_active = False |
| 255 |
user.save() |
| 256 |
else: |
| 257 |
return redirect("organization_add") |
| 258 |
organization = create_organization( |
| 259 |
user, |
| 260 |
form.cleaned_data["name"], |
| 261 |
form.cleaned_data["slug"], |
| 262 |
is_active=False, |
| 263 |
) |
| 264 |
return render( |
| 265 |
request, |
| 266 |
self.activation_success_template, |
| 267 |
{"user": user, "organization": organization}, |
| 268 |
) |
| 269 |
return render(request, self.registration_form_template, {"form": form}) |
| 270 |
|
| 271 |
def success_view(self, request): |
| 272 |
return render(request, self.activation_success_template, {}) |
| 273 |
|
| 274 |
|
| 275 |
class InvitationBackend(BaseBackend): |
| 276 |
""" |
| 277 |
A backend for inviting new users to join the site as members of an |
| 278 |
organization. |
| 279 |
""" |
| 280 |
|
| 281 |
notification_subject = "organizations/email/notification_subject.txt" |
| 282 |
notification_body = "organizations/email/notification_body.html" |
| 283 |
invitation_subject = "organizations/email/invitation_subject.txt" |
| 284 |
invitation_body = "organizations/email/invitation_body.html" |
| 285 |
reminder_subject = "organizations/email/reminder_subject.txt" |
| 286 |
reminder_body = "organizations/email/reminder_body.html" |
| 287 |
form_class = UserRegistrationForm |
| 288 |
|
| 289 |
def get_success_url(self): |
| 290 |
|
| 291 |
return reverse("organization_list") |
| 292 |
|
| 293 |
def get_urls(self): |
| 294 |
|
| 295 |
return [ |
| 296 |
path( |
| 297 |
"<int:user_id>-<token>/", |
| 298 |
view=self.activate_view, |
| 299 |
name="invitations_register", |
| 300 |
) |
| 301 |
] |
| 302 |
|
| 303 |
def invite_by_email(self, email, sender=None, request=None, **kwargs): |
| 304 |
"""Creates an inactive user with the information we know and then sends |
| 305 |
an invitation email for that user to complete registration. |
| 306 |
|
| 307 |
If your project uses email in a different way then you should make to |
| 308 |
extend this method as it only checks the `email` attribute for Users. |
| 309 |
""" |
| 310 |
try: |
| 311 |
user = self.user_model.objects.get(email=email) |
| 312 |
except self.user_model.DoesNotExist: |
| 313 |
|
| 314 |
if ( |
| 315 |
"username" |
| 316 |
in inspect.getfullargspec(self.user_model.objects.create_user).args |
| 317 |
): |
| 318 |
user = self.user_model.objects.create( |
| 319 |
username=self.get_username(), |
| 320 |
email=email, |
| 321 |
password=self.user_model.objects.make_random_password(), |
| 322 |
) |
| 323 |
else: |
| 324 |
user = self.user_model.objects.create( |
| 325 |
email=email, password=self.user_model.objects.make_random_password() |
| 326 |
) |
| 327 |
user.is_active = False |
| 328 |
user.save() |
| 329 |
self.send_invitation(user, sender, **kwargs) |
| 330 |
return user |
| 331 |
|
| 332 |
def send_invitation(self, user, sender=None, **kwargs): |
| 333 |
"""An intermediary function for sending an invitation email that |
| 334 |
selects the templates, generating the token, and ensuring that the user |
| 335 |
has not already joined the site. |
| 336 |
""" |
| 337 |
if user.is_active: |
| 338 |
return False |
| 339 |
token = self.get_token(user) |
| 340 |
kwargs.update({"token": token}) |
| 341 |
self.email_message( |
| 342 |
user, self.invitation_subject, self.invitation_body, sender, **kwargs |
| 343 |
).send() |
| 344 |
return True |
| 345 |
|
| 346 |
def send_notification(self, user, sender=None, **kwargs): |
| 347 |
""" |
| 348 |
An intermediary function for sending an notification email informing |
| 349 |
a pre-existing, active user that they have been added to a new |
| 350 |
organization. |
| 351 |
""" |
| 352 |
if not user.is_active: |
| 353 |
return False |
| 354 |
self.email_message( |
| 355 |
user, self.notification_subject, self.notification_body, sender, **kwargs |
| 356 |
).send() |
| 357 |
return True |