How can I prevent an endpoint from directly accessing only redirection can access not the user?

Viewed 23

I am making a website where after signing up, it redirects to OTP endpoint. I don't want that URL to be accessible directly by user. I only want to be accessible when a function like signup redirects towards that endpoint. How can I do that? Here is my code

Forms.py

class OTP_Form(forms.ModelForm):
    class Meta:
        model = OTP
        fields = ("otp", )
    otp = forms.CharField(label="Enter your OTP", required=True,
                          widget=forms.PasswordInput(attrs={'placeholder': 'e.g. 123456'}))

Here is the view for OTP

def phone_verification(request):
    try:
        if request.method == "POST":
            otp = request.session.get('otp')
            username = request.session.get('username')
            first_name = request.session.get('first_name')
            last_name = request.session.get('last_name')
            email = request.session.get('email')
            password = request.session.get('password')
            phone = request.session.get('phone')
            age = request.session.get('age')
            otp_form = OTP_Form(request.POST)
            if otp_form.is_valid():
                get_otp = otp_form.cleaned_data['otp']
                if get_otp == otp:
                    user = User.objects.create_user(username=username, email=email, password=password,
                                                    first_name=first_name, last_name=last_name, last_login=str(datetime.now(pytz.timezone('Asia/Karachi'))))
                    customer = Customer.objects.create(
                        user=user, phone=phone, age=age)
                    user.save()
                    customer.save()
                    otp_entry = OTP.objects.create(phone=phone, otp=otp)
                    otp_entry.save()
                    messages.success(request, 'Your account has been creaated')
                    return redirect('login')
                else:
                    messages.error(request, 'Incorrect OTP')
                    return redirect('otp')
            else:
                messages.error(request, 'Please enter the OTP again')
                return redirect('otp')
        else:
            otp_form = OTP_Form()
            return render(request, 'otp.html', {'otp_form': otp_form})
    except:
        return ValidationError("An error occured while verifyig otp")


1 Answers

Your authenticated users don't need this view so write this to view:

def phone_verification(request):
     if request.user.is_authenticated:
         redirect('home')
     else:
         #your staffs
         ...
Related