Exemplo n.º 1
0
def register_user(request):
    print("registrando um novo usuário")
    profile_form = get_profile_form()
    form = profile_form(request.POST or None, request.FILES or None)
    print(form)
    print(dir(form))
    print(form.is_valid())
    if request.method == "POST" and form.is_valid():
        print("Método post e form válido")
        new_user = form.save()
        if not new_user.is_active:
            if settings.ACCOUNTS_APPROVAL_REQUIRED:
                print('Usuário cadastrado, aguardando aprovação')
                send_approve_mail(request, new_user)
                info(
                    request, "Obrigado por se cadastrar! Você receberá um "
                    "email quando sua conta for ativada.")
            else:
                print('Usuário cadastrado, aguardando confirmação')
                send_verification_mail(request, new_user, "signup_verify")
                info(
                    request, "Um email de verificação foi enviado com um "
                    "link para ativação de sua conta.")
            return redirect(next_url(request) or "/")
        else:
            print('usuário cadastrado com sucesso')
            info(request, "Cadastro realizado com sucesso")
            login(request, new_user)
            return login_redirect(request)
    else:
        error(request, form)
        return redirect(request.META['HTTP_REFERER'] + "#cadastro",
                        kwargs={'registration_form': form})
    return redirect(next_url(request) or request.META['HTTP_REFERER'])
Exemplo n.º 2
0
def send_action_to_take_email(request, user, action_type, **kwargs):
    """
    Sends an email with an action link to a user.
    The actual action takes place when the user clicks on the link

    The ``action_type`` arg is both the name of the urlpattern for
    the action link, as well as the names of the email templates
    to use. Additional context variable needed in the email template can be
    passed using the kwargs

    for action_type == 'group_membership', an instance of GroupMembershipRequest and
    instance of Group are expected to
    be passed into this function
    """
    email_to = kwargs.get('group_owner', user)
    context = {'request': request, 'user': user}
    if action_type == 'group_membership':
        membership_request = kwargs['membership_request']
        action_url = reverse(
            action_type,
            kwargs={
                "uidb36": int_to_base36(email_to.id),
                "token": default_token_generator.make_token(email_to),
                "membership_request_id": membership_request.id
            }) + "?next=" + (next_url(request) or "/")

        context['group'] = kwargs.pop('group')
    elif action_type == 'group_auto_membership':
        context['group'] = kwargs.pop('group')
        action_url = ''
    else:
        action_url = reverse(
            action_type,
            kwargs={
                "uidb36": int_to_base36(email_to.id),
                "token": default_token_generator.make_token(email_to)
            }) + "?next=" + (next_url(request) or "/")

    context['action_url'] = action_url
    context.update(kwargs)

    subject_template_name = "email/%s_subject.txt" % action_type
    subject = subject_template(subject_template_name, context)
    send_mail_template(subject,
                       "email/%s" % action_type,
                       settings.DEFAULT_FROM_EMAIL,
                       email_to.email,
                       context=context)
Exemplo n.º 3
0
def send_verification_mail_for_email_update(request, user, new_email, verification_type):
    """
    Sends an email with a verification link to users when
    they update their email. The email is sent to the new email.
    The actual update of the email happens only after
    the verification link is clicked.
    The ``verification_type`` arg is both the name of the urlpattern for
    the verification link, as well as the names of the email templates
    to use.
    """
    verify_url = reverse(verification_type, kwargs={
        "uidb36": int_to_base36(user.id),
        "token": default_token_generator.make_token(user),
        "new_email": new_email
    }) + "?next=" + (next_url(request) or "/")
    context = {
        "request": request,
        "user": user,
        "new_email": new_email,
        "verify_url": verify_url,
    }
    subject_template_name = "email/%s_subject.txt" % verification_type
    subject = subject_template(subject_template_name, context)
    send_mail_template(subject, "email/%s" % verification_type,
                       settings.DEFAULT_FROM_EMAIL, new_email,
                       context=context)
Exemplo n.º 4
0
 def process_view(self, request, view_func, view_args, view_kwargs):
     login_type = request.POST.get("mezzanine_login_interface")
     if login_type and not is_authenticated(request.user):
         response = view_func(request, *view_args, **view_kwargs)
         if is_authenticated(request.user):
             if login_type == "admin":
                 next = next_url(request) or request.get_full_path()
                 username = request.user.get_username()
                 if username == DEFAULT_USERNAME and request.user.check_password(
                     DEFAULT_PASSWORD
                 ):
                     error(
                         request,
                         mark_safe(
                             _(
                                 "Your account is using the default password, "
                                 "please <a href='%s'>change it</a> immediately."
                             )
                             % reverse(
                                 "user_change_password", args=(request.user.id,)
                             )
                         ),
                     )
             else:
                 next = "/"
             return HttpResponseRedirect(next)
         else:
             return response
     return None
Exemplo n.º 5
0
def logout(request):
    """
    Log the user out.
    """
    auth_logout(request)
    info(request, _("Successfully logged out"))
    return redirect(next_url(request) or get_script_prefix())
Exemplo n.º 6
0
def send_verification_mail(request, user, verification_type):
    """
    Sends an email with a verification link to users when
    ``ACCOUNTS_VERIFICATION_REQUIRED`` is ```True`` and they're signing
    up, or when they reset a lost password.
    The ``verification_type`` arg is both the name of the urlpattern for
    the verification link, as well as the names of the email templates
    to use.
    """
    verify_url = (
        reverse(
            verification_type,
            kwargs={"uidb36": int_to_base36(user.id), "token": default_token_generator.make_token(user)},
        )
        + "?next="
        + (next_url(request) or "/")
    )
    context = {"request": request, "user": user, "verify_url": verify_url}
    subject_template_name = "email/%s_subject.txt" % verification_type
    subject = subject_template(subject_template_name, context)
    send_mail_template(
        subject,
        "email/%s" % verification_type,
        settings.DEFAULT_FROM_EMAIL,
        user.email,
        context=context,
        fail_silently=settings.DEBUG,
    )
Exemplo n.º 7
0
def signup(request, template="accounts/account_signup.html"):
    """
    Signup form.
    """
    profile_form = UserRegistrationLeadForm
    form = profile_form(request.POST or None, request.FILES or None)
    if request.method == "POST" and form.is_valid():
        data = form.cleaned_data.copy()

        # ensure user is not a robot
        honeypot = data.pop('superpriority')
        if honeypot:
            raise PermissionDenied

        # save the user
        new_user = form.save()

        if not new_user.is_active:
            if settings.ACCOUNTS_APPROVAL_REQUIRED:
                send_approve_mail(request, new_user)
                info(request, _("Thanks for signing up! You'll receive "
                                "an email when your account is activated."))
            else:
                send_verification_mail(request, new_user, "signup_verify")
                info(request, _("A verification email has been sent with "
                                "a link for activating your account."))
            return redirect(next_url(request) or "/")
        else:
            info(request, _("Successfully signed up"))
            auth_login(request, new_user)
            return login_redirect(request)
    context = {"form": form, "title": _("Sign up")}
    return render(request, template, context)
Exemplo n.º 8
0
def signup(request, template="accounts/account_signup.html",
           extra_context=None):
    """
    Signup form.
    """
    #Staat in admin_forms
    form = NewUserCreationForm(request.POST or None, request.FILES or None)
    if request.method == "POST" and form.is_valid():
        new_user = form.save()
        if not new_user.is_active:
            if settings.ACCOUNTS_APPROVAL_REQUIRED:
                send_approve_mail(request, new_user)
                info(request, _("Thanks for signing up! You'll receive "
                                "an email when your account is activated."))
            else:
                send_verification_mail(request, new_user, "signup_verify")
                info(request, _("A verification email has been sent with "
                                "a link for activating your account."))
            return redirect(next_url(request) or "/")
        else:
            info(request, _("Successfully signed up"))
            auth_login(request, new_user)
            return login_redirect(request)
    context = {"form": form, "title": _("Sign up")}
    context.update(extra_context or {})
    return render(request, template, context)
Exemplo n.º 9
0
def send_verification_mail_for_email_update(request, user, new_email,
                                            verification_type):
    """
    Sends an email with a verification link to users when
    they update their email. The email is sent to the new email.
    The actual update of the email happens only after
    the verification link is clicked.
    The ``verification_type`` arg is both the name of the urlpattern for
    the verification link, as well as the names of the email templates
    to use.
    """
    verify_url = reverse(verification_type,
                         kwargs={
                             "uidb36": int_to_base36(user.id),
                             "token": default_token_generator.make_token(user),
                             "new_email": new_email
                         }) + "?next=" + (next_url(request) or "/")
    context = {
        "request": request,
        "user": user,
        "new_email": new_email,
        "verify_url": verify_url,
    }
    subject_template_name = "email/%s_subject.txt" % verification_type
    subject = subject_template(subject_template_name, context)
    send_mail_template(subject,
                       "email/%s" % verification_type,
                       settings.DEFAULT_FROM_EMAIL,
                       new_email,
                       context=context)
Exemplo n.º 10
0
def logout(request):
    """
    Log the user out.
    """
    auth_logout(request)
    info(request, _("Successfully logged out"))
    return redirect(next_url(request) or get_script_prefix())
Exemplo n.º 11
0
def send_verification_mail(request, user, verification_type):
    """
    Sends an email with a verification link to users when
    ``ACCOUNTS_VERIFICATION_REQUIRED`` is ```True`` and they're signing
    up, or when they reset a lost password.
    The ``verification_type`` arg is both the name of the urlpattern for
    the verification link, as well as the names of the email templates
    to use.
    """
    verify_url = reverse(verification_type,
                         kwargs={
                             "uidb36": int_to_base36(user.id),
                             "token": default_token_generator.make_token(user),
                         }) + "?next=" + (next_url(request) or "/")
    context = {
        "request": request,
        "user": user,
        "verify_url": verify_url,
    }
    subject_template_name = "email/%s_subject.txt" % verification_type
    subject = subject_template(subject_template_name, context)
    send_mail_template(subject,
                       "email/%s" % verification_type,
                       settings.DEFAULT_FROM_EMAIL,
                       user.email,
                       context=context)
Exemplo n.º 12
0
def signup(request,
           template="accounts/account_signup.html",
           extra_context=None):
    """
    Signup form.
    """
    profile_form = get_profile_form()
    form = profile_form(request.POST or None, request.FILES or None)
    if request.method == "POST" and form.is_valid():
        new_user = form.save()
        if not new_user.is_active:
            if settings.ACCOUNTS_APPROVAL_REQUIRED:
                send_approve_mail(request, new_user)
                info(
                    request,
                    _("Thanks for signing up! You'll receive "
                      "an email when your account is activated."))
            else:
                send_verification_mail(request, new_user, "signup_verify")
                info(
                    request,
                    _("A verification email has been sent with "
                      "a link for activating your account."))
            return redirect(next_url(request) or "/")
        else:
            info(request, _("Successfully signed up"))
            auth_login(request, new_user)
            return login_redirect(request)
    context = {"form": form, "title": _("Sign up")}
    context.update(extra_context or {})
    return TemplateResponse(request, template, context)
Exemplo n.º 13
0
def set_device(request, device=""):
    """
    Sets a device name in a cookie when a user explicitly wants to go
    to the site for a particular device (eg mobile).
    """
    response = redirect(add_cache_bypass(next_url(request) or "/"))
    set_cookie(response, "mezzanine-device", device, 60 * 60 * 24 * 365)
    return response
Exemplo n.º 14
0
def set_device(request, device=""):
    """
    Sets a device name in a cookie when a user explicitly wants to go
    to the site for a particular device (eg mobile).
    """
    response = redirect(add_cache_bypass(next_url(request) or "/"))
    set_cookie(response, "mezzanine-device", device, 60 * 60 * 24 * 365)
    return response
Exemplo n.º 15
0
def signup(request,
           template="accounts/account_signup.html",
           extra_context=None):
    """
    Signup form. Overriding mezzanine's view function for signup submit
    """
    form = SignupForm(request, request.POST, request.FILES)
    if request.method == "POST" and form.is_valid():
        try:
            new_user = form.save()
        except ValidationError as e:
            messages.error(request, e.message)
            return HttpResponseRedirect(request.META['HTTP_REFERER'])
        else:
            if not new_user.is_active:
                if settings.ACCOUNTS_APPROVAL_REQUIRED:
                    send_approve_mail(request, new_user)
                    info(
                        request,
                        _("Thanks for signing up! You'll receive "
                          "an email when your account is activated."))
                else:
                    send_verification_mail(request, new_user, "signup_verify")
                    info(
                        request,
                        _("A verification email has been sent to " +
                          new_user.email +
                          " with a link that must be clicked prior to your account "
                          "being activated. If you do not receive this email please "
                          "check that you entered your address correctly, or your "
                          "spam folder as sometimes the email gets flagged as spam. "
                          "If you entered an incorrect email address, please request "
                          "an account again."))
                return redirect(next_url(request) or "/")
            else:
                info(request, _("Successfully signed up"))
                auth_login(request, new_user)
                return login_redirect(request)

    # remove the key 'response' from errors as the user would have no idea what it means
    form.errors.pop('response', None)
    messages.error(request, form.errors)

    # TODO: User entered data could be retained only if the following
    # render function would work without messing up the css

    # context = {
    #     "form": form,
    #     "title": _("Sign up"),
    # }
    # context.update(extra_context or {})
    # return render(request, template, context)

    # This one keeps the css but not able to retained user entered data.
    return HttpResponseRedirect(request.META['HTTP_REFERER'])
Exemplo n.º 16
0
def signup(request, template="accounts/account_signup.html", extra_context=None):
    """
    Signup form. Overriding mezzanine's view function for signup submit
    """
    form = SignupForm(request, request.POST, request.FILES)
    if request.method == "POST" and form.is_valid():
        try:
            new_user = form.save()
        except ValidationError as e:
            if e.message == "Email already in use.":
                messages.error(request, '<p>An account with this email already exists.  Log in '
                                'or click <a href="' + reverse("mezzanine_password_reset") +
                               '" >here</a> to reset password',
                               extra_tags="html")
            else:
                messages.error(request, e.message)
            return HttpResponseRedirect(request.META['HTTP_REFERER'])
        else:
            if not new_user.is_active:
                if settings.ACCOUNTS_APPROVAL_REQUIRED:
                    send_approve_mail(request, new_user)
                    info(request, _("Thanks for signing up! You'll receive "
                                    "an email when your account is activated."))
                else:
                    send_verification_mail(request, new_user, "signup_verify")
                    info(request, _("A verification email has been sent to " + new_user.email +
                                    " with a link that must be clicked prior to your account "
                                    "being activated. If you do not receive this email please "
                                    "check that you entered your address correctly, or your " 
                                    "spam folder as sometimes the email gets flagged as spam. "
                                    "If you entered an incorrect email address, please request "
                                    "an account again."))
                return redirect(next_url(request) or "/")
            else:
                info(request, _("Successfully signed up"))
                auth_login(request, new_user)
                return login_redirect(request)

    # remove the key 'response' from errors as the user would have no idea what it means
    form.errors.pop('response', None)
    messages.error(request, form.errors)

    # TODO: User entered data could be retained only if the following
    # render function would work without messing up the css

    # context = {
    #     "form": form,
    #     "title": _("Sign up"),
    # }
    # context.update(extra_context or {})
    # return render(request, template, context)

    # This one keeps the css but not able to retained user entered data.
    return HttpResponseRedirect(request.META['HTTP_REFERER'])
Exemplo n.º 17
0
 def process_view(self, request, view_func, view_args, view_kwargs):
     login_type = request.POST.get("mezzanine_login_interface")
     if login_type and not request.user.is_authenticated():
         response = view_func(request, *view_args, **view_kwargs)
         if request.user.is_authenticated():
             if login_type == "admin":
                 next = next_url(request) or request.get_full_path()
                 username = request.user.get_username()
                 if (username == DEFAULT_USERNAME and
                         request.user.check_password(DEFAULT_PASSWORD)):
                     error(request, mark_safe(_(
                           "Your account is using the default password, "
                           "please <a href='%s'>change it</a> immediately.")
                           % reverse("user_change_password",
                                     args=(request.user.id,))))
             else:
                 next = next_url(request) or "/"
             return HttpResponseRedirect(next)
         else:
             return response
     return None
Exemplo n.º 18
0
def login_user(request):
    logout(request)
    username = password = ''
    if request.POST:
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        user = authenticate(username=username, password=password)
        if user is not None and user.is_active:
            login(request, user)
        else:
            error(request, "Usuário e/ou senha inválidos.")
    return redirect(next_url(request) or request.META['HTTP_REFERER'])
Exemplo n.º 19
0
 def process_view(self, request, view_func, view_args, view_kwargs):
     login_type = request.POST.get("mezzanine_login_interface")
     if login_type and not request.user.is_authenticated():
         response = view_func(request, *view_args, **view_kwargs)
         if request.user.is_authenticated():
             if login_type == "admin":
                 next = request.get_full_path()
             else:
                 next = next_url(request) or "/"
             return HttpResponseRedirect(next)
         else:
             return response
     return None
Exemplo n.º 20
0
 def process_view(self, request, view_func, view_args, view_kwargs):
     login_type = request.POST.get("mezzanine_login_interface")
     if login_type and not request.user.is_authenticated():
         response = view_func(request, *view_args, **view_kwargs)
         if request.user.is_authenticated():
             if login_type == "admin":
                 next = request.get_full_path()
             else:
                 next = next_url(request) or "/"
             return HttpResponseRedirect(next)
         else:
             return response
     return None
Exemplo n.º 21
0
Arquivo: views.py Projeto: J0WI/fxoss
def signup(request, template="accounts/account_signup.html"):
    """
    Signup form.
    """
    profile_form = UserRegistrationLeadForm
    form = profile_form(request.POST or None, request.FILES or None)
    if request.method == "POST" and form.is_valid():
        data = form.cleaned_data.copy()

        # ensure user is not a robot
        honeypot = data.pop('superpriority')
        if honeypot:
            raise PermissionDenied

        # save the user
        new_user = form.save()

        # Generate Salesforce Lead
        # Pop non-Salesforce Fields
        for field in ['password1', 'password2']:
            data.pop(field)
        for k, v in SALESFORCE_FIELD_MAPPINGS.items():
            data[v] = data.pop(k)
        data['oid'] = '00DU0000000IrgO'
        # As we're doing the Salesforce POST in the background here,
        # `retURL` is never visited/seen by the user. I believe it
        # is required by Salesforce though, so it should hang around
        # as a placeholder (with a valid URL, just in case).
        data['retURL'] = (request.build_absolute_uri())

        r = requests.post('https://www.salesforce.com/servlet/'
                          'servlet.WebToLead?encoding=UTF-8', data)

        if not new_user.is_active:
            if settings.ACCOUNTS_APPROVAL_REQUIRED:
                send_approve_mail(request, new_user)
                info(request, _("Thanks for signing up! You'll receive "
                                "an email when your account is activated."))
            else:
                send_verification_mail(request, new_user, "signup_verify")
                info(request, _("A verification email has been sent with "
                                "a link for activating your account."))
            return redirect(next_url(request) or "/")
        else:
            info(request, _("Successfully signed up"))
            auth_login(request, new_user)
            return login_redirect(request)
    context = {"form": form, "title": _("Sign up")}
    return render(request, template, context)
Exemplo n.º 22
0
def signup(request, template="accounts/account_signup.html"):
    """
    Signup form.
    """
    profile_form = get_profile_form()
    form = profile_form(request.POST or None, request.FILES or None)
    if request.method == "POST" and form.is_valid():
        new_user = form.save()
        if not new_user.is_active:
            if settings.ACCOUNTS_APPROVAL_REQUIRED:
                send_approve_mail(request, new_user)
                info(request, _("Thanks for signing up! You'll receive "
                                "an email when your account is activated."))
            else:
                send_verification_mail(request, new_user, "signup_verify")
                info(request, _("A verification email has been sent with "
                                "a link for activating your account."))
#            return redirect(request.GET.get("next", "/"))
            return redirect(next_url(request) or "/")
        else:
            info(request, _("Successfully signed up"))
            auth_login(request, new_user)

            customer = request.user.get_profile()
            customer_address = customer.address + ', ' + customer.zip_code
            loc = location_utils.getLocation(customer_address)
            correct_address = location_utils.getAddress(loc[0],loc[1])
            customer.location = loc
            customer.address = correct_address
            customer.save()

            request.session['location'] = (loc[0],loc[1])
            request.session['age'] = True
            request.session['address'] = correct_address
            request.session['map'] = True

            avail_store_ids, avail_store_names, avail_liquor_types, loc, store_locs = new_location_get_ids(request, loc)

#            return login_redirect(request)
            if 'cart loaded' in request.session:
                return redirect('/shop/cart/')
            else:
                return redirect('/shop/')
    context = {"form": form, "title": _("Sign up")}
    return render(request, template, context)
Exemplo n.º 23
0
def old_account_redirect(request, url_suffix):
    """
    Catches and redirects any unmatched account URLs to their
    correct version (account/ to accounts/) as per #934.
    The URL is constructed manually, handling slashes as appropriate.
    """
    if url_suffix is None:
        correct_url = reverse("account_redirect")
    else:
        correct_url = "{account_url}{middle_slash}{suffix}{slash}".format(
                account_url=reverse("account_redirect"),
                middle_slash="/" if not settings.APPEND_SLASH else "",
                suffix=url_suffix,
                slash="/" if settings.APPEND_SLASH else "")
    next = next_url(request)
    if next:
        correct_url += "?next=%s" % next
    return redirect(correct_url)
Exemplo n.º 24
0
def old_account_redirect(request, url_suffix):
    """
    Catches and redirects any unmatched account URLs to their
    correct version (account/ to accounts/) as per #934.
    The URL is constructed manually, handling slashes as appropriate.
    """
    if url_suffix is None:
        correct_url = reverse("account_redirect")
    else:
        correct_url = "{account_url}{middle_slash}{suffix}{slash}".format(
                account_url=reverse("account_redirect"),
                middle_slash="/" if not settings.APPEND_SLASH else "",
                suffix=url_suffix,
                slash="/" if settings.APPEND_SLASH else "")
    next = next_url(request)
    if next:
        correct_url += "?next=%s" % next
    return redirect(correct_url)
Exemplo n.º 25
0
def invoice_resend_email(request, order_id):
    """
    Re-sends the order complete email for the given order and redirects
    to the previous page.
    """
    try:
        order = Order.objects.get_for_user(order_id, request)
    except Order.DoesNotExist:
        raise Http404
    if request.method == "POST":
        checkout.send_order_email(request, order)
        msg = _("The order email for order ID %s has been re-sent") % order_id
        info(request, msg)
    # Determine the URL to return the user to.
    redirect_to = next_url(request)
    if redirect_to is None:
        if request.user.is_staff:
            redirect_to = reverse("admin:shop_order_change", args=[order_id])
        else:
            redirect_to = reverse("shop_order_history")
    return redirect(redirect_to)
Exemplo n.º 26
0
def logout(request):
    """
    Log the user out.
    """
    auth_logout(request)
    info(request, _("Successfully logged out"))

    if 'stores' in request.session:
        del request.session['stores']
    if 'cart loaded' in request.session:
        del request.session['cart loaded']
    if 'location' in request.session:
        del request.session['location']
        del request.session['address']
        del request.session['store ids']
        del request.session['store names']
    if 'age' in request.session:
        del request.session['age']

#    return redirect('/')
    return redirect(next_url(request) or "/")
Exemplo n.º 27
0
def invoice_resend_email(request, order_id):
    """
    Re-sends the order complete email for the given order and redirects
    to the previous page.
    """
    try:
        order = Order.objects.get_for_user(order_id, request)
    except Order.DoesNotExist:
        raise Http404
    if request.method == "POST":
        checkout.send_order_email(request, order)
        msg = _("The order email for order ID %s has been re-sent" % order_id)
        info(request, msg)
    # Determine the URL to return the user to.
    redirect_to = next_url(request)
    if redirect_to is None:
        if request.user.is_staff:
            redirect_to = reverse("admin:shop_order_change", args=[order_id])
        else:
            redirect_to = reverse("shop_order_history")
    return redirect(redirect_to)
Exemplo n.º 28
0
def send_verification_mail_for_password_reset(request, user):
    """
    Sends an email with a verification link to users when
    they request to reset forgotten password to their email. The email is sent to the new email.
    The actual reset of of password will begin after the user clicks the link
    provided in the email.
    The ``verification_type`` arg is both the name of the urlpattern for
    the verification link, as well as the names of the email templates
    to use.
    """
    reset_url = reverse('email_verify_password_reset',
                        kwargs={
                            "uidb36": int_to_base36(user.id),
                            "token": default_token_generator.make_token(user)
                        }) + "?next=" + (next_url(request) or "/")
    context = {"request": request, "user": user, "reset_url": reset_url}
    subject_template_name = "email/reset_password_subject.txt"
    subject = subject_template(subject_template_name, context)
    send_mail_template(subject,
                       "email/reset_password",
                       settings.DEFAULT_FROM_EMAIL,
                       user.email,
                       context=context)
Exemplo n.º 29
0
def set_site(request):
    """
    Put the selected site ID into the session - posted to from
    the "Select site" drop-down in the header of the admin. The
    site ID is then used in favour of the current request's
    domain in ``mezzanine.core.managers.CurrentSiteManager``.
    """
    site_id = int(request.GET["site_id"])
    if not request.user.is_superuser:
        try:
            SitePermission.objects.get(user=request.user, sites=site_id)
        except SitePermission.DoesNotExist:
            raise PermissionDenied
    request.session["site_id"] = site_id
    admin_url = reverse("admin:index")
    next = next_url(request) or admin_url
    # Don't redirect to a change view for an object that won't exist
    # on the selected site - go to its list view instead.
    if next.startswith(admin_url):
        parts = next.split("/")
        if len(parts) > 4 and parts[4].isdigit():
            next = "/".join(parts[:4])
    return redirect(next)
Exemplo n.º 30
0
def set_site(request):
    """
    Put the selected site ID into the session - posted to from
    the "Select site" drop-down in the header of the admin. The
    site ID is then used in favour of the current request's
    domain in ``mezzanine.core.managers.CurrentSiteManager``.
    """
    site_id = int(request.GET["site_id"])
    if not request.user.is_superuser:
        try:
            SitePermission.objects.get(user=request.user, sites=site_id)
        except SitePermission.DoesNotExist:
            raise PermissionDenied
    request.session["site_id"] = site_id
    admin_url = reverse("admin:index")
    next = next_url(request) or admin_url
    # Don't redirect to a change view for an object that won't exist
    # on the selected site - go to its list view instead.
    if next.startswith(admin_url):
        parts = next.split("/")
        if len(parts) > 4 and parts[4].isdigit():
            next = "/".join(parts[:4])
    return redirect(next)
def signup(request, template="accounts/account_signup.html"):
    """
    Signup form.
    """
    profile_form = UserRegistrationLeadForm
    form = profile_form(request.POST or None, request.FILES or None)
    if request.method == "POST" and form.is_valid():
        data = form.cleaned_data.copy()

        # ensure user is not a robot
        honeypot = data.pop('superpriority')
        if honeypot:
            raise PermissionDenied

        # save the user
        new_user = form.save()

        if not new_user.is_active:
            if settings.ACCOUNTS_APPROVAL_REQUIRED:
                send_approve_mail(request, new_user)
                info(
                    request,
                    _("Thanks for signing up! You'll receive "
                      "an email when your account is activated."))
            else:
                send_verification_mail(request, new_user, "signup_verify")
                info(
                    request,
                    _("A verification email has been sent with "
                      "a link for activating your account."))
            return redirect(next_url(request) or "/")
        else:
            info(request, _("Successfully signed up"))
            auth_login(request, new_user)
            return login_redirect(request)
    context = {"form": form, "title": _("Sign up")}
    return render(request, template, context)
Exemplo n.º 32
0
def send_verification_mail_for_password_reset(request, user):
    """
    Sends an email with a verification link to users when
    they request to reset forgotten password to their email. The email is sent to the new email.
    The actual reset of of password will begin after the user clicks the link
    provided in the email.
    The ``verification_type`` arg is both the name of the urlpattern for
    the verification link, as well as the names of the email templates
    to use.
    """
    reset_url = reverse('email_verify_password_reset', kwargs={
        "uidb36": int_to_base36(user.id),
        "token": default_token_generator.make_token(user)
    }) + "?next=" + (next_url(request) or "/")
    context = {
        "request": request,
        "user": user,
        "reset_url": reset_url
    }
    subject_template_name = "email/reset_password_subject.txt"
    subject = subject_template(subject_template_name, context)
    send_mail_template(subject, "email/reset_password",
                       settings.DEFAULT_FROM_EMAIL, user.email,
                       context=context)