Exemplo n.º 1
0
def reverse(viewname, qualified=False, scheme=None, request=None, **kwargs):
    """
    Reverses the URL of the given view name with other optional arguments to
    django.core.urlresolvers.reverse(). If qualified is True, the URL will be
    fully qualified. The URL scheme may be specified with the scheme argument,
    defaulting to "http". By default, the hostname will come from the current
    django.contrib.sites.models.Site object. Alternatively, the scheme and
    hostname may be specified by a django.http.request.HttpRequest object
    passed in the request argument.
    
    If qualfied is True, no request is specified and the django.contrib.sites
    app is not installed and configured, an exception will be raised.
    
    If qualified is True and both a scheme and request are specified, the
    passed scheme will take precedence over the request's scheme.
    
    """
    url = urlresolvers.reverse(viewname, **kwargs)
    if qualified:
        return "{scheme:s}://{host:s}{url:s}".format(
            scheme=(
                scheme
                    if scheme is not None
                    else "http"
                        if request is None
                        else "https"
                            if request.is_secure()
                            else "http"),
            host=(
                request.get_host()
                    if request is not None
                    else Site.objects.get_current().domain),
            url=url)
    return url
Exemplo n.º 2
0
def checkout_address_create_view(request):
    form = AddressForm(request.POST or None)
    context = {
        "form": form
    }
    next_ = request.GET.get('next')
    next_post = request.POST.get('next')
    redirect_path = next_ or next_post or None
    if form.is_valid():
        print(request.POST)
        instance = form.save(commit=False)
        billing_profile, billing_profile_created = BIllingProfile.objects.new_or_get(request)
        if billing_profile is not None:
            address_type = request.POST.get('address_type', 'shipping')
            instance.billing_profile = billing_profile
            instance.address_type = address_type
            instance.save()
            request.session[address_type + "_address_id"] = instance.id
            print(address_type + "_address_id")

        else:
            print("error here address didnot dsave")
            return redirect("cart:checkout")
        if is_safe_url(redirect_path, request.get_host()):
            return redirect(redirect_path)
        else:
            return redirect("cart:checkout")
    return redirect("cart:checkout")
Exemplo n.º 3
0
def register(request):
    if request.method == "POST":
        form = SignUpForm(request.POST)
        if form.is_valid():
            new_user_name = form.cleaned_data['username']
            new_user_password = form.cleaned_data['password1']
            new_user_email = form.cleaned_data['email']
            new_user = User.objects.create_user(username=new_user_name,
                                                email=new_user_email,
                                                password=new_user_password)
            new_user.is_active = False
            new_user.save()
            new_user_token = activation_user().make_token(new_user)
            # kwargs={'pk':new_user.id, 'token':new_user_token})
            host = request.get_host()
            # var_url = 'http://'+ host + url

            send_mail("Activate YOur Account",
                      loader.render_to_string('user_activate.html',
                                              {'pk': new_user.id,
                                               'token': new_user_token,
                                               'domain': host,
                                               'user': new_user_name}), '*****@*****.**', ['*****@*****.**', new_user_email])
            return HttpResponseRedirect('/login/')
            # else:
            #     x = [v[0] for k, v in form.errors.items()]
            #     return HttpResponse(x)
    else:
        form = SignUpForm()
    return render(request, 'registration.html', {'form': form})
Exemplo n.º 4
0
def simplify_redirect(redirect, source, request=None):
    """
    Simplifies a redirect URL with respect to a source URL and returns the
    redirect URL. When both URLs' scheme and host match, the scheme and host
    are stripped from the redirect URL. When a request is specified, its
    scheme and host are also used to simplify the redirect URL.
    
    """
    redirect = urlparse.urlparse(encoding.force_str(redirect))
    source = urlparse.urlparse(encoding.force_str(source))
    empty = ("", "",)
    request = (
        (("https", request.get_host(),)
            if request.is_secure()
            else ("http", request.get_host(),))
            if request is not None
            else empty)
    if (redirect[:2] != empty and (
            redirect[:2] == source[:2] or
            (redirect[:2] == request and source[:2] == empty))):
        redirect = empty + redirect[2:]
    return urlparse.urlunparse(redirect)
Exemplo n.º 5
0
def request_views(request):
    # print(dir(request))
    # print(request.META)

    scheme = request.scheme
    body = request.body
    path = request.path
    host = request.get_host()
    method = request.method
    get = request.GET
    post = request.POST
    cookies = request.COOKIES

    return render(request, '01-request.html', locals())
Exemplo n.º 6
0
def login_email_submit(request, redirect_field_name=REDIRECT_FIELD_NAME):
    """
    index page
    :param request:
    :return:
    """

    #Displays the login form and handles the login action.
    redirect_to = request.REQUEST.get(redirect_field_name, '')
    resp = {
        'error': {},
        'success': {
            'pass': False,
            'message': ''
        },
        'redirect_to': redirect_to,
        'csrfCookie': None
    }
    override_msg = None
    if request.method == "POST" and request.is_ajax():

        data = json.loads(str(request.body, 'utf-8'))
        form = AuthenticationForm(request, data)
        #import ipdb; ipdb.set_trace()
        try:
            if form.is_valid():
                # Ensure the user-originating redirection url is safe.
                if not is_safe_url(url=redirect_to, host=request.get_host()):
                    resp['redirect_to'] = resolve_url(
                        settings.LOGIN_REDIRECT_URL)

                # Okay, security check complete. Log the user in.
                auth_login(request, form.get_user())
                user = form.get_user()
                if user is not None:
                    # the password verified for the user
                    if user.is_active:
                        resp['success']['pass'] = True
                        resp['success']['message'] = "Welcome."
                        # remove once cookie catch is done.
                        resp['csrfToken'] = request.META.get('CSRF_COOKIE')

        except Exception as e:
            override_msg = "An error occurred. Please contact the system admin."
        resp['error'] = form.get_formatted_errors(override_msg=override_msg)

    response = HttpResponse(json.dumps(resp))
    response['Content-Type'] = 'application/json'
    return response
Exemplo n.º 7
0
def payment_process(request):
    host = request.get_host()
    paypal_dict = {
        'business': "*****@*****.**",
        'amount': '1',
        'item_name': 'Item_Name_xyz',
        'invoice': ' Test Payment Invoice',
        'currency_code': 'USD',
        'notify_url': 'http://{}{}'.format(host, reverse('paypal-ipn')),
        'return_url': 'http://{}{}'.format(host, reverse('payment_done')),
        'cancel_return': 'http://{}{}'.format(host,
                                              reverse('payment_canceled')),
    }
    form = PayPalPaymentsForm(initial=paypal_dict)
    return render(request, 'payment_process.html', {'form': form})
Exemplo n.º 8
0
def login_email_submit(request, redirect_field_name=REDIRECT_FIELD_NAME):
    """
    index page
    :param request:
    :return:
    """

    #Displays the login form and handles the login action.
    redirect_to = request.REQUEST.get(redirect_field_name, '')
    resp = {
        'error': {},
        'success': {'pass': False, 'message': ''},
        'redirect_to': redirect_to,
        'csrfCookie': None
    }
    override_msg = None
    if request.method == "POST" and request.is_ajax():

        data = json.loads(str(request.body, 'utf-8'))
        form = AuthenticationForm(request, data)
        #import ipdb; ipdb.set_trace()
        try:
            if form.is_valid():
                # Ensure the user-originating redirection url is safe.
                if not is_safe_url(url=redirect_to, host=request.get_host()):
                    resp['redirect_to'] = resolve_url(settings.LOGIN_REDIRECT_URL)

                # Okay, security check complete. Log the user in.
                auth_login(request, form.get_user())
                user = form.get_user()
                if user is not None:
                    # the password verified for the user
                    if user.is_active:
                        resp['success']['pass'] = True
                        resp['success']['message'] = "Welcome."
                        # remove once cookie catch is done.
                        resp['csrfToken'] = request.META.get('CSRF_COOKIE')

        except Exception as e:
            override_msg = "An error occurred. Please contact the system admin."
        resp['error'] = form.get_formatted_errors(override_msg=override_msg)

    response = HttpResponse(json.dumps(resp))
    response['Content-Type'] = 'application/json'
    return response
Exemplo n.º 9
0
def guest_login_page(request):
    form = GuestForm(request.POST or None)
    context = {
        "form": form
    }
    next_ = request.GET.get('next')
    next_post = request.POST.get('next')
    redirect_path = next_ or next_post or None
    if form.is_valid():
        email = form.cleaned_data.get("email")
        new_guest_email = GuestEmail.objects.create(email=email)
        request.session['guest_email_id'] = new_guest_email.id
        if is_safe_url(redirect_path, request.get_host()):
            return redirect(redirect_path)
        else:
            return redirect("/register/")

    return redirect("/register/")
Exemplo n.º 10
0
def sign_up(request):
    """
    Sign up
    """
    logger.info("sign_up")
    User = get_user_model()
    if request.method == "POST":
        signup_form = SignUpForm(request.POST)
        if signup_form.is_valid():
            email = signup_form.cleaned_data.get("email")
            if User.objects.filter(email__iexact=email).count() == 0:
                # signup way 1
                new_user = signup_form.save(commit=False)
                new_user.set_password(signup_form.cleaned_data["password"])
                new_user.is_active = False
                new_user.save()

                current_site = request.get_host()
                mail_subject = "Welcome to Django Blog!"

                message = render_to_string(
                    "account/activation.html",
                    {
                        "user": new_user,
                        "domain": current_site,
                        "uid": urlsafe_base64_encode(force_bytes(new_user.id)),
                        "token": account_activation_token.make_token(new_user),
                    },
                )

                try:
                    email = EmailMessage(mail_subject,
                                         message,
                                         to=[new_user.email])
                    email.send()
                except Exception:
                    logger.error("Email error")
                return HttpResponse(
                    "Verification link has been sent to linked email addresses"
                )
    else:
        signup_form = SignUpForm()
    return render(request, "account/signup.html", {"signup_form": signup_form})
Exemplo n.º 11
0
def checkout_address_reuse_view(request):
    if request.user.is_authenticated:
        context = {}
        next_ = request.GET.get('next')
        next_post = request.POST.get('next')
        redirect_path = next_ or next_post or None
        if request.method == "POST":
            print(request.POST)
            shipping_address = request.POST.get('shipping_address', None)
            address_type = request.POST.get('address_type', 'shipping')
            billing_profile, billing_profile_created = BIllingProfile.objects.new_or_get(request)
            if shipping_address is not None:
                qs = Address.objects.filter(billing_profile=billing_profile, id=shipping_address)
                if qs.exist():
                    request.session[address_type + "_address_id"] = shipping_address

            if is_safe_url(redirect_path, request.get_host()):
                return redirect(redirect_path)
            else:
                return redirect("cart:checkout")
    return redirect("cart:checkout")
Exemplo n.º 12
0
 def form_valid(self, form):
     request = self.request
     next_ = request.GET.get('next')
     next_post = request.POST.get('next')
     redirect_path = next_ or next_post or None
     email = form.cleaned_data.get("email")
     password = form.cleaned_data.get("password")
     user = authenticate(request, username=email, password=password)
     print(user)
     if user is not None:
         login(request, user)
         user_logged_in.send(user.__class__, instance=user ,request=request)
         try:
             del request.session['guest_email_id']
         except:
             pass
         if is_safe_url(redirect_path, request.get_host()):
             return redirect(redirect_path)
         else:
             return redirect("/")
     return super(LoginView, self).form_valid(form)
Exemplo n.º 13
0
def verify(request):
    email = request.GET['email']
    token = request.GET['token']
    if VerifyToken.objects.filter(email=email, tokens=token).exists():
        v = get_object_or_404(VerifyToken, email=email, tokens=token)
        us = get_object_or_404(User, email=email)
        if v.is_used == True:
            messages.warning(
                request,
                "Your Account has been verified, Kindly proceed and Login to your account"
            )
            return redirect('/login')
        else:
            u = VerifyToken.objects.filter(email=email, tokens=token)
            u.update(is_used=True)
            usp = User.objects.filter(email=v.email)
            usp.update(is_active=True)

            url = request.get_host()

            ### Sending Verification Email #####
            subject, from_email, to = 'Tradify Verification', EMAIL_FROM, email
            html_content = render_to_string('email/verify_done.html', {
                'url': url,
                'fullname': us.fullname
            })
            text_content = strip_tags(html_content)
            msg = EmailMultiAlternatives(subject, text_content, from_email,
                                         [to])
            msg.attach_alternative(html_content, "text/html")
            msg.send()
            messages.success(
                request,
                "Account Verified. Kindly proceed and Login to your account")
            return redirect('/login')
    else:
        messages.error(
            request,
            "Verification Error. kindly click on resend verification link")
        return redirect('/login')
Exemplo n.º 14
0
def resolve(url, scheme=None, request=None, **kwargs):
    """
    Resolves the given URL by passing its path and other optional arguments to
    django.core.urlresolvers.resolve(). For fully qualified URLs, the URL
    scheme and hostname will be checked, and a ValueError will be raised upon
    mismatch. The URL scheme may be specified with the scheme argument,
    defaulting to 'http'. By default, the hostname will come from the current
    django.contrib.sites.models.Site object. Alternatively, the scheme and
    hostname may be specified by a django.http.request.HttpRequest object
    passed in the request argument.
    
    For fully qualified URLs, if no request is specified and the
    django.contrib.sites app is not installed and configured, an exception
    will be raised.
    
    For fully qualified URLs, if both a scheme and a request are specified,
    the passed scheme will take precedence over the request's scheme.
    
    """
    parts = urlparse.urlparse(url)
    if ((
        parts.scheme and
        parts.scheme != (scheme
            if scheme is not None
            else "http"
                if request is None
                else "https"
                    if request.is_secure()
                    else "http")) or (
        parts.netloc and
        parts.netloc != request.get_host()
            if request is not None
            else Site.objects.get_current().domain)):
        raise ValueError(
            "The fully qualified URL's scheme or hostname are invalid for "
            "this host.")
    return urlresolvers.resolve(parts.path)
Exemplo n.º 15
0
def send_account_activation_email(request, user):
    text_content = 'Account Activation Email'
    subject = 'Email Activation'
    template_name = "emails/account/activation.html"
    from_email = settings.DEFAULT_FROM_EMAIL
    recipients = [user.email]
    kwargs = {
        "uidb64": urlsafe_base64_encode(force_bytes(user.pk)).decode(),
        "token": default_token_generator.make_token(user)
    }
    activation_url = reverse("activate_user_account", kwargs=kwargs)

    activate_url = "{0}://{1}{2}".format(request.scheme, request.get_host(),
                                         activation_url)

    context = {'user': user, 'activate_url': activate_url}

    html_content = render_to_string(template_name, context)
    email = EmailMultiAlternatives(subject, text_content, from_email,
                                   recipients)
    email.attach_alternative(html_content, "text/html")
    email.send()

    return HttpResponse(activate_url)
Exemplo n.º 16
0
def signup(request):
    N = 100
    tokens = ''.join(
        secrets.choice(string.ascii_lowercase + string.digits)
        for i in range(N))
    url = request.get_host()
    if request.user.is_authenticated:
        return redirect('/dashboard')
    elif request.method == "POST":
        fullname = request.POST['fullname']
        email = request.POST['email']
        mobile = request.POST['mobile']
        country = request.POST['country']
        password1 = request.POST['password1']
        password2 = request.POST['password2']

        if country == "":
            messages.error(request, "Please select your country of residence")
            return render(request, 'signup.html', {
                'fullname': fullname,
                'email': email,
                'mobile': mobile
            })

        elif User.objects.filter(email=email).exists() or User.objects.filter(
                mobile=mobile).exists():
            messages.error(request, "Mobile Number/Email Used")
            return render(request, 'signup.html', {
                'fullname': fullname,
                'email': email,
                'mobile': mobile
            })

        elif password1 == password2:
            user = User.objects.create_user(fullname=fullname,
                                            email=email,
                                            mobile=mobile,
                                            password=password1,
                                            country=country,
                                            is_user=True,
                                            is_active=False)
            user.save()
            tken = VerifyToken(email=email, tokens=tokens, user=user)
            tken.save()
            verify_link = f'http://{url}/verify?email={email}&token={tokens}'

            ### Sending Verification Email #####
            subject, from_email, to = 'Tradify Verification', EMAIL_FROM, email
            html_content = render_to_string('email/verify.html', {
                'verify_link': verify_link,
                'fullname': fullname
            })
            text_content = strip_tags(html_content)
            msg = EmailMultiAlternatives(subject, text_content, from_email,
                                         [to])
            msg.attach_alternative(html_content, "text/html")
            msg.send()
            messages.success(
                request,
                "Registration Successful. Check your Email for verification Link"
            )
            return redirect('/signup')
        else:
            messages.error(request, "Password Missmatch")
            return render(request, 'signup.html', {
                'fullname': fullname,
                'email': email,
                'mobile': mobile
            })
    else:
        return render(request, 'signup.html')