Example #1
0
    def form_valid(self, form):
        company = form["contact"].save(commit=False)
        is_new = not bool(company.pk)
        company.save()
        user = self.request.user
        person = get_person_contact(user)
        company.members.add(person)
        billing_address = form["billing"].save()
        shipping_address = form["shipping"].save()
        if billing_address.pk != company.default_billing_address_id:  # Identity changed due to immutability
            company.default_billing_address = billing_address
        if shipping_address.pk != company.default_shipping_address_id:  # Identity changed due to immutability
            company.default_shipping_address = shipping_address

        message = _("Company information saved successfully.")
        # If company registration requires activation,
        # company will be created as inactive.
        if is_new and company_registration_requires_approval(self.request.shop):
            company.is_active = False
            message = _("Company information saved successfully. "
                        "Please follow the instructions sent to your email address.")

        company.save()
        if is_new:
            user_registered.send(sender=self.__class__,
                                 user=self.request.user,
                                 request=self.request)
            CompanyAccountCreated(contact=company, customer_email=company.email).run(shop=self.request.shop)

        messages.success(self.request, message)
        return redirect("shuup:company_edit")
Example #2
0
def register_user(email, client, created_by, request, backend=None, site=None):
    """
    Register an inactive user and send an email to the email address provided.
    Associate the new user with the given client.
    Return a tuple of (new user, registration profile).
    """
    if site is None:
        site = Site.objects.get_current()
    if backend is None:
        backend = DefaultBackend

    # username wont be used, so we create a random string with 30 chars
    username = sha224(str(urandom(128))).hexdigest()[:30]
    password = ''
    new_user = RegistrationProfile.objects.create_inactive_user(
        username, email, password, site)
    registration_profile = RegistrationProfile.objects.get(user=new_user)
    # Create user profile
    user_profile = UserProfile.objects.create(
        user=new_user,
        active=False)
    user_profile.clients.add(client)
    user_profile.save()

    user_registered.send(sender=backend,
                         user=new_user,
                         request=request)

    return new_user, registration_profile
Example #3
0
def create_auth(request):
    serialized = UserSerializer(data=request.data,
                                context={'request': request})
    init_data = serialized.initial_data.copy()
    init_data['password1'] = init_data['password2'] = init_data.get('password')

    form = PersonRegForm(init_data, instance=User())
    if serialized.is_valid() and form.is_valid():
        new_user = get_user_model().objects.create_user(
            email=init_data['email'],
            username=init_data['username'],
            password=init_data['password'],
            first_name=init_data['first_name'],
            last_name=init_data['last_name'],
        )
        user_registered.send(sender=MestoRegistrationView,
                             user=new_user,
                             request=request)

        return Response(UserSerializer(new_user, context={
            'request': request
        }).data,
                        status=status.HTTP_201_CREATED)
    else:
        errors = dict(form.errors.items() + serialized._errors.items())
        return Response(errors, status=status.HTTP_400_BAD_REQUEST)
    def register(self, request, email=None):
        """ Create user; log in; send activation email

        Here's how it works:
         - Create a user with a random password
         - log them in (requires a password to be set)
         - sets the password to be unusable
         - send an email to complete registration

        This function assumes that the form has already been validated,
        meaning the email has already been verified as unique.
        """
        if email is None:
            raise ValueError('email cannot be None')
        user, password = create_user_and_password(request, email)
        # log in
        auth_user = authenticate(username=user.username, password=password)
        assert auth_user == user
        login(request, auth_user)
        user.set_unusable_password()
        user.save()
        request.user = user  # assign the created user and not the logged in user (this has a temporary password for login)
        # get site
        site = get_site(request)
        context = RequestContext(request, {'user' : user})
        send_activation_email(user, site, extra_context=context)
        user_registered.send(
            sender=self.__class__,
            user=user,
            request=request
        )
        return user
Example #5
0
 def register(self, form):
     user = User.objects.get(
         pk=self.request.session.get('registration_uid'))
     user.email = form.cleaned_data['email']
     user_registered.send(self.__class__, user=user, request=self.request)
     # Go to Step 3
     self.send_activation_email(user)
     return user
Example #6
0
    def register(self, form):
        profile = Profile.objects.create(show_full_name=form.cleaned_data['show_full_name'])
        user = profile.set_user(email=form.cleaned_data['email'],
                         username=form.cleaned_data['username'],
                         password=form.cleaned_data['password1'],
                         first_name=form.cleaned_data['first_name'],
                         last_name=form.cleaned_data['last_name'])

        user_registered.send(sender=self.__class__, user=user)
        return user
Example #7
0
 def register(self, form):
     user = User.objects.get(pk=self.request.session.get('registration_uid'))
     user.email = form.cleaned_data['email']
     user_registered.send(self.__class__, user=user, request=self.request)
     if getattr(settings, 'REGISTRATION_VERIFY_EMAIL', True):
         # Go to Step 3
         self.send_activation_email(user)
     else:
         user.is_active = True
         user.save()
         login(self.request, user, 'allianceauth.authentication.backends.StateBackend')
     return user
 def register(self, request, **cleaned_data):
     """Allow a new user to register via invitation."""
     username, email, password = cleaned_data['username'], \
                                 cleaned_data['email'], \
                                 cleaned_data['password1']
     User.objects.create_user(username, email, password)
     self.user = authenticate(username=username, password=password)
     login(request, self.user)
     user_registered.send(sender=self.__class__, user=self.user,
                          request=request)
     self.invitation.mark_accepted(self.user)
     return self.user
 def register(self, request, **cleaned_data):
     """Allow a new user to register via invitation."""
     username, email, password = cleaned_data['username'], \
                                 cleaned_data['email'], \
                                 cleaned_data['password1']
     User.objects.create_user(username, email, password)
     self.user = authenticate(username=username, password=password)
     login(request, self.user)
     user_registered.send(sender=self.__class__,
                          user=self.user,
                          request=request)
     self.invitation.mark_accepted(self.user)
     return self.user
Example #10
0
 def register(self, form):
     user = User.objects.get(
         pk=self.request.session.get('registration_uid'))
     user.email = form.cleaned_data['email']
     user_registered.send(self.__class__, user=user, request=self.request)
     if getattr(settings, 'REGISTRATION_VERIFY_EMAIL', True):
         # Go to Step 3
         self.send_activation_email(user)
     else:
         user.is_active = True
         user.save()
         login(self.request, user,
               'allianceauth.authentication.backends.StateBackend')
     return user
Example #11
0
    def test_worker_autocreation(self):
        """ When new users register, worker objects should be autocreated. """

        # Create a user
        user = UserFactory(username="******", password="******", email="*****@*****.**")

        # There should be no worker yet
        self.assertFalse(Worker.objects.filter(user=user).exists())

        # Fake registering the user
        user_registered.send(sender=self.__class__, user=user, request=None)

        # Expect the worker object to be created
        self.assertTrue(Worker.objects.filter(user=user).exists(), "Worker not autocreated on User registration")
Example #12
0
    def test_worker_autocreation(self):
        """ When new users register, worker objects should be autocreated. """

        # Create a user
        user = UserFactory(username='******',
                           password='******',
                           email='*****@*****.**')

        # There should be no worker yet
        self.assertFalse(Worker.objects.filter(user=user).exists())

        # Fake registering the user
        user_registered.send(sender=self.__class__, user=user, request=None)

        # Expect the worker object to be created
        self.assertTrue(
            Worker.objects.filter(user=user).exists(),
            'Worker not autocreated on User registration')
Example #13
0
    def register_new_user(self, request, email, password):
        """
        Create and immediately log in a new user.

        """
        email, password = email, password
        email = self.clean_email(email)
        username = self.generate_username(email)
        User.objects.create_user(username, email, password)

        # authenticate() always has to be called before login(), and
        # will return the user we just created.
        new_user = authenticate(username=username, password=password)
        login(request, new_user)
        user_registered.send(sender=self.__class__,
            user=new_user,
            request=request)
        return new_user
Example #14
0
    def save(self):
        company = self.forms["contact"].save(commit=False)
        is_new = not bool(company.pk)
        company.save()
        user = self.request.user

        # TODO: Should this check if contact will be created? Or should we expect create always?
        person = get_person_contact(user)
        person.add_to_shop(self.request.shop)
        company.members.add(person)
        company.add_to_shop(self.request.shop)

        if "billing" in self.forms:
            billing_address = self.forms["billing"].save()
            if billing_address.pk != company.default_billing_address_id:  # Identity changed due to immutability
                company.default_billing_address = billing_address

        if "shipping" in self.forms:
            shipping_address = self.forms["shipping"].save()
            if shipping_address.pk != company.default_shipping_address_id:  # Identity changed due to immutability
                company.default_shipping_address = shipping_address

        message = _("Company information saved successfully.")
        # If company registration requires activation,
        # company will be created as inactive.
        if is_new and company_registration_requires_approval(
                self.request.shop):
            company.is_active = False
            message = _(
                "Company information saved successfully. "
                "Please follow the instructions sent to your email address.")

        messages.success(self.request, message)
        company.save()

        if is_new:
            user_registered.send(sender=self.__class__,
                                 user=self.request.user,
                                 request=self.request)
            CompanyAccountCreated(
                contact=company,
                customer_email=company.email).run(shop=self.request.shop)

        return company
Example #15
0
 def register(self, request, **cleaned_data):
     """Allow a new user to register via invitation."""
     backend = InvitationBackend()
     email, password = cleaned_data['email'], \
                       cleaned_data['password1']
     first_name = cleaned_data['first_name'] or None
     last_name = cleaned_data['last_name'] or None
     print "calling register with %s" % cleaned_data
     new_user = backend.register(request,
                                 email=email,
                                 password=password,
                                 first_name=first_name,
                                 last_name=last_name)
     self.user = authenticate(email=new_user.username, password=password)
     login(request, self.user)
     user_registered.send(sender=self.__class__,
                          user=self.user,
                          request=request)
     self.invitation.mark_accepted(self.user)
     return self.user
Example #16
0
 def register(self, request, **cleaned_data):
     user_id = tasks.addplayer.delay(
         name    = cleaned_data['character_name'],
         passwd    = cleaned_data['passwd'],
         enabled    = False,
     ).get(timeout=5)
     
     assert user_id is not None, "Didn't get an entity ID back from addplayer"
     
     player = models.Player.objects.get(avatar_id=user_id)
     activation_key = get_activation_key(cleaned_data['character_name'])
     
     # it's a hack, but it works well
     player.__class__ = models.RegisteredPlayer
     player.email = cleaned_data['email']
     player.activation_key = activation_key
     player.save()
     
     user_registered.send(sender=self.__class__, user=player, request=request)
     
     return player
Example #17
0
 def register(self, form):
     """Standard `register` method overwritten in order to properly handle our custom `payment_plan` form field."""
     new_user = form.save(commit=False)
     username_field = getattr(new_user, 'USERNAME_FIELD', 'username')
     # Save lowercased email as username.
     setattr(new_user, username_field, form.cleaned_data['email'].lower())
     new_user.first_name = form.cleaned_data['first_name']
     new_user.last_name = form.cleaned_data['last_name']
     new_user.save()
     new_user = authenticate(username=getattr(new_user, username_field), password=form.cleaned_data['password1'])
     login(self.request, new_user)
     user_registered.send(sender=self.__class__, user=new_user, request=self.request)
     profile, _ = Profile.objects.get_or_create(user=new_user)
     self.request.session['signed_up'] = True
     profile.payment_plan = int(form.cleaned_data['payment_plan'])
     profile.company_name = form.cleaned_data['company']
     profile.phone = form.cleaned_data['phone']
     profile.save(update_fields=['payment_plan', 'company_name', 'phone'])
     if profile.payment_plan != Profile.PAYMENT_PLAN_FREE:
         messages.add_message(self.request, messages.INFO,
                              'Congratulations! We won\'t charge you for this plan for now.')
     return new_user
Example #18
0
    def save(self):
        company = self.forms["contact"].save(commit=False)
        is_new = not bool(company.pk)
        company.save()
        user = self.request.user

        # TODO: Should this check if contact will be created? Or should we expect create always?
        person = get_person_contact(user)
        person.add_to_shop(self.request.shop)
        company.members.add(person)
        company.add_to_shop(self.request.shop)

        if "billing" in self.forms:
            billing_address = self.forms["billing"].save()
            if billing_address.pk != company.default_billing_address_id:  # Identity changed due to immutability
                company.default_billing_address = billing_address

        if "shipping" in self.forms:
            shipping_address = self.forms["shipping"].save()
            if shipping_address.pk != company.default_shipping_address_id:  # Identity changed due to immutability
                company.default_shipping_address = shipping_address

        message = _("Company information saved successfully.")
        # If company registration requires activation,
        # company will be created as inactive.
        if is_new and company_registration_requires_approval(self.request.shop):
            company.is_active = False
            message = _("Company information saved successfully. "
                        "Please follow the instructions sent to your email address.")

        messages.success(self.request, message)
        company.save()

        if is_new:
            user_registered.send(sender=self.__class__, user=self.request.user, request=self.request)
            CompanyAccountCreated(contact=company, customer_email=company.email).run(shop=self.request.shop)

        return company
Example #19
0
    def form_valid(self, form):
        company = form["contact"].save(commit=False)
        is_new = not bool(company.pk)
        company.save()
        user = self.request.user
        person = get_person_contact(user)
        company.members.add(person)
        billing_address = form["billing"].save()
        shipping_address = form["shipping"].save()
        if billing_address.pk != company.default_billing_address_id:  # Identity changed due to immutability
            company.default_billing_address = billing_address
        if shipping_address.pk != company.default_shipping_address_id:  # Identity changed due to immutability
            company.default_shipping_address = shipping_address

        user.email = company.email
        user.first_name = company.name
        user.last_name = ""
        user.save()

        message = _("Company information saved successfully.")
        # If company registration requires activation,
        # company will be created as inactive.
        if is_new and configuration.get(None, "company_registration_requires_approval"):
            company.is_active = False
            message = _("Company information saved successfully. "
                        "Please follow the instructions sent to your email address.")

        company.save()
        if is_new:
            user_registered.send(sender=self.__class__,
                                 user=self.request.user,
                                 request=self.request)
            CompanyAccountCreated(contact=company, customer_email=company.email).run()

        messages.success(self.request, message)
        return redirect("shuup:company_edit")
Example #20
0
    def register(self, form):
        formuser = RegistrationForm(
            data={
                'username': form.cleaned_data["username"],
                'email': form.cleaned_data["email"],
                'password1': form.cleaned_data["password1"],
                'password2': form.cleaned_data["password2"]
            })
        new_user = self.create_inactive_user(formuser)
        user_registered.send(sender=self.__class__,
                             user=new_user,
                             request=self.request)

        if get_current_site(self.request).domain == 'localhost:8000':
            grupo = Group.objects.get(name='Sitios_Admin')
            grupo.user_set.add(new_user)
            new_user.is_staff = True
            new_user.save()
        else:
            Forum_User_Profile.objects.create(user=new_user,
                                              sites=get_current_site(
                                                  self.request))
            new_user.save()
        return new_user
Example #21
0
 def register(self, form):
     new_user = self.create_inactive_user(form)
     user_registered.send(sender=self.__class__,
                          user=new_user,
                          request=self.request)
     return new_user
Example #22
0
def register(request,
             invitation_key,
             wrong_key_template='invitation/wrong_invitation_key.html',
             redirect_to_if_authenticated='/',
             success_url=None,
             form_class=RegistrationFormInvitation,
             template_name='registration/registration_form.html',
             extra_context=None):
    """
    Allow a new user to register via invitation.

    Send invitation email and then redirect to success URL if the
    invitation form is valid. Redirect named URL ``invitation_unavailable``
    on InvitationError. Render invitation form template otherwise. Sends
    registration.signals.user_registered after creating the user.

    **Required arguments:**

    :invitation_key:
        An invitation key in the form of ``[\da-e]{40}``

    **Optional arguments:**

    :wrong_key_template:
        Template to be used when an invalid invitation key is supplied.
        Default value is ``invitation/wrong_invitation_key.html``.

    :redirect_to_if_authenticated:
        URL to be redirected when an authenticated user calls this view.
        Defaults value is ``/``

    :success_url:
        The URL to redirect to on successful registration. Default value is
        ``None``, ``invitation_registered`` will be resolved in this case.

    :form_class:
        A form class to use for registration. Takes the invited email as first
        argument to its constructor.

    :template_name:
        A custom template to use. Default value is
        ``registration/registration_form.html``.

    :extra_context:
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context.

    **Templates:**

    ``invitation/invitation_form.html`` or ``template_name`` keyword
    argument as the *main template*.

    ``invitation/wrong_invitation_key.html`` or ``wrong_key_template`` keyword
    argument as the *wrong key template*.

    **Context:**

    ``RequestContext`` instances are used rendering both templates. Context,
    in addition to ``extra_context``, contains:

    For wrong key template
        :invitation_key: supplied invitation key

    For main template
        :form:
            The registration form.
    """
    if request.user.is_authenticated():
        return HttpResponseRedirect(redirect_to_if_authenticated)
    try:
        invitation = Invitation.objects.find(invitation_key)
    except Invitation.DoesNotExist:
        context = apply_extra_context(RequestContext(request), extra_context)
        return render_to_response(wrong_key_template,
                                  {'invitation_key': invitation_key},
                                  context_instance=context)
    if request.method == 'POST':
        form = form_class(invitation.email, request.POST, request.FILES)
        if form.is_valid():
            new_user = form.save()
            invitation.mark_accepted(new_user)
            user_registered.send(sender="invitation",
                                 user=new_user,
                                 request=request)
            # return HttpResponseRedirect(success_url or reverse('invitation_registered'))
            # return HttpResponseRedirect(success_url or reverse('profiles-profile-detail', kwargs={'slug':new_user.username}))
            return HttpResponseRedirect(success_url or reverse('auth_login'))
    else:
        form = form_class(invitation.email)
    context = apply_extra_context(RequestContext(request), extra_context)
    return render_to_response(template_name,
                              {'form': form},
                              context_instance=context)
Example #23
0
    def create_inactive_user(self, username, password, email, domain_override="", 
                             send_email=True):
        """
        Create a new, inactive ``User``, generate a
        ``RegistrationProfile`` and email its activation key to the
        ``User``, returning the new ``User``.
        
        To disable the email, call with ``send_email=False``.

        The activation email will make use of two templates:

        ``registration/activation_email_subject.txt``
            This template will be used for the subject line of the
            email. It receives one context variable, ``site``, which
            is the currently-active
            ``django.contrib.sites.models.Site`` instance. Because it
            is used as the subject line of an email, this template's
            output **must** be only a single line of text; output
            longer than one line will be forcibly joined into only a
            single line.

        ``registration/activation_email.txt``
            This template will be used for the body of the email. It
            will receive three context variables: ``activation_key``
            will be the user's activation key (for use in constructing
            a URL to activate the account), ``expiration_days`` will
            be the number of days for which the key will be valid and
            ``site`` will be the currently-active
            ``django.contrib.sites.models.Site`` instance.

        To execute customized logic once the new ``User`` has been
        created, connect a function to the signal
        ``registration.signals.user_registered``; this signal will be
        sent (with the new ``User`` as the value of the keyword
        argument ``user``) after the ``User`` and
        ``RegistrationProfile`` have been created, and the email (if
        any) has been sent..
        
        """
        from registration.signals import user_registered
        # prepend "key_" to the key_name, because key_names can't start with numbers
        new_user = User(username=username, key_name="key_"+username.lower(),
            email=email, is_active=False)
        new_user.set_password(password)
        new_user.put()
        
        registration_profile = self.create_profile(new_user)
        
        if send_email:
            from django.core.mail import send_mail
            current_site = domain_override
#            current_site = Site.objects.get_current()
            
            subject = render_to_string('registration/activation_email_subject.txt',
                                       { 'site': current_site })
            # Email subject *must not* contain newlines
            subject = ''.join(subject.splitlines())
            
            message = render_to_string('registration/activation_email.txt',
                                       { 'activation_key': registration_profile.activation_key,
                                         'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
                                         'site': current_site })
            
            send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [new_user.email])
        user_registered.send(sender=self.model, user=new_user)
        return new_user
Example #24
0
def register(request,
             invitation_key,
             wrong_key_template='invitation/wrong_invitation_key.html',
             redirect_to_if_authenticated='/',
             success_url=None,
             form_class=RegistrationFormInvitation,
             template_name='registration/registration_form.html',
             extra_context=None):
    """
    Allow a new user to register via invitation.

    Send invitation email and then redirect to success URL if the
    invitation form is valid. Redirect named URL ``invitation_unavailable``
    on InvitationError. Render invitation form template otherwise. Sends
    registration.signals.user_registered after creating the user.

    **Required arguments:**

    :invitation_key:
        An invitation key in the form of ``[\da-e]{40}``

    **Optional arguments:**

    :wrong_key_template:
        Template to be used when an invalid invitation key is supplied.
        Default value is ``invitation/wrong_invitation_key.html``.

    :redirect_to_if_authenticated:
        URL to be redirected when an authenticated user calls this view.
        Defaults value is ``/``

    :success_url:
        The URL to redirect to on successful registration. Default value is
        ``None``, ``invitation_registered`` will be resolved in this case.

    :form_class:
        A form class to use for registration. Takes the invited email as first
        argument to its constructor.

    :template_name:
        A custom template to use. Default value is
        ``registration/registration_form.html``.

    :extra_context:
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context.

    **Templates:**

    ``invitation/invitation_form.html`` or ``template_name`` keyword
    argument as the *main template*.

    ``invitation/wrong_invitation_key.html`` or ``wrong_key_template`` keyword
    argument as the *wrong key template*.

    **Context:**

    ``RequestContext`` instances are used rendering both templates. Context,
    in addition to ``extra_context``, contains:

    For wrong key template
        :invitation_key: supplied invitation key

    For main template
        :form:
            The registration form.
    """
    if request.user.is_authenticated():
        return HttpResponseRedirect(redirect_to_if_authenticated)
    try:
        invitation = Invitation.objects.find(invitation_key)
    except Invitation.DoesNotExist:
        context = apply_extra_context(RequestContext(request), extra_context)
        return render_to_response(wrong_key_template,
                                  {'invitation_key': invitation_key},
                                  context_instance=context)
    if request.method == 'POST':
        form = form_class(invitation.email, request.POST, request.FILES)
        if form.is_valid():
            new_user = form.save()
            invitation.mark_accepted(new_user)
            user_registered.send(sender="invitation",
                                 user=new_user,
                                 request=request)
            """
            bit hackish... authenticate & login the user
            """
            new_user.backend = 'django.contrib.auth.backends.ModelBackend'
            login(request, new_user)
            return HttpResponseRedirect(new_user.get_absolute_url())
            #return HttpResponseRedirect(success_url or reverse('auth_login'))
    else:
        form = form_class(invitation.email)
    context = apply_extra_context(RequestContext(request), extra_context)
    return render_to_response(template_name, {'form': form},
                              context_instance=context)
Example #25
0
    def register(self, request, **kwargs):
        """
        Given core dealer information, create a new ``Dealer`` object 
        in 'PENDING' status.

        Along with the new ``Dealer`` object, a new
        ``registration.models.RegistrationProfile`` will be created,
        tied to that ``Dealer``, containing the activation key which
        will be used for this account.

        An email will be sent to the supplied email address; this
        email should contain an activation link. The email will be
        rendered using two templates. See the documentation for
        ``RegistrationProfile.send_activation_email()`` for
        information about these templates and the contexts provided to
        them.

        After the ``Dealer`` and ``RegistrationProfile`` are created and
        the activation email is sent, the signal
        ``registration.signals.user_registered`` will be sent, with
        the new ``User`` as the keyword argument ``user`` and the
        class of this backend as the sender.

        """        
        
        logger.debug('DealerRegistrationBackend: register(%s) called', kwargs)
        
        first_name, last_name, company_name, email = kwargs.pop('first_name'), kwargs.pop('last_name'), kwargs['legal_name'], kwargs['email']
        notes = {}
        for key in ('rush', 'product_type', 'revisions', 'expected_orders', 'tos' ):
            notes[key] = kwargs.pop(key)
        
        if Site._meta.installed:
            site = Site.objects.get_current()
        else:
            site = RequestSite(request)

        temp_username = sha1(company_name+str(datetime.now())).hexdigest()[:25]
        new_user = RegistrationProfile.objects.create_inactive_user(temp_username, email,
                                                                    None, site, send_email=False)
        try:
            new_user.first_name = first_name
            new_user.last_name = last_name
            new_user.save()
            
            new_dealer = Dealer(**kwargs)
            new_dealer.notes = '\n'.join(['%s: %s' % (k,v) for (k,v) in notes.items()])
            new_dealer.status = Dealer.Const.PENDING
            new_dealer.save()
            
            new_profile = UserProfile(user=new_user, account=new_dealer)
            new_profile.primary = True
            new_profile.save()        
            
            notify_new_dealer_registration(new_dealer)
                
        except Exception as ex:
            logger.error('DealerRegistrationBackend: registration failure: %s - rolling back', ex)
            transaction.rollback()
            new_user.delete()
            transaction.commit()
#            return False
            raise ex
        else:
            transaction.commit()
        
        user_registered.send(sender=self.__class__,
                                     user=new_user,
                                     request=request)
        logger.info('DealerRegistrationBackend: new registration for %s/%s', new_user, new_dealer)
        return new_user 
Example #26
0
    def create_inactive_user(self,
                             username,
                             password,
                             email,
                             domain_override="",
                             send_email=True):
        """
        Create a new, inactive ``User``, generate a
        ``RegistrationProfile`` and email its activation key to the
        ``User``, returning the new ``User``.
        
        To disable the email, call with ``send_email=False``.

        The activation email will make use of two templates:

        ``registration/activation_email_subject.txt``
            This template will be used for the subject line of the
            email. It receives one context variable, ``site``, which
            is the currently-active
            ``django.contrib.sites.models.Site`` instance. Because it
            is used as the subject line of an email, this template's
            output **must** be only a single line of text; output
            longer than one line will be forcibly joined into only a
            single line.

        ``registration/activation_email.txt``
            This template will be used for the body of the email. It
            will receive three context variables: ``activation_key``
            will be the user's activation key (for use in constructing
            a URL to activate the account), ``expiration_days`` will
            be the number of days for which the key will be valid and
            ``site`` will be the currently-active
            ``django.contrib.sites.models.Site`` instance.

        To execute customized logic once the new ``User`` has been
        created, connect a function to the signal
        ``registration.signals.user_registered``; this signal will be
        sent (with the new ``User`` as the value of the keyword
        argument ``user``) after the ``User`` and
        ``RegistrationProfile`` have been created, and the email (if
        any) has been sent..
        
        """
        from registration.signals import user_registered
        # prepend "key_" to the key_name, because key_names can't start with numbers
        new_user = User(username=username,
                        key_name="key_" + username.lower(),
                        email=email,
                        is_active=False)
        new_user.set_password(password)
        new_user.put()

        registration_profile = self.create_profile(new_user)

        #        if send_email:
        #            from django.core.mail import send_mail
        #            current_site = domain_override
        ##            current_site = Site.objects.get_current()
        #
        #            subject = render_to_string('registration/activation_email_subject.txt',
        #                                       { 'site': current_site })
        #            # Email subject *must not* contain newlines
        #            subject = ''.join(subject.splitlines())
        #
        #            message = render_to_string('registration/activation_email.txt',
        #                                       { 'activation_key': registration_profile.activation_key,
        #                                         'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
        #                                         'site': current_site })
        #
        #            send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [new_user.email])
        """Отправка письма через google API"""
        if send_email:
            from google.appengine.api import mail
            current_site = domain_override

            message = mail.EmailMessage(
                sender="*****@*****.**",
                to=new_user.email,
                subject=render_to_string(
                    'registration/activation_email_subject.txt',
                    {'site': current_site}),
                body=render_to_string(
                    'registration/activation_email.txt', {
                        'activation_key': registration_profile.activation_key,
                        'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
                        'site': current_site
                    }))
            message.send()

        user_registered.send(sender=self.model, user=new_user)
        return new_user
Example #27
0
    def create_inactive_user(self, username, password, email, send_email=True):
        """
        Create a new, inactive ``User``, generate a
        ``RegistrationProfile`` and email its activation key to the
        ``User``, returning the new ``User``.
        
        To disable the email, call with ``send_email=False``.

        The activation email will make use of two templates:

        ``registration/activation_email_subject.txt``
            This template will be used for the subject line of the
            email. It receives one context variable, ``site``, which
            is the currently-active
            ``django.contrib.sites.models.Site`` instance. Because it
            is used as the subject line of an email, this template's
            output **must** be only a single line of text; output
            longer than one line will be forcibly joined into only a
            single line.

        ``registration/activation_email.txt``
            This template will be used for the body of the email. It
            will receive three context variables: ``activation_key``
            will be the user's activation key (for use in constructing
            a URL to activate the account), ``expiration_days`` will
            be the number of days for which the key will be valid and
            ``site`` will be the currently-active
            ``django.contrib.sites.models.Site`` instance.

        To execute customized logic once the new ``User`` has been
        created, connect a function to the signal
        ``registration.signals.user_registered``; this signal will be
        sent (with the new ``User`` as the value of the keyword
        argument ``user``) after the ``User`` and
        ``RegistrationProfile`` have been created, and the email (if
        any) has been sent..
        
        """
        from registration.signals import user_registered

        new_user = User.objects.create_user(username, email, password)
        new_user.is_active = False
        new_user.is_staff = True
        new_user.save()

        registration_profile = self.create_profile(new_user)

        if send_email:
            from django.core.mail import send_mail, EmailMultiAlternatives

            current_site = Site.objects.get_current()

            subject = render_to_string(
                'registration/activation_email_subject.txt',
                {'site': 'troggle'})
            # Email subject *must not* contain newlines
            subject = ''.join(subject.splitlines())

            text_content = render_to_string(
                'registration/activation_email.txt', {
                    'activation_key': registration_profile.activation_key,
                    'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
                    'site': 'troggle'
                })
            html_content = render_to_string(
                'registration/activation_email.html', {
                    'activation_key': registration_profile.activation_key,
                    'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
                    'site': 'troggle'
                })
            msg = EmailMultiAlternatives(subject, text_content,
                                         settings.DEFAULT_FROM_EMAIL,
                                         [new_user.email])
            msg.attach_alternative(html_content, "text/html")
            msg.send()


#            send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [new_user.email])
        user_registered.send(sender=self.model, user=new_user)
        return new_user