def post(self, request): serializer = self.get_serializer(data=request.data) try: serializer.is_valid(raise_exception=True) return self._action(serializer) except ValidationError: error = serializer.errors except exceptions.AccountInactiveError as e: user = serializer.user user.is_active = False user.save() error = e.msg except exceptions.EmailNotVerifiedError as e: user = serializer.user error = e.msg send_email_confirmation(self.request._request, user) except exceptions.PhoneNotVerifiedError as e: user = serializer.user error = e.msg device = user.verificationdevice_set.get(label='phone_verify') device.generate_challenge() return Response(data={'detail': error}, status=status.HTTP_401_UNAUTHORIZED)
def pre_social_login_(sender, request, sociallogin, **kwargs): ''' Resolve issue of existing email address. When signing up a social account with the existing email address it will logged the existing user. And for security hole issue the account will not successfully logged if their given email address are not verified. To verify ownership of email this function will automatically send a verification link to the given email and only legit user can access the said account. :param sender: :param request: :param sociallogin: :param kwargs: :return: ''' email = sociallogin.account.extra_data['email'] _user = get_user_model() users = _user.objects.filter(email=email) _s_emails = s_emails.objects.filter(email=email) e_existing = _s_emails.exists() u_existing = users.exists() if u_existing : if e_existing: if _s_emails[0].verified: perform_login(request, users[0], app_settings.EMAIL_VERIFICATION) raise ImmediateHttpResponse(redirect(settings.LOGIN_REDIRECT_URL)) send_email_confirmation(request, users[0]) raise ImmediateHttpResponse(render(request, 'account/verification_sent.html', {}))
def validate(self, attrs): username = attrs.get('username') password = attrs.get('password') user = None if 'allauth' in settings.INSTALLED_APPS: user = self._validate_username_email(username, password) else: # Authentication without using allauth if username: user = self._validate_username_email(username, password) # Did we get back an active user? if user: if not user.is_active: msg = _('User account is disabled.') raise exceptions.ValidationError(msg) else: msg = _('Unable to log in with provided credentials.') raise exceptions.ValidationError(msg) # If required, is the email verified? if 'rest_auth.registration' in settings.INSTALLED_APPS: from allauth.account import app_settings if app_settings.EMAIL_VERIFICATION == app_settings.EmailVerificationMethod.MANDATORY: email_address = user.emailaddress_set.get(email=user.email) if not email_address.verified: send_email_confirmation(self.context.get("request"), user) raise ValidationError( _('E-mail is not verified. Verification Mail has been resent to your E-mail!' )) attrs['user'] = user return attrs
def perform_update(self, serializer): instance = self.get_object() current_email, current_phone = instance.email, instance.phone new_email = serializer.validated_data.get('email', instance.email) new_phone = serializer.validated_data.get('phone', instance.phone) user = serializer.save() if current_email != new_email: instance.emailaddress_set.all().delete() if new_email: send_email_confirmation(self.request._request, user) if current_email: user.email = current_email utils.send_email_update_notification(current_email) if current_phone != new_phone: instance.verificationdevice_set.all().delete() if new_phone: device = VerificationDevice.objects.create( user=instance, unverified_phone=new_phone) device.generate_challenge() if current_phone: user.phone = current_phone utils.send_sms(current_phone, messages.phone_change) user.save()
def test_signup_with_released_email(self): user = UserFactory.create(username='******', email='*****@*****.**', email_verified=True) EmailAddress.objects.create(user=user, email=user.email, verified=True) data = { 'username': '******', 'email': '*****@*****.**', } request = HttpRequest() setattr(request, 'session', 'session') self.messages = FallbackStorage(request) setattr(request, '_messages', self.messages) request.META['SERVER_NAME'] = 'testserver' request.META['SERVER_PORT'] = '80' form = forms.ProfileForm(data, request=request, instance=user) form.save() user = UserFactory.create(username='******', email='*****@*****.**') try: send_email_confirmation(request, user) except IntegrityError: assert False else: assert True
def profile(request): if request.method == 'POST': form = CustomUserChangeForm(request.POST, instance=request.user) if form.is_valid(): user = form.save(commit=False) user_before_update = CustomUser.objects.get(pk=user.pk) need_to_confirm_email = ( user_before_update.email != user.email and require_email_confirmation() and not user_has_confirmed_email_address(user, user.email)) if need_to_confirm_email: # don't change it but instead send a confirmation email # email will be changed by signal when confirmed new_email = user.email send_email_confirmation(request, user, signup=False, email=new_email) user.email = user_before_update.email # recreate the form to avoid populating the previous email in the returned page form = CustomUserChangeForm(instance=user) user.save() else: form = CustomUserChangeForm(instance=request.user) return render(request, 'account/profile.html', { 'form': form, 'active_tab': 'profile' })
def form_valid(self, form): """Create and log in the user signing up Took this from allauth because extensibility is for chumps. """ self.object = form.save(request=self.request) signals.user_signed_up.send(sender=self.object.__class__, request=self.request, user=self.object) # not is_active: social users are redirected to a template # local users are stopped due to form validation checking is_active assert self.object.is_active if (settings.ACCOUNT_EMAIL_VERIFICATION and not EmailAddress.objects.filter(user=self.object, verified=True).exists()): send_email_confirmation(self.object, self.request) # HACK: This may not be nice. The proper Django way is to use an # authentication backend, but I fail to see any added benefit # whereas I do see the downsides (having to bother the integrator # to set up authentication backends in settings.py if not hasattr(self.object, 'backend'): self.object.backend = "django.contrib.auth.backends.ModelBackend" signals.user_logged_in.send(sender=self.object.__class__, request=self.request, user=self.object) login(self.request, self.object) msg = _('Successfully signed in as {0}.'.format(user_display(self.object))) messages.success(self.request, msg) return HttpResponseRedirect(self.get_success_url())
def save(self): request = self.context.get('request') User = get_user_model() email = self.reset_form.cleaned_data["email"] user = User.objects.get(email__iexact=email) send_email_confirmation(request, user, True) return email
def _process_signup(request, sociallogin): # If email is specified, check for duplicate and if so, no auto signup. auto_signup = app_settings.AUTO_SIGNUP email = sociallogin.account.user.email if auto_signup: # Let's check if auto_signup is really possible... if email: if account_settings.UNIQUE_EMAIL: try: user = User.objects.get(email__iexact=email) # Oops, another user already has this address. We # cannot simply connect this social account to the # existing user. Reason is that the email adress may # not be verified, meaning, the user may be a hacker # that has added your email address to his account in # the hope that you fall in his trap. To solve this, # we reset the password of the email account and connect # the user. user.set_password(md5.new('%s:%s ' % (email, time.time())).hexdigest()) user.save() context = create_password_reset_context(user) get_account_adapter().send_mail('account/email/link_facebook', email, context) sociallogin.account.user = user sociallogin.save() return perform_login(request, user, redirect_url=sociallogin.get_redirect_url(request)) except User.DoesNotExist: # No user exists with this email. Let's auto sign up the user. auto_signup = True elif account_settings.EMAIL_REQUIRED: # Nope, email is required and we don't have it yet... auto_signup = False if not auto_signup: request.session['socialaccount_sociallogin'] = sociallogin url = reverse('socialaccount_signup') ret = HttpResponseRedirect(url) else: # FIXME: This part contains a lot of duplication of logic # ("closed" rendering, create user, send email, in active # etc..) try: if not get_account_adapter().is_open_for_signup(request): return render(request, "account/signup_closed.html") except ImmediateHttpResponse, e: return e.response u = sociallogin.account.user u.username = generate_unique_username(u.username or email or 'user') u.last_name = (u.last_name or '') \ [0:User._meta.get_field('last_name').max_length] u.first_name = (u.first_name or '') \ [0:User._meta.get_field('first_name').max_length] u.email = email or '' u.set_unusable_password() sociallogin.save() send_email_confirmation(request, u) ret = complete_social_signup(request, sociallogin)
def dispatch(self, request, *args, **kwargs): if not EmailAddress.objects.filter(user=request.user, verified=True).exists(): send_email_confirmation(request, request.user) return render(request, 'account/verified_email_required.html') return super().dispatch(request, *args, **kwargs)
def resend_user_activation( request, template_file="administration/resend_activation/index.html"): context = RequestContext(request) if request.method == "POST": form = EmailForm(request.POST) if form.is_valid(): try: user = User.objects.get( email__iexact=form.cleaned_data.get('email')) if not user.is_active: try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() except Profile.MultipleObjectsReturned: profiles = Profile.objects.filter(user=user) profile = profiles[0] if not profile.skeleton_user: send_email_confirmation(request, user) context[ 'message'] = "Activation email has been resent to %s" % user.email else: context[ 'message'] = "This user hasn't signed up for ratetracker" else: context[ 'message'] = "This user has already activated, they should probably use the password reset bit on the login page!" except User.DoesNotExist: context['message'] = "User doesn't exist!" else: context['form'] = EmailForm() return render_to_response(template_file, context_instance=context)
def q_send_email_confirmation(request): valid_request, msg = validate_request(request) if not valid_request: return HttpResponseForbidden(msg) username = request.POST.get("username") try: user = User.objects.get(username=username) except User.DoesNotExist: msg = "Unable to locate user '{0}'.".format(username) messages.add_message(request, messages.ERROR, msg) return HttpResponseBadRequest(msg) current_user = request.user if not current_user.is_superuser and current_user.username != username: msg = "You do not have authority to validate this user's email." messages.add_message(request, messages.ERROR, msg) return HttpResponseBadRequest(msg) try: send_email_confirmation(request, user) except Exception as e: msg = "Error sending confirmation email." messages.add_message(request, messages.ERROR, msg) return HttpResponseBadRequest(msg) return JsonResponse({})
def get_email_address(self, request, user): try: return EmailAddress.objects.get(email=user.email) except ObjectDoesNotExist: setup_user_email(request, user, []) send_email_confirmation(request, user) return EmailAddress.objects.get(email=user.email)
def post(self, request): user = get_object_or_404(User, email=request.data['email']) emailAddress = EmailAddress.objects.filter(user=user, verified=True).exists() if emailAddress: return Response({'message': 'Это Email уже проверен'}, status=status.HTTP_400_BAD_REQUEST) else: try: send_email_confirmation(request, user=user) return Response( { 'message': 'Отправлено подтверждение по электронной почте' }, status=status.HTTP_201_CREATED) except APIException: return Response( { 'message': 'Этот адрес электронной почты не существует, \ пожалуйста, создайте новую учетную запись' }, status=status.HTTP_403_FORBIDDEN)
def perform_create(self, serializer): user = serializer.save() signals.user_registered.send(sender=self.__class__, user=user, request=self.request) send_email_confirmation(self.request._request, user)
def resend_email_confirmation(request): """ Resends the confirmation email on user request. """ user = request.user send_email_confirmation(request._request, user) return Response(status=status.HTTP_200_OK)
def assign_user_to_group(modeladmin, queryset, group_name, request): """ Approves users :param queryset: List of the users to be approved :param group: Group to be assigned :param request: :return: """ group = Group.objects.get(name=group_name) if group: for user_profile in queryset: user_profile.status = UserProfile.APPROVED_STATE user_profile.save() # sending the confirmation email send_email_confirmation(request, user_profile.user, signup=True) # setting the group group.user_set.add(user_profile.user) modeladmin.message_user( request, 'El usuario %s fue agregado al grupo %s con éxito.' % (user_profile.user.first_name,group.name) ) else: self.message_user( request,'El grupo %s no existe.' % group_name, level=messages.ERROR )
def send_email_verification(request, user, email_verification): has_verified_email = EmailAddress.objects.filter(user=user, verified=True).exists() if not has_verified_email: send_email_confirmation(request, user, signup=True)
def resend_user_activation(request, template_file="administration/resend_activation/index.html"): context = RequestContext(request) if request.method == "POST": form = EmailForm(request.POST) if form.is_valid(): try: user = User.objects.get(email__iexact=form.cleaned_data.get('email')) if not user.is_active: try: profile = user.profile except Profile.DoesNotExist: profile = Profile(user=user) profile.save() except Profile.MultipleObjectsReturned: profiles = Profile.objects.filter(user=user) profile = profiles[0] if not profile.skeleton_user: send_email_confirmation(request, user) context['message'] = "Activation email has been resent to %s" % user.email else: context['message'] = "This user hasn't signed up for ratetracker" else: context[ 'message'] = "This user has already activated, they should probably use the password reset bit on the login page!" except User.DoesNotExist: context['message'] = "User doesn't exist!" else: context['form'] = EmailForm() return render_to_response(template_file, context_instance=context)
def create(self, validated_data): with transaction.atomic(): first_name = validated_data.get("first_name", "") last_name = validated_data.get("last_name", "") account_type = validated_data.get("account_type", "") user = FcUser.objects.create(username=validated_data.get("email"), email=validated_data.get("email"), phone_number=validated_data.get( "phone_number", ""), first_name=first_name, last_name=last_name, account_type=account_type) user.set_password(validated_data.get("password")) user.raw_password = validated_data.get("password") user.save() if account_type == 'customer': customer_info = FcCustomer.objects.create(user=user) customer_info.save() else: provider_info = FcProvider.objects.create(user=user) provider_info.save() request = self.context.get("request") print('before sending mail') send_email_confirmation(request, user, True) print('after sending mail') return user
def home(request): try: qs = Event.objects.untranslated().use_fallbacks() try: today = datetime.now() event = qs.filter(start__gte=now).first() except: event = qs.order_by('start').last() except: event = None if request.method == 'POST': form = EmailOnlyForm(request.POST) if form.is_valid(): user = form.save(request) send_email_confirmation(request, user) return redirect('thanks') form = EmailOnlyForm() if event: dt_now = timezone.now() if dt_now > event.start and dt_now < event.end: return redirect('map', event_codename=event.codename) return render(request, 'home.html', { 'event': event, 'form': form, 'current_page': 'home', })
def form_valid(self, form): phone = form.data.get('phone') email = form.data.get('email') if phone: try: with transaction.atomic(): phone_device = VerificationDevice.objects.get( unverified_phone=phone, verified=False) phone_device.generate_challenge() self.request.session[ 'phone_verify_id'] = phone_device.user_id except TwilioRestException as e: if e.status >= 500: msg = TWILIO_ERRORS.get('default') else: msg = TWILIO_ERRORS.get(e.code) if msg: form.add_error('phone', msg) return self.form_invalid(form) else: raise except VerificationDevice.DoesNotExist: pass message = _( "Your phone number has been submitted." " If it matches your account on Cadasta Platform, you will" " receive a verification token to confirm your phone.") messages.add_message(self.request, messages.SUCCESS, message) if email: email = email.casefold() try: email_device = EmailAddress.objects.get(email=email, verified=False) user = email_device.user if not user.email_verified: user.email = email send_email_confirmation(self.request, user) self.request.session['phone_verify_id'] = email_device.user.id except EmailAddress.DoesNotExist: pass # This is a gross hack, removing all messages previously added to # the message queue so we don't reveal whether the email address # existed in the system or not. (See issue #1869) get_messages(self.request)._queued_messages = [] message = _( "Your email address has been submitted." " If it matches your account on Cadasta Platform, you will" " receive a verification link to confirm your email.") messages.add_message(self.request, messages.SUCCESS, message) return super().form_valid(form)
def form_valid(self, form): user = form.user if not user.email_verified and timezone.now() > user.verify_email_by: user.is_active = False user.save() send_email_confirmation(self.request, user) return super().form_valid(form)
def save(self, request): new_user = self.create_user() self.sociallogin.account.user = new_user self.sociallogin.save(request) super(SignupForm, self).save(new_user) # Confirmation last (save may alter first_name etc -- used in mail) send_email_confirmation(request, new_user) return new_user
def create(self, request): if request.user.email_verified: raise ValidationError( {"email": ["Email Already Verified"]}) send_email_confirmation(request, request.user) # , status=status.HTTP_201_CREATED) return Response({'detail': 'Email Confirmation Sent Succesfully'})
def post(self, request): if request.user.email_verified: return Response({'message': 'Email already verified'}, status=status.HTTP_201_CREATED) send_email_confirmation(request, request.user) return Response({'message': 'Email confirmation sent'}, status=status.HTTP_201_CREATED)
def save(self, request=None): new_user = self.create_user() self.sociallogin.account.user = new_user self.sociallogin.save() super(SignupForm, self).save(new_user) # Confirmation last (save may alter first_name etc -- used in mail) send_email_confirmation(request, new_user) return new_user
def post(self, request, format=None): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): new_user = serializer.save() send_email_confirmation(request._request, new_user) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def handle(self, *args, **options): users = User.objects.filter( emailaddress__verified=False, emailaddress__email__contains=options['email_contains']) request = RequestFactory().get('/') request.environ['SERVER_NAME'] = settings.ALLOWED_HOSTS[0] for user in users: print "Resending to", user send_email_confirmation(request, user)
def post_resident_save(sender, instance, created,**kwargs): if created: ''' in special cases the instance will be passed with a request attribute Eg;instance.resident by the serializer. Should be accounte for in the tests ''' assign_role(instance.user, 'resident')#assigns role as resident if hasattr(instance, 'request'): send_email_confirmation(instance.request, instance.user, signup=True)
def post(self, request): obj = EmailAddress.objects.get(email=request.user.email) if obj.verified: return Response({'message': 'Email already verified'}, status=status.HTTP_201_CREATED) send_email_confirmation(request, request.user) return Response({'message': 'Email confirmation sent'}, status=status.HTTP_201_CREATED)
def perform_create(self, serializer): user = serializer.save() signals.user_registered.send(sender=self.__class__, user=user, request=self.request) try: send_email_confirmation(self.request._request, user) except MessageFailure: pass
def _process_signup(request, sociallogin): # If email is specified, check for duplicate and if so, no auto signup. auto_signup = app_settings.AUTO_SIGNUP email = user_email(sociallogin.account.user) if auto_signup: # Let's check if auto_signup is really possible... if email: if account_settings.UNIQUE_EMAIL: if email_address_exists(email): # Oops, another user already has this address. We # cannot simply connect this social account to the # existing user. Reason is that the email adress may # not be verified, meaning, the user may be a hacker # that has added your email address to his account in # the hope that you fall in his trap. We cannot check # on 'email_address.verified' either, because # 'email_address' is not guaranteed to be verified. auto_signup = False # FIXME: We redirect to signup form -- user will # see email address conflict only after posting # whereas we detected it here already. elif app_settings.EMAIL_REQUIRED: # Nope, email is required and we don't have it yet... auto_signup = False if not auto_signup: request.session['socialaccount_sociallogin'] = sociallogin url = reverse('socialaccount_signup') ret = HttpResponseRedirect(url) else: # FIXME: This part contains a lot of duplication of logic # ("closed" rendering, create user, send email, in active # etc..) try: if not get_account_adapter().is_open_for_signup(request): return render(request, "account/signup_closed.html") except ImmediateHttpResponse as e: return e.response u = sociallogin.account.user if account_settings.USER_MODEL_USERNAME_FIELD: user_username(u, generate_unique_username(user_username(u) or email or 'user')) for field in ['last_name', 'first_name']: if hasattr(u, field): truncated_value = (user_field(u, field) or '') \ [0:User._meta.get_field(field).max_length] user_field(u, field, truncated_value) user_email(u, email or '') u.set_unusable_password() sociallogin.save(request) send_email_confirmation(request, u) ret = complete_social_signup(request, sociallogin) return ret
def validate(self, attrs): username = attrs.get('username') email = attrs.get('email') password = attrs.get('password') user = None if 'allauth' in settings.INSTALLED_APPS: from allauth.account import app_settings # Authentication through email if app_settings.AUTHENTICATION_METHOD == app_settings.AuthenticationMethod.EMAIL: user = self._validate_email(email, password) # Authentication through username if app_settings.AUTHENTICATION_METHOD == app_settings.AuthenticationMethod.USERNAME: user = self._validate_username(username, password) # Authentication through either username or email else: user = self._validate_username_email(username, email, password) else: # Authentication without using allauth if email: try: username = UserModel.objects.get( email__iexact=email).get_username() except UserModel.DoesNotExist: pass if username: user = self._validate_username_email(username, '', password) # Did we get back an active user? if user: if not user.is_active: msg = _('User account is disabled.') raise exceptions.ValidationError(msg) else: msg = _('Unable to log in with provided credentials.') raise exceptions.ValidationError(msg) # If required, is the email verified? if 'rest_auth.registration' in settings.INSTALLED_APPS: from allauth.account import app_settings if app_settings.EMAIL_VERIFICATION == app_settings.EmailVerificationMethod.MANDATORY: email_address = user.emailaddress_set.get(email=user.email) if not email_address.verified: # added resending confirmation email send_email_confirmation(self.context['request'], user) raise serializers.ValidationError( _('E-mail is not verified.')) attrs['user'] = user return attrs
def _process_signup(request, sociallogin): log.debug('socialaccount.helpers._process_signup') # If email is specified, check for duplicate and if so, no auto signup. log.debug("_process_signup") auto_signup = app_settings.AUTO_SIGNUP email = sociallogin.account.user.email if auto_signup: # Let's check if auto_signup is really possible... log.debug("auto_signup") if email: if account_settings.UNIQUE_EMAIL: if email_address_exists(email): # Oops, another user already has this address. We # cannot simply connect this social account to the # existing user. Reason is that the email adress may # not be verified, meaning, the user may be a hacker # that has added your email address to his account in # the hope that you fall in his trap. We cannot check # on 'email_address.verified' either, because # 'email_address' is not guaranteed to be verified. auto_signup = False # FIXME: We redirect to signup form -- user will # see email address conflict only after posting # whereas we detected it here already. elif account_settings.EMAIL_REQUIRED: # Nope, email is required and we don't have it yet... log.debug("no email available") auto_signup = False if not auto_signup: log.debug("not auto signup") request.session['socialaccount_sociallogin'] = sociallogin url = reverse('socialaccount_signup') ret = HttpResponseRedirect(url) else: # FIXME: There is some duplication of logic inhere # (create user, send email, in active etc..) log.debug("Auto sign up again") u = sociallogin.account.user u.username = generate_unique_username(u.username or email or 'user') u.last_name = (u.last_name or '') \ [0:User._meta.get_field('last_name').max_length] u.first_name = (u.first_name or '') \ [0:User._meta.get_field('first_name').max_length] u.email = email or '' u.set_unusable_password() log.debug(u) sociallogin.save() log.debug("Sending email to the following:") log.debug(email) send_email_confirmation(request, u) log.debug("Email confirmation sent") ret = complete_social_signup(request, sociallogin) log.debug(ret) return ret
def save(self, *args, **kwargs): user = super().save(commit=False, *args, **kwargs) if self._send_confirmation: send_email_confirmation(self.request, user) self._send_confirmation = False user.email_verified = False user.verify_email_by = now_plus_48_hours() user.save() return user
def dispatch(self, request, *args, **kwargs): """ Confirm valid user,and then confirm a verified email. """ if not request.user.is_authenticated: return self.handle_no_permission() elif not EmailAddress.objects.filter(user=request.user, verified=True).exists(): send_email_confirmation(request, request.user) # Should maybe be some kind of reverse blah blah blah return render(request, 'account/verified_email_required.html') return super().dispatch(request, *args, **kwargs)
def _wrapped_view(request, *args, **kwargs): context ={ 'domains': domains } if not EmailAddress.objects.filter(Q(user=request.user), reduce(lambda x, y: (x | y), [Q(email__icontains=domain) for domain in domains])).exists(): return render(request, 'account/email_required_domain.html', context) elif not EmailAddress.objects.filter(Q(user=request.user, verified=True), reduce(lambda x, y: (x | y), [Q(email__icontains=('@' + domain)) for domain in domains])).exists(): send_email_confirmation(request, request.user) return render(request, 'account/verified_email_required_domain.html', context) return view_func(request, *args, **kwargs)
def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] if not user.is_active: send_email_confirmation(request, user) return Response({'detail': 'User is inactive!'}, status=403) token, created = Token.objects.get_or_create(user=user) user_data = UserSerializer(user, many=False).data user_data['token'] = token.key return Response(user_data)
def post(self, *args, **kwargs): # if the email address is already verified, do nothing user = self.request.user has_verified_email = EmailAddress.objects.filter(user=user, verified=True).exists() if has_verified_email: return Response(None, HTTP_204_NO_CONTENT) # otherwise, send the confirmation email print("sending email confirmation...") allauth_utils.send_email_confirmation(self.request, user) return Response({'message': 'Account email verification sent'}, HTTP_200_OK)
def save(self, request): new_user = self.create_user() self.sociallogin.account.user = new_user self.sociallogin.save(request) super(SignupForm, self).save(new_user) # Make sure the user has a primary email address if EmailAddress.objects.filter(user=new_user).count() == 0: setup_user_email(request, new_user) # Confirmation last (save may alter first_name etc -- used in mail) send_email_confirmation(request, new_user) return new_user
def save(self, *args, **kwargs): user = super().save(commit=False, *args, **kwargs) if self._send_confirmation: send_email_confirmation(self.request, user) self._send_confirmation = False user.email_verified = False user.verify_email_by = (datetime.now(tz=timezone.utc) + timedelta(hours=48)) user.save() return user
def _process_signup(request, data, account): # If email is specified, check for duplicate and if so, no auto signup. auto_signup = app_settings.AUTO_SIGNUP email = data.get('email') if auto_signup: # Let's check if auto_signup is really possible... if email: if account_settings.UNIQUE_EMAIL: if email_address_exists(email): # Oops, another user already has this address. We # cannot simply connect this social account to the # existing user. Reason is that the email adress may # not be verified, meaning, the user may be a hacker # that has added your email address to his account in # the hope that you fall in his trap. We cannot check # on 'email_address.verified' either, because # 'email_address' is not guaranteed to be verified. auto_signup = False # FIXME: We redirect to signup form -- user will # see email address conflict only after posting # whereas we detected it here already. elif account_settings.EMAIL_REQUIRED: # Nope, email is required and we don't have it yet... auto_signup = False if not auto_signup: request.session['socialaccount_signup'] = dict(data=data, account=account) url = reverse('socialaccount_signup') next = request.REQUEST.get('next') if next: url = url + '?' + urlencode(dict(next=next)) ret = HttpResponseRedirect(url) else: # FIXME: There is some duplication of logic inhere # (create user, send email, in active etc..) username = generate_unique_username \ (data.get('username', email or 'user')) u = User(username=username, email=email or '', last_name = data.get('last_name', '')[0:User._meta.get_field('last_name').max_length], first_name = data.get('first_name', '')[0:User._meta.get_field('first_name').max_length]) u.set_unusable_password() u.is_active = not account_settings.EMAIL_VERIFICATION u.save() accountbase = SocialAccount() accountbase.user = u accountbase.save() account.base = accountbase account.sync(data) send_email_confirmation(u, request=request) ret = complete_social_signup(request, u, account) return ret
def perform_update(self, serializer): user = self.get_object() new_email = serializer.validated_data.get('email', user.email) if user.email != new_email: updated = serializer.save( email_verified=False, verify_email_by=now_plus_48_hours() ) try: send_email_confirmation(self.request._request, updated) except MessageFailure: pass else: serializer.save()
def _process_signup(request, data, account): # If email is specified, check for duplicate and if so, no auto signup. auto_signup = app_settings.AUTO_SIGNUP email = data.get("email") if auto_signup: # Let's check if auto_signup is really possible... if email: if account_settings.UNIQUE_EMAIL: email_address = get_email_address(email) if email_address: # Oops, another user already has this address. We # cannot simply connect this social account to the # existing user. Reason is that the email adress may # not be verified, meaning, the user may be a hacker # that has added your email address to his account in # the hope that you fall in his trap. We cannot check # on 'email_address.verified' either, because # 'email_address' is not guaranteed to be verified. auto_signup = False # FIXME: We redirect to signup form -- user will # see email address conflict only after posting # whereas we detected it here already. elif account_settings.EMAIL_REQUIRED: # Nope, email is required and we don't have it yet... auto_signup = False if not auto_signup: request.session["socialaccount_signup"] = dict(data=data, account=account) ret = HttpResponseRedirect(reverse("socialaccount_signup")) else: # FIXME: There is some duplication of logic inhere # (create user, send email, in active etc..) username = generate_unique_username(data.get("username", email or "user")) u = User( username=username, email=email or "", last_name=data.get("last_name", ""), first_name=data.get("first_name", ""), ) u.set_unusable_password() u.is_active = not account_settings.EMAIL_VERIFICATION u.save() account.user = u account.save() send_email_confirmation(u, request=request) ret = complete_signup(request, u, get_login_redirect_url(request)) return ret
def create(self, request, *args, **kwargs): params = request.data email = params.get('email') password = params.get('password') full_name = params.get('full_name') try: user = User.objects.create_user(email, password, full_name=full_name, active=True, channel='Android') social_data = request.data.get('social') if social_data: try: SocialLoginToken.create(user, social_data) except ValueError as e: raise APIException(str(e)) setup_user_email(request, user, []) send_email_confirmation(request, user, signup=True) except IntegrityError: return Response({'detail': 'The e-mail address already exists.'}, status=400) except Exception as e: return Response({'detail': str(e)}, status=400) return Response(self.serializer_class(user).data, status=status.HTTP_200_OK)
def perform_login(request, user, email_verification, return_data={}, signal_kwargs={}, signup=False): """ Keyword arguments: signup -- Indicates whether or not sending the email is essential (during signup), or if it can be skipped (e.g. in case email verification is optional and we are only logging in). """ from allauth.account.models import EmailAddress has_verified_email = EmailAddress.objects.filter(user=user, verified=True).exists() if email_verification == EmailVerificationMethod.NONE: pass elif email_verification == EmailVerificationMethod.OPTIONAL: # In case of OPTIONAL verification: send on signup. if not has_verified_email and signup: send_email_confirmation(request, user, signup=signup) elif email_verification == EmailVerificationMethod.MANDATORY: if not has_verified_email: send_email_confirmation(request, user, signup=signup) return Response({'message': 'Account email verification sent'}, HTTP_401_UNAUTHORIZED) # Local users are stopped due to form validation checking # is_active, yet, adapter methods could toy with is_active in a # `user_signed_up` signal. Furthermore, social users should be # stopped anyway. if not user.is_active: return Response({'message': 'User account is inactive'}, HTTP_403_FORBIDDEN) get_adapter().login(request, user) signals.user_logged_in.send(sender=user.__class__, request=request, user=user, **signal_kwargs) get_adapter().add_message(request, messages.SUCCESS, 'account/messages/logged_in.txt', {'user': user}) return_data.update({'message': 'User logged in.'}) return Response(return_data, HTTP_200_OK)
def register(request): """ Create a single user """ data = request.data serializer = UserRegisterSerializer(data=data) if serializer.is_valid(): timezone = Timezone.objects.get( name=serializer.validated_data['timezone_name'] ) user = LocalUser.objects.create_user( username=serializer.validated_data['email'], email=serializer.validated_data['email'], password=serializer.validated_data['password'], timezone=timezone ) send_email_confirmation(request._request, user, signup=True) return Response( UserSerializer(instance=user).data, status=status.HTTP_201_CREATED ) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request): serializer = self.get_serializer(data=request.data) try: serializer.is_valid(raise_exception=True) return self._action(serializer) except ValidationError: return Response( data=serializer.errors, status=status.HTTP_400_BAD_REQUEST, ) except EmailNotVerifiedError: user = serializer.user user.is_active = False user.save() try: send_email_confirmation(self.request._request, user) except MessageFailure: pass return Response( data={'detail': _("The email has not been verified.")}, status=status.HTTP_400_BAD_REQUEST, )
def complete_login(self, request, app, token, email_addresses=[]): client = TwitterAPI(request, app.client_id, app.secret, self.request_token_url) extra_data = client.get_user_info() uid = extra_data['id'] user = User.objects.filter(username=extra_data.get('screen_name')) if user: return user else: user = get_adapter() \ .populate_new_user(username=extra_data.get('screen_name'), name=extra_data.get('name')) user.save() account = SocialAccount(user=user, uid=uid, provider=TwitterProvider.id, extra_data=extra_data) account.save() application = SocialApp.objects.get(secret=app.secret) sample_token = SocialToken.objects.filter(app=application, account=account) if sample_token: token = sample_token[0] else: token = SocialToken(app=application, account=account, token=request.session["oauth_api.twitter.com_access_token"]["oauth_token"], token_secret=request.session["oauth_api.twitter.com_access_token"][ "oauth_token_secret"]) token.save() mail = send_email_confirmation(request=request, user=user, signup=True) return SocialLogin(account=account, token=token, email_addresses=email_addresses)
def save(self, request=None): new_user = self.create_user() send_email_confirmation(new_user, request=request) return new_user
def login(request, user): mail = send_email_confirmation(request=request, user=user, signup=False)
def save(self, request=None): new_user = self.create_user() send_email_confirmation(new_user, request=request) super(SignupForm, self).save(new_user) return new_user
def save(self, request=None): new_user = self.create_user() super(SignupForm, self).save(new_user) # Before confirmation (may alter first_name etc used in mail) send_email_confirmation(new_user, request=request) return new_user
def senMailOnSingUp(sender, request, user, **kwargs): send_email_confirmation(request, user, signup=True)