I’m working on a project, in the back-end we are using Django with Rest and for front we are using WordPress and we want to send otp for user and if the OTP code from user is valid then login the user and save the CSRF-token and so on ..
but here is my problem I didn’t wanted to save the opt in a table and in chatgpt it suggested that I can save it in session or memory cash, I wanted to try the session way but I encounter a problem : after calling the /send_otp/ and getting the otp I need to call the /login/ and check if the otp is a mach, but in login it returns the otp from session None and I can access the session I saved in the send_otp
this is the two functions send_otp and login :
class SendOTPView(APIView):
def post(self, request):
serializer = OTPSerializer(data=request.data)
if serializer.is_valid():
phone_number = serializer.validated_data["phone"]
otp_code = randint(100000, 999999)
request.session['otp_code'] = otp_code
print("otp in sendOTP",request.session.get("otp_code"))
otp_send(phone_number, otp_code)
return Response(
{"detail": "OTP sent successfully"}, status=status.HTTP_200_OK
)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class UserLoginView(APIView):
def post(self, request):
serializer = UserLoginSerializer(data=request.data)
if serializer.is_valid():
stored_otp = request.session.get("otp_code")
print(stored_otp)
user_entered_otp = serializer.validated_data["otp"]
phone_number = serializer.validated_data["phone"]
try:
user_from_db = User.objects.get(username=phone_number)
except:
return Response({"detail": "user not found"}, status=status.HTTP_404_NOT_FOUND)
password = generate_password(phone_number)
if str(user_entered_otp) == str(stored_otp):
del request.session['otp_code']
user = authenticate(username=phone_number, password=password)
if user:
return Response({"detail": 'logged in successfully '}, status=status.HTTP_200_OK)
else:
return Response(
{"detail": "Invalid phone or otp"},
status=status.HTTP_400_BAD_REQUEST,
)
else :
return Response(
{
"detail": "Wrong otp code",
},
status=status.HTTP_400_BAD_REQUEST,)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
and here is the html & js files (it’s a simple one for test only):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="csrf-token" content="{{ csrf_token }}">
<title>OTP Verification</title>
</head>
<body>
<div id="phone-form">
<h2>Send OTP</h2>
<input type="text" id="phone" placeholder="Enter your phone number">
<button onclick="sendOTP()">Send OTP</button>
</div>
<div id="otp-form" style="display: none;">
<h2>Verify OTP</h2>
<input type="hidden" id="otp-phone">
<input type="text" id="otp" placeholder="Enter OTP">
<button onclick="verifyOTP()">Verify OTP</button>
</div>
<script>
// Base URL for the API
const baseURL = 'http://127.0.0.1:8000/auth';
// Function to get CSRF token from the meta tag
function getCSRFToken() {
return document.querySelector('meta[name="csrf-token"]').getAttribute('content');
}
// Function to send OTP
function sendOTP() {
const phone = document.getElementById('phone').value;
fetch(`${baseURL}/send_otp/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': getCSRFToken()
},
credentials: 'include', // include cookies with the request
body: JSON.stringify({ phone })
})
.then(response => {
if (response.ok) {
alert('OTP sent successfully');
document.getElementById('phone-form').style.display = 'none';
document.getElementById('otp-form').style.display = 'block';
document.getElementById('otp-phone').value = phone; // pre-fill phone number in the OTP form
} else {
alert('Failed to send OTP');
}
})
.catch(error => console.error('Error:', error));
}
// Function to verify OTP and login
function verifyOTP() {
const phone = document.getElementById('otp-phone').value;
const otp = document.getElementById('otp').value;
fetch(`${baseURL}/login/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': getCSRFToken()
},
credentials: 'include', // include cookies with the request
body: JSON.stringify({ phone, otp })
})
.then(response => {
if (response.ok) {
alert('Login successful');
window.location.href = '/'; // redirect to the dashboard or desired page after login
} else {
alert('Failed to verify OTP');
}
})
.catch(error => console.error('Error:', error));
}
</script>
</body>
</html>
// Base URL for the API
const baseURL = 'http://127.0.0.1:8000/auth';
// Function to get CSRF token from the cookie
function getCSRFToken() {
const cookieValue = document.cookie
.split('; ')
.find(row => row.startsWith('csrftoken='))
.split('=')[1];
return cookieValue;
}
// Function to send OTP
function sendOTP() {
const phone = document.getElementById('phone').value;
fetch(`http://127.0.0.1:8000/auth/send_otp/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': getCSRFToken() // Include CSRF token in the request headers
},
credentials: 'include', // include cookies with the request
body: JSON.stringify({ phone })
})
.then(response => {
if (response.ok) {
alert('OTP sent successfully');
document.getElementById('phone-form').style.display = 'none';
document.getElementById('otp-form').style.display = 'block';
document.getElementById('otp-phone').value = phone; // pre-fill phone number in the OTP form
} else {
alert('Failed to send OTP');
}
})
.catch(error => console.error('Error:', error));
}
// Function to verify OTP and login
function verifyOTP() {
const phone = document.getElementById('otp-phone').value;
const otp = document.getElementById('otp').value;
fetch(`http://127.0.0.1:8000/auth/login/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': getCSRFToken() // Include CSRF token in the request headers
},
credentials: 'include', // include cookies with the request
body: JSON.stringify({ phone, otp })
})
.then(response => {
if (response.ok) {
alert('Login successful');
window.location.href = '/'; // redirect to the dashboard or desired page after login
} else {
alert('Failed to verify OTP');
}
})
.catch(error => console.error('Error:', error));
}
and Idk why but if i do it in postman I get the result and it validates the code (first calling the send_otp in postman then calling login) but when I try with html and js I can’t