def pre_social_login(self, request, sociallogin): """ Invoked just after a user successfully authenticates via a social provider, but before the login is actually processed. We use it to: 1. Check if the user is connecting accounts via signup page 2. store the name of the socialaccount provider in the user's session. """ session_login_data = request.session.get('socialaccount_sociallogin', None) request_login = sociallogin # Is there already a sociallogin_provider in the session? if session_login_data: session_login = SocialLogin.deserialize(session_login_data) # If the provider in the session is different from the provider in the # request, the user is connecting a new provider to an existing account if session_login.account.provider != request_login.account.provider: # Does the request sociallogin match an existing user? if not request_login.is_existing: # go straight back to signup page with an error message # BEFORE allauth over-writes the session sociallogin level = messages.ERROR message = "socialaccount/messages/account_not_found.txt" get_adapter().add_message(request, level, message) raise ImmediateHttpResponse( redirect('socialaccount_signup') ) # TODO: Can the code that uses this just use request.session['socialaccount_sociallogin'].account.provider instead? request.session['sociallogin_provider'] = (sociallogin .account.provider) request.session.modified = True
def form_valid(self, form): """ We use the selected email here and reset the social loging list of email addresses before they get created. We send our welcome email via celery during complete_signup. So, we need to manually commit the user to the db for it. """ selected_email = form.cleaned_data["email"] if selected_email == form.other_email_value: email_address = {"email": form.cleaned_data["other_email"], "verified": False, "primary": True} else: email_address = self.email_addresses.get(selected_email, None) if email_address: email_address["primary"] = True self.sociallogin.email_addresses = [EmailAddress(*email_address)] if email_address["verified"]: # we have to stash the selected email address here # so that no email verification is sent again # this is done by adding the email address to the session get_adapter().stash_verified_email(self.request, email_address["email"]) with transaction.commit_on_success(): form.save(self.request) return helpers.complete_social_signup(self.request, self.sociallogin)
def send(self, request, signup=False, **kwargs): """ Overridden method to enable passing kwargs to the email template. """ activate_view = kwargs.pop('activate_view', 'account_confirm_email') current_site = kwargs["site"] if "site" in kwargs \ else Site.objects.get_current() activate_url = reverse(activate_view, args=[self.key]) activate_url = request.build_absolute_uri(activate_url) ctx = { "user": self.email_address.user, "activate_url": activate_url, "current_site": current_site, "key": self.key, } ctx.update(**kwargs) if signup: email_template = 'account/email/email_confirmation_signup' else: email_template = 'account/email/email_confirmation' get_adapter().send_mail(email_template, self.email_address.email, ctx) self.sent = timezone.now() self.save() signals.email_confirmation_sent.send(sender=self.__class__, confirmation=self)
def save(self, **kwargs): email = self.cleaned_data["email"] token_generator = kwargs.get("token_generator", default_token_generator) for user in self.users: temp_key = token_generator.make_token(user) # save it to the password reset model # password_reset = PasswordReset(user=user, temp_key=temp_key) # password_reset.save() current_site = Site.objects.get_current() # send the password reset email path = reverse("account_reset_password_from_key", kwargs=dict(uidb36=int_to_base36(user.id), key=temp_key)) url = '%s%s' % (WEBSITE_HOMEPAGE, path[1:]) context = {"site": current_site, "user": user, "password_reset_url": url} get_adapter().send_mail('account/email/password_reset_key', email, context) return self.cleaned_data["email"]
def form_valid(self, form): """ We use the selected email here and reset the social loging list of email addresses before they get created. We send our welcome email via celery during complete_signup. So, we need to manually commit the user to the db for it. """ selected_email = form.cleaned_data['email'] if form.other_email_used: email_address = { 'email': selected_email, 'verified': False, 'primary': True, } else: email_address = self.email_addresses.get(selected_email, None) if email_address: email_address['primary'] = True primary_email_address = EmailAddress(**email_address) form.sociallogin.email_addresses = \ self.sociallogin.email_addresses = [primary_email_address] if email_address['verified']: # we have to stash the selected email address here # so that no email verification is sent again # this is done by adding the email address to the session get_adapter().stash_verified_email(self.request, email_address['email']) with transaction.atomic(): form.save(self.request) return helpers.complete_social_signup(self.request, self.sociallogin)
def send_invitation(self, request, **kwargs): current_site = (kwargs['site'] if 'site' in kwargs else Site.objects.get_current()) invite_url = reverse('invitations:accept-invite', args=[self.key]) invite_url = request.build_absolute_uri(invite_url) ctx = { 'invite_url': invite_url, 'current_site': current_site, 'email': self.email, 'key': self.key, } email_template = 'invitations/email/email_invite' get_adapter().send_mail(email_template, self.email, ctx) self.sent = timezone.now() self.save() signals.invite_url_sent.send( sender=self.__class__, instance=self, invite_url_sent=invite_url)
def send_confirmation_mail(self, request, emailconfirmation, signup): current_site = get_current_site(request) activate_url = self.get_email_confirmation_url( request, emailconfirmation) badgr_app = get_session_badgr_app(request) if not badgr_app: badgr_app = BadgrApp.objects.get_current(request, raise_exception=False) ctx = { "user": emailconfirmation.email_address.user, "email": emailconfirmation.email_address, "activate_url": activate_url, "current_site": current_site, "key": emailconfirmation.key, "badgr_app": badgr_app } if signup == 'canvas': email_template = 'account/email/email_confirmation_canvas' elif signup: email_template = 'account/email/email_confirmation_signup' else: email_template = 'account/email/email_confirmation' get_adapter().send_mail(email_template, emailconfirmation.email_address.email, ctx)
def send(self, request, email, **kwargs): """ Generates an email message with a link to the ExamResponse form. The link is generated using self.key. This function calls get_adapter() from django-allauth and uses allauth's send_mail function. """ current_site = Site.objects.get_current() test_url = reverse("take_test_IRB", args=[self.key]) test_url = request.build_absolute_uri(test_url) # The ctx dictionary is a way to create variables to be used in the message # template (no need to get into the send_mail function below.) ctx = { "test_url": test_url, "current_site": current_site, "key": self.key, "expiration": self.expiration_datetime } # email_template is a prefix, '_message.txt' or '_subject.txt' will be added email_template = 'exam/email_test' # get_adapter and send_mail depend on django-allauth get_adapter().send_mail(email_template, email, ctx) self.sent = timezone.now() self.save()
def save(self, request, **kwargs): email = self.cleaned_data["email"] token_generator = kwargs.get("token_generator", default_token_generator) for user in self.users: temp_key = token_generator.make_token(user) # save it to the password reset model # password_reset = PasswordReset(user=user, temp_key=temp_key) # password_reset.save() current_site = get_current_site(request) # send the password reset email path = reverse("account_reset_password_from_key", kwargs=dict(uidb36=user_pk_to_url_str(user), key=temp_key)) url = build_absolute_uri( request, path, protocol=app_settings.DEFAULT_HTTP_PROTOCOL) context = {"site": current_site, "user": user, "password_reset_url": url, "request": request} if app_settings.AUTHENTICATION_METHOD \ != AuthenticationMethod.EMAIL: context['username'] = user_username(user) get_adapter().send_mail('account/email/password_reset_key', email, context) return self.cleaned_data["email"]
def toggle_choice(request): campaign = get_active_campaign_or_404() volunteer = get_object_or_404(Volunteer, pk=request.POST.get('volunteer_id')) with transaction.atomic(): cursor = connection.cursor() cursor.execute('LOCK TABLE %s' % VolunteerCampaign._meta.db_table) created = False try: obj = VolunteerCampaign.objects.get( Q(accepted__isnull=True) | Q(accepted=True), campaign=campaign, volunteer=volunteer, ) except VolunteerCampaign.DoesNotExist: obj, created = VolunteerCampaign.objects.get_or_create( campaign=campaign, volunteer=volunteer, organisation=request.user.organisation, ) if created: serializer = URLSafeSerializer(settings.SECRET_KEY) confirm_invite_url = reverse('confirm_invite', args=[serializer.dumps(obj.pk)]) get_adapter().send_mail('emails/volunteer_invitation', volunteer.user.email, { 'organisation': request.user.organisation, 'confirm_invite_url': request.build_absolute_uri(confirm_invite_url), }) state, label = get_volunteer_status(obj, request.user.organisation) return JsonResponse({ 'state': state, 'label': label, })
def send_invitation(self, request, **kwargs): current_site = (kwargs['site'] if 'site' in kwargs else Site.objects.get_current()) invite_url = reverse('invitations:accept-invite', args=[self.key]) invite_url = ''.join(['https://', current_site.domain, invite_url]) # invite_url = request.build_absolute_uri(invite_url) ctx = { 'invite_url': invite_url, 'site_name': current_site.name, 'email': self.email, 'key': self.key, } if 'extra' in kwargs: ctx.update(kwargs['extra']) email_template = 'invitations/email/email_invite' get_adapter().send_mail( email_template, self.email, ctx) self.sent = timezone.now() self.save() signals.invite_url_sent.send( sender=self.__class__, instance=self, invite_url_sent=invite_url, inviter=request.user)
def post(self, *args, **kwargs): self.object = invitation = self.get_object() get_adapter().stash_verified_email(self.request, invitation.email) get_adapter().stash_invitation(self.request, invitation.id) return redirect(app_settings.SIGNUP_REDIRECT)
def confirm_invite(request, volunteer_campaign_id): serializer = URLSafeSerializer(settings.SECRET_KEY) try: volunteer_campaign_id = serializer.loads(volunteer_campaign_id) except BadSignature as e: raise Http404(str(e)) volunteer_campaign = get_object_or_404(VolunteerCampaign, pk=volunteer_campaign_id) if request.user.is_authenticated() and volunteer_campaign.volunteer != request.user.volunteer: raise Http404('Invitation was sent to other volunteer.') response = log_user_in(request, volunteer_campaign.volunteer.user) if response is not None: return response if request.method == 'POST': if request.POST.get('action') == 'accept': volunteer_campaign.accepted = True get_adapter().send_mail('emails/volunteer_accept', volunteer_campaign.organisation.user.email, { 'volunteer': volunteer_campaign.volunteer, }) else: volunteer_campaign.accepted = False volunteer_campaign.save() return redirect('volunteer_profile') return render(request, 'volunteers/confirm.html', { 'organisation': volunteer_campaign.organisation, })
def confirm(self, request): if not self.key_expired() and not self.email_address.verified: email_address = self.email_address get_adapter().confirm_email(request, email_address) signals.email_confirmed.send(sender=self.__class__, request=request, email_address=email_address) return email_address
def form_valid(self, form): email = form.cleaned_data["email"] users = form.users if users: context = { "instance": self.request.instance, "inviter": self.request.user, "invitee": users[0], } get_adapter().send_mail('instance_invite_existing', email, context) user_ids = [x.id for x in users] else: # Create a new user with email address as username # or a bit of a hash of the email address if it's longer # than Django's 30 character username limit. if len(email) > 30: username = hashlib.md5(email).hexdigest()[:10] else: username = email # Let's try creating a new user and sending an email to them # with a link to the password reset page. # FIXME - should probably try/catch the very unlikely situation # where we have a duplicate username, I guess. user = User.objects.create_user(username, email=email) user_ids = (user.id,) temp_key = default_token_generator.make_token(user) instance_url = self.request.instance.get_absolute_url() # send the password reset email path = reverse("instance_accept_invite", kwargs=dict(uidb36=int_to_base36(user.id), key=temp_key)) url = urlparse.urljoin(instance_url, path) context = { "instance": self.request.instance, "inviter": self.request.user, "invitee": user, "password_reset_url": url, } get_adapter().send_mail('accept_invite', email, context) self.request.instance.users.add(*user_ids) messages.add_message( self.request, messages.SUCCESS, 'Your invitation has been sent.', ) return super(ShareWithCollaborators, self).form_valid(form)
def form_valid(self, form): form.save() get_adapter().add_message(self.request, messages.SUCCESS, self.success_message_template) password_reset.send(sender=self.reset_user.__class__, request=self.request, user=self.reset_user) get_adapter().login(self.request, self.reset_user) return super(PasswordResetFromKeyView, self).form_valid(form)
def email_confirmed_receiver(email_address, **kwargs): """Email confirmed callback This method overrides the default behavior for handling the sign up of a new user. In this case, a welcome email will be sent waiting for the operator of the system to accept the request made by this user. :param email_address: email address that's been confirmed :param kwargs: additional parameters dictionary """ try: # User has to be activated by server's administrator, unless the user # is the administrator itself! user = auth_models.User.objects.get(email=email_address.email) if user.is_staff or user.is_superuser: user.is_active = True else: user.is_active = False user.save() # The confirmation of the email only verifies the account. u_profile = account_models.UserProfile.objects.get( email=email_address.email ) u_profile.is_verified = True u_profile.save() # Email sent to the administrator to report the new user for staff_email_i in auth_models.User.objects.filter( is_staff=True ).values_list('email', flat=True): logger.info( '(((((email_confirmed))))), notifying to staff = ' + str( staff_email_i ) ) allauth_adapter.get_adapter().send_mail( template_prefix=CONFIRMED_EMAIL_TEMPLATE, email=staff_email_i, context={ 'staff_email': staff_email_i, } ) except exceptions.ObjectDoesNotExist: logger.warning( 'Confirmed email = <' + str( email_address ) + '> does not exist in the database.' )
def form_valid(self, form): email_address = form.save(self.request) get_adapter().add_message(self.request, messages.INFO, 'account/messages/' 'email_confirmation_sent.txt', {'add_email': form.cleaned_data["add_email"]}) signals.email_added.send(sender=self.request.user.__class__, request=self.request, user=self.request.user, email_address=email_address) return super(EmailView, self).form_valid(form)
def get_or_create_by_email(self, email): try: created = False user = self.get_by_email(email).user except self.model.DoesNotExist: user, created = auth.get_user_model().objects.get_or_create( email=email) if created: allauth_adapter.get_adapter().populate_username(None, user) user.set_unusable_password() user.save() return user.gestalt
def form_valid(self, form): form.save() # Update session to keep user logged in. update_session_auth_hash(self.request, form.user) get_adapter().add_message(self.request, messages.SUCCESS, 'account/messages/password_changed.txt') signals.password_changed.send(sender=self.request.user.__class__, request=self.request, user=self.request.user) return super(PasswordChangeView, self).form_valid(form)
def post(self, request, format=None): fc = self.get_form_class() form = fc(data=request.data, user=request.user) if form.is_valid(): form.save() get_adapter().add_message(self.request, messages.SUCCESS, 'account/messages/password_changed.txt') signals.password_changed.send(sender=request.user.__class__, request=request, user=request.user) return Response(None, HTTP_204_NO_CONTENT) return Response(form.errors, HTTP_400_BAD_REQUEST)
def pre_social_login(self, request, sociallogin): """ Invoked just after a user successfully authenticates via a social provider, but before the login is actually processed. We use it to: 1. Check if the user is connecting accounts via signup page 2. store the name of the socialaccount provider in the user's session. TODO: When legacy Persona sessions are cleared (Nov 1 2016), this function can be simplified. """ session_login_data = request.session.get('socialaccount_sociallogin', None) request_login = sociallogin # Is there already a sociallogin_provider in the session? if session_login_data: session_login = SocialLogin.deserialize(session_login_data) # If the provider in the session is different from the provider in the # request, the user is connecting a new provider to an existing account if session_login.account.provider != request_login.account.provider: # Does the request sociallogin match an existing user? if not request_login.is_existing: # go straight back to signup page with an error message # BEFORE allauth over-writes the session sociallogin level = messages.ERROR message = "socialaccount/messages/account_not_found.txt" get_adapter().add_message(request, level, message) raise ImmediateHttpResponse( redirect('socialaccount_signup') ) # Is the user banned? if sociallogin.is_existing: bans = UserBan.objects.filter(user=sociallogin.user, is_active=True) if bans.exists(): banned_response = render(request, 'users/user_banned.html', { 'bans': bans, 'path': request.path }) add_never_cache_headers(banned_response) raise ImmediateHttpResponse(banned_response) # sociallogin_provider is used in the UI to indicate what method was # used to login to the website. The session variable # 'socialaccount_sociallogin' has the same data, but will be dropped at # the end of login. request.session['sociallogin_provider'] = (sociallogin .account.provider) request.session.modified = True
def post(self, *args, **kwargs): confirmation = self.get_object() if not confirmation: return Response({"detail": _("Email confirmation key could not be found")}, HTTP_400_BAD_REQUEST) if confirmation.email_address.verified: return Response(None, HTTP_304_NOT_MODIFIED) confirmation.confirm(self.request) get_adapter().add_message(self.request, messages.SUCCESS, 'account/messages/email_confirmed.txt', {'email': confirmation.email_address.email}) return_data = get_adapter().email_confirmation_response_data(confirmation) return Response(return_data, HTTP_200_OK)
def validate_email(self, email): email = get_adapter().clean_email(email) if allauth_settings.UNIQUE_EMAIL: if email and email_address_exists(email): raise serializers.ValidationError( _("A user is already registered with this e-mail address.")) return email
def validate_email(self, email): email = get_adapter().clean_email(email) if allauth_settings.UNIQUE_EMAIL: if email and email_address_exists(email): raise ValidationError( ("Un usuario ya ha sido registrado con este correo electrónico.")) return email
def process_view(self, request, view_func, view_args, view_kwargs): # The user is not logged in, do nothing. if request.user.is_anonymous: return # If this doesn't require 2FA, then stop processing. if not self.require_2fa(request): return # If the user is on one of the allowed pages, do nothing. for urlname in self.allowed_pages: try: if request.path == reverse(urlname): return except NoReverseMatch: # The developer may have misconfigured the list of allowed pages. # Let's not outright crash at that point, but inform the developer about their mishap. warnings.warn('NoReverseMatch for %s while checking for pages allowed without 2FA' % urlname) # User already has two-factor configured, do nothing. if get_adapter(request).has_2fa_enabled(request.user): return # The request required 2FA but it isn't configured! return self.on_require_2fa(request)
def clean_email(self): value = self.cleaned_data["email"] value = get_adapter().clean_email(value) if app_settings.UNIQUE_EMAIL: if value and email_address_exists(value): self.raise_duplicate_email_error() return value
def post(self, *args, **kwargs): self.object = invitation = self.get_object() invitation.accepted = True invitation.save() get_adapter().stash_verified_email(self.request, invitation.email) signals.invite_accepted.send(sender=self.request.user.__class__, request=self.request, email=invitation.email) get_adapter().add_message(self.request, messages.SUCCESS, 'invitations/messages/invite_accepted.txt', {'email': invitation.email}) return redirect(app_settings.SIGNUP_REDIRECT)
def fake_users(number=10): last_id = 0 last_user = User.objects.order_by('-pk').first() if last_user: last_id = last_user.id for i in range(last_id + 1, last_id + number): first_name = 'User{} FirstName'.format(i) last_name = 'User{} LastName'.format(i) email = 'user{}@example.com'.format(i) password = '******', unique_username = get_adapter().generate_unique_username([ first_name, last_name, email, ]) user_data = dict(first_name=first_name, last_name=last_name, username=unique_username, email=email, password=password, ) User.objects.create_user(**user_data) return "{} users created!".format(number)
def import_users(filename, password=None, customer=None): """takes a csv with First Name, Last Name, Email and creates users""" with open(filename, "rb") as ifile: reader = csv.reader(ifile) t = zip(reader) import_list = [x[0] for x in t] for i, row in enumerate(import_list): first_name = row[0].strip().title() last_name = row[1].strip().title() if not last_name: names = first_name.split(" ") if len(names) > 1: last_name = " ".join(names[1:]) first_name = names[0] unique_username = get_adapter().generate_unique_username([ first_name, last_name, row[2].strip(), ]) data = dict( first_name=first_name, last_name=last_name, email=row[2].strip(), username=unique_username ) result = User(**data) if password: result.set_password(password) result.save() if customer: result.userprofile.customer = customer result.userprofile.save()
def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() adapter.save_user(request, user, self) setup_user_email(request, user, []) user.first_name = self.cleaned_data.get('first_name') user.second_name = self.cleaned_data.get('second_name') user.email = self.cleaned_data.get('email') user.user_type = self.cleaned_data.get('user_type') user.phone_number = self.cleaned_data.get('phone_number') user.wants_to_receive_marketing_emails = self.cleaned_data.get( 'wants_to_receive_marketing_emails') user.save() return user
def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() adapter.save_user(request, user, self) #Assign gender and birthdate to the new user userProfile = UserProfile(user=user, gender=self.validated_data.get('gender', ''), birthdate=self.validated_data.get( 'birthdate', '')) userProfile.save() self.custom_signup(request, user) setup_user_email(request, user, []) return user
def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() user.gender = self.cleaned_data['gender'] user.phone_number = self.cleaned_data['phone_number'] user.date_of_birth = self.cleaned_data['date_of_birth'] user.profile_img = self.cleaned_data['profile_img'] adapter.save_user(request, user, self) self.custom_signup(request, user) setup_user_email(request, user, []) return user
def save(self, request): """ Override save method to save custom fields: address, phone_number, date_of_birth """ adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() adapter.save_user(request, user, self) setup_user_email(request, user, []) user.address = self.cleaned_data.get('address') user.date_of_birth = self.cleaned_data.get('date_of_birth') user.phone_number = self.cleaned_data.get('phone_number') user.save() return user
def form_valid(self, form): logout(self.request) self.object = confirmation = self.get_object() confirmation.confirm(self.request) get_adapter().add_message(self.request, messages.SUCCESS, 'account/messages/email_confirmed.txt', {'email': confirmation.email_address.email}) form.save() # get the confirmation object again so it reloads the user model that has the new password self.object = confirmation = self.get_object() resp = self.login_on_confirm(confirmation) if resp: return resp # Don't -- allauth doesn't touch is_active so that sys admin can # use it to block users et al # # user = confirmation.email_address.user # user.is_active = True # user.save() redirect_url = self.success_url if not redirect_url: ctx = self.get_context_data() return self.render_to_response(ctx) return redirect(redirect_url)
def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() adapter.save_user(request, user, self) setup_user_email(request, user, []) ## User extra data assignation user.profile_photo = request.data['profile_photo'] if \ 'profile_photo' in request.data.keys() else None user.country = self.cleaned_data['country'] user.save() return user
def clean(self): super(SignupForm, self).clean() # `password` cannot be of type `SetPasswordField`, as we don't # have a `User` yet. So, let's populate a dummy user to be used # for password validaton. dummy_user = get_user_model() user_email(dummy_user, self.cleaned_data.get("email")) password = self.cleaned_data.get('password1') if password: try: get_adapter().clean_password(password, user=dummy_user) except forms.ValidationError as e: self.add_error('password1', e) if "password1" in self.cleaned_data \ and "password2" in self.cleaned_data: if self.cleaned_data["password1"] \ != self.cleaned_data["password2"]: self.add_error( 'password2', _("The password and confirm password fields do not match.") ) return self.cleaned_data
def get(self, request, *args, **kwargs): invitation = self.get_object() # save the invitation key in the session request.session[INVITATION_SESSION_KEY] = invitation.secret_key # verify the email adapter = get_adapter(request) adapter.stash_verified_email(request, invitation.email) # add a message for the user messages.info( request, _('You have been invited to join %(organisation)s on Toucan. Please continue with the signup process.' % {'organisation': invitation.organisation.name})) # and redirect to return HttpResponseRedirect(reverse('account_signup'))
def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() user = adapter.save_user(request, user, self, commit=False) try: adapter.clean_password(self.cleaned_data['password1'], user=user) except DjangoValidationError as exc: raise serializers.ValidationError( detail=serializers.as_serializer_error(exc) ) user.save() self.custom_signup(request, user) setup_user_email(request, user, []) return user
def save(self, request): print(self.get_cleaned_data()) adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() adapter.save_user(request, user, self) setup_user_email(request, user, []) first_name = request.data.get('first_name') last_name = request.data.get('last_name') user.first_name = first_name user.last_name = last_name user.save() profile = user.profile profile.save() return user
def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() # commit=False does not save the user to the DB yet adapter.save_user(request, user, self, commit=False) # the custom_signup method contains the openwisp specific logic self.custom_signup(request, user) # create a RegisteredUser object for every user that registers through API RegisteredUser.objects.create( user=user, method=self.validated_data['method'], ) setup_user_email(request, user, []) return user
def clean(self): super(SignupForm, self).clean() # `password` cannot by of type `SetPasswordField`, as we don't # have a `User` yet. So, let's populate a dummy user to be used # for password validaton. dummy_user = get_user_model() user_username(dummy_user, self.cleaned_data.get("username")) user_email(dummy_user, self.cleaned_data.get("email")) password = self.cleaned_data.get('password1') if password: try: get_adapter().clean_password(password, user=dummy_user) except forms.ValidationError as e: self.add_error('password1', e) if app_settings.SIGNUP_PASSWORD_ENTER_TWICE \ and "password1" in self.cleaned_data \ and "password2" in self.cleaned_data: if self.cleaned_data["password1"] \ != self.cleaned_data["password2"]: self.add_error('password2', _("You must type the same password each time.")) return self.cleaned_data
def send_confirmation_mail(self, request, emailconfirmation, signup): current_site = get_current_site(request) activate_url = self.get_email_confirmation_url(request, emailconfirmation) badgr_app = get_session_badgr_app(request) if not badgr_app: badgr_app = BadgrApp.objects.get_current(request, raise_exception=False) ctx = { "user": emailconfirmation.email_address.user, "email": emailconfirmation.email_address, "activate_url": activate_url, "current_site": current_site, "key": emailconfirmation.key, "badgr_app": badgr_app } if signup == 'canvas': email_template = 'account/email/email_confirmation_canvas' elif signup: email_template = 'account/email/email_confirmation_signup' else: email_template = 'account/email/email_confirmation' get_adapter().send_mail(email_template, emailconfirmation.email_address.email, ctx)
def form_valid(self, form): if 'info' in self.request.POST: logger.debug("form: info success") dmm.notifications.success(self.request, "Info successfully updated") email = self.request.user.emailaddress_set.get(primary=True) if form.cleaned_data["email"] != email.email: email.change(self.request, form.cleaned_data["email"]) get_adapter(self.request).add_message( self.request, messages.INFO, 'account/messages/' 'email_confirmation_sent.txt', {'email': email}) return super().form_valid(form) elif 'password' in self.request.POST: logger.debug("form: password success") form.save() logout_on_password_change(self.request, form.user) get_adapter(self.request).add_message( self.request, messages.SUCCESS, 'account/messages/password_set.txt') allauth.account.signals.password_set.send( sender=self.request.user.__class__, request=self.request, user=self.request.user) return HttpResponseRedirect(self.get_success_url())
def validate_email(self, email): email = get_adapter().clean_email(email) ''' get role, raise exception if email exists and pertains to an owner ''' if allauth_settings.UNIQUE_EMAIL: if email and email_address_exists(email): #get the role of existing email address user = User.objects.get(email=email) role = user.userprofile.basic_role if role == 'owner': raise serializers.ValidationError( _("An owner is already registered with this e-mail address." )) return email
def save(self, commit=True): """ Saves the email and name properties after the normal save behavior is complete. Sets a random password, which the user must change upon initial login. Saves the location and group after the user object is saved. """ user = super(UserCreationForm, self).save(commit) if user: user.email = self.cleaned_data["email"] user.name = self.cleaned_data["name"] password = get_random_string(length=32) user.set_password(password) locations = self.cleaned_data["locations"] group = self.cleaned_data["group"] if commit: user.save() # You cannot associate the user with a m2m field until it’s been saved # https://docs.djangoproject.com/en/3.1/topics/db/examples/many_to_many/ user.locations.add(*locations) user.groups.add(*[group]) # TODO: Remove if we do not require email confirmation; we will no longer need the lines below # See allauth: # https://github.com/pennersr/django-allauth/blob/c19a212c6ee786af1bb8bc1b07eb2aa8e2bf531b/allauth/account/utils.py # setup_user_email(self.request, user, []) get_adapter().send_new_user_mail(self.request, user, password) return user
def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() user.address = self.cleaned_data.get('address') user.account = self.cleaned_data.get('account') user.name = self.cleaned_data.get('name') if user.account == 'broker': user.is_verified = False user.save() adapter.save_user(request, user, self) return user
def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() user.username = self.cleaned_data.get('username') user.mobile = self.cleaned_data.get('mobile') user.is_student = self.cleaned_data.get('is_student') user.is_teacher = self.cleaned_data.get('is_teacher') # print('XXXXXXXXXXXXXXXXXXXX username', user.username) # print('XXXXXXXXXXXXXXXXXXXX mobile', user.mobile) # print('XXXXXXXXXXXXXXXXXXXX mobile', user.is_student) user.save() adapter.save_user(request, user, self) return user
def send_invitation(self, request, **kwargs): current_site = (kwargs['site'] if 'site' in kwargs else Site.objects.get_current()) invite_url = reverse('invitations:accept-invite', args=[self.key]) invite_url = request.build_absolute_uri(invite_url) ctx = { 'invite_url': invite_url, 'site_name': current_site.name, 'email': self.email, 'key': self.key, 'inviter': self.inviter, } email_template = 'invitations/email/email_invite' get_adapter().send_mail(email_template, self.email, ctx) self.sent = timezone.now() self.save() signals.invite_url_sent.send(sender=self.__class__, instance=self, invite_url_sent=invite_url, inviter=request.user)
def save(self, request): try: group = Group.objects.get(id=request.data['group_id']) except ObjectDoesNotExist: raise NotFound(detail='Group_id not found') adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() adapter.save_user(request, user, self) setup_user_email(request, user, []) user.groups.add(group) user.save() return user
def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() adapter.save_user(request, user, self) setup_user_email(request, user, []) profile_data = self.get_profile_data() # Added custom information on registration (Profile, Services and Work_zones) ProfileOperator.create_profile(user, profile_data) # Create Profile if self.initial_data.get('type') == PROFESSIONAL: ServicesOperator.create_services( user, self.initial_data.get('services')) # Create UserServices WorZonesOperator.create_work_zones( user, self.initial_data.get('work_zones')) # Create UserWorZones return user
def save(self, request): adapter = get_adapter() user = adapter.new_user(request) #user.id_number = self.validated_data.get('id_number') user.save() self.cleaned_data = self.get_cleaned_data() adapter.save_user(request, user, self) vd = self.validated_data condominio = Condo(user=user, terms_accepted=vd.get('terms'), name=vd.get('name'), id_proof=vd.get('id_proof')) condominio.save() self.custom_signup(request, user) setup_user_email(request, user, []) return user
def save(self, request): ''' we attempt to get the user, if an exception is thrown we create the broker ''' try: cleaned_data = self.get_cleaned_data() return User.objects.get(email=cleaned_data.get('email'), username=cleaned_data.get('username')) except: adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() adapter.save_user(request, user, self) user = self.custom_signup(request, user) setup_user_email(request, user, []) return user
def invite_artist(self, request): adapter = get_adapter() try: user = User.objects.get(email=self.cleaned_data.get('email')) user.artist = self.artist user.save() except ObjectDoesNotExist: user = adapter.new_user(request) user = adapter.save_user(request, user, self) user.artist = self.artist user.save() self.custom_signup(request, user) # TODO: Move into adapter `save_user` ? setup_user_email(request, user, []) send_email_confirmation(request, user, signup=True, activate_view='artist_registration_confirm_email') return user
def validate_username(self, username): """Check for unique email address or phone number.""" pattern = re.compile("^\d{10,13}") match = pattern.match(username) if match: username = self.validate_phone(username) # TODO: validate phone return username else: email = get_adapter().clean_email(username) if app_settings.UNIQUE_EMAIL: if email and email_address_exists(email): raise serializers.ValidationError( "A user is already registered with this e-mail address." ) return email
def create(self, request, *args, **kwargs): # Check if registration is open if get_adapter(self.request).is_open_for_signup(self.request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(self.get_response_data(user), status=status.HTTP_201_CREATED, headers=headers) else: return Response( data={'message': 'Registration is not open.'}, status=status.HTTP_403_FORBIDDEN, )
def update(self, instance, validated_data): request = self.context.get('request') profile = validated_data.get('profile', None) instance.username = validated_data.get('username', instance.username) instance.first_name = validated_data.get('first_name', instance.first_name) if profile: bio = profile.get("bio") location = profile.get("location") birth_date = profile.get("birth_date") first_name = profile.get("first_name") last_name = profile.get("last_name") if bio and bio != instance.profile.bio: instance.profile.bio = bio if location and location != instance.profile.location: instance.profile.location = location if birth_date and birth_date != instance.profile.birth_date: instance.profile.birth_date = birth_date if first_name and first_name != instance.profile.first_name: instance.profile.first_name = first_name if last_name and last_name != instance.profile.last_name: instance.profile.last_name = last_name email = validated_data.get('email', None) if email and email != instance.email: adapter = get_adapter() adapter.send_mail('account/email/email_change', instance.email, {}) email_address = EmailAddress.objects.get(user=instance, verified=True) email_address.change(request, email, True) instance.email = email if 'avatar' in request.FILES: avatar = Avatar(user=instance, primary=True) image_file = request.FILES['avatar'] avatar.avatar.save(image_file.name, image_file) avatar.save() avatar_updated.send(sender=Avatar, user=instance, avatar=avatar) instance.save() # sync_sso(instance) return instance
def login_on_confirm(self, confirmation): """Login on confrim.""" user_pk = None user_pk_str = get_adapter(self.request).unstash_user(self.request) if user_pk_str: user_pk = url_str_to_user_pk(user_pk_str) user = confirmation.email_address.user if user_pk == user.pk and self.request.user.is_anonymous(): return perform_login( self.request, user, app_settings.EmailVerificationMethod.NONE, # passed as callable, as this method # depends on the authenticated state redirect_url=self.get_redirect_url) return None
def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() if (request.data['is_student'] == True) : user.is_student = True else: user.is_teacher = True user.save() adapter.save_user(request, user, self) if (request.data['is_student'] == True) : create_student = Student(user= user) create_student.save() else: create_teacher = Teacher(user= user) create_teacher.save() return user
def custom_signup(self, request, user): # send a notification email; not doing this as part of the adapter # b/c sometimes registration forms/serializers have additional checks # to make before _actually_ saving the user - this fn runs after those if app_settings.ASTROSAT_USERS_NOTIFY_SIGNUPS: adapter = get_adapter(request) subject = adapter.format_email_subject(f"new user signup: {user}") message = f"User {user.email} signed up for an account." mail_managers(subject, message, fail_silently=True) customer_name = self.validated_data.get("customer_name") if customer_name: # create a customer and customer-user as part of the signup process # (this bypasses creating them via separate DRF Views) (customer, _) = Customer.objects.get_or_create(name=customer_name) customer.add_user(user, type="MANAGER", status="PENDING") return super().custom_signup(request, user)