Browse Source

login error messages

master
Mohsen Taba 4 months ago
parent
commit
ea851dbbf9
  1. 15
      apps/account/views/user.py
  2. 94
      test_login_errors.py

15
apps/account/views/user.py

@ -394,10 +394,19 @@ class UserLoginView(CreateAPIView):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
data = serializer.data
# u = User.objects.get(id = username=request.data['email'] )
user = authenticate(request, username=request.data['email'], password=data['password'])
# Check if user with this email exists
email = request.data['email']
try:
user_obj = User.objects.get(email=email)
except User.DoesNotExist:
raise ValidationError({"email": "user not exists with this email"})
# If user exists, try to authenticate (check password)
user = authenticate(request, username=email, password=data['password'])
if not user:
raise ValidationError({"email": "Unable to log in with provided credentials."})
raise ValidationError({"password": "password is incorrect"})
user_timezone = serializer.validated_data.pop('timezone', None)
user.last_login = timezone.now()
user.is_active = True

94
test_login_errors.py

@ -0,0 +1,94 @@
#!/usr/bin/env python
"""
Test script to demonstrate the improved login error handling
"""
import os
import django
# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.develop')
django.setup()
from django.test import RequestFactory
from apps.account.views.user import UserLoginView
from rest_framework.exceptions import ValidationError
from django.contrib.auth.models import User as DjangoUser
def test_login_errors():
"""Test the different login error scenarios"""
factory = RequestFactory()
view = UserLoginView()
print("🧪 Testing Login Error Handling")
print("=" * 40)
# Test Case 1: Non-existent email
print("\n1️⃣ Testing non-existent email:")
try:
request = factory.post('/api/account/login/', {
'email': 'nonexistent@example.com',
'password': 'somepassword'
}, content_type='application/json')
view.request = request
response = view.create(request)
print("❌ Should have raised ValidationError")
except ValidationError as e:
print(f"✅ Correctly caught ValidationError: {e.detail}")
except Exception as e:
print(f"❌ Unexpected error: {e}")
# Test Case 2: Wrong password for existing user
print("\n2️⃣ Testing wrong password for existing user:")
try:
# First, let's create a test user if it doesn't exist
test_email = 'test@example.com'
test_password = 'correctpassword'
if not DjangoUser.objects.filter(email=test_email).exists():
DjangoUser.objects.create_user(
username=test_email,
email=test_email,
password=test_password
)
print(f" Created test user: {test_email}")
# Now test wrong password
request = factory.post('/api/account/login/', {
'email': test_email,
'password': 'wrongpassword'
}, content_type='application/json')
view.request = request
response = view.create(request)
print("❌ Should have raised ValidationError")
except ValidationError as e:
print(f"✅ Correctly caught ValidationError: {e.detail}")
except Exception as e:
print(f"❌ Unexpected error: {e}")
# Test Case 3: Correct login (should succeed if user exists)
print("\n3️⃣ Testing correct login:")
try:
request = factory.post('/api/account/login/', {
'email': test_email,
'password': test_password
}, content_type='application/json')
view.request = request
response = view.create(request)
if response.status_code == 201:
print("✅ Login successful (as expected)")
else:
print(f"❌ Login failed with status: {response.status_code}")
except ValidationError as e:
print(f"ℹ️ ValidationError (might be expected): {e.detail}")
except Exception as e:
print(f"❌ Unexpected error: {e}")
print("\n" + "=" * 40)
print("🎯 SUMMARY:")
print("- Non-existent email → 'user not exists with this email'")
print("- Wrong password → 'password is incorrect'")
print("- Correct credentials → Successful login")
if __name__ == "__main__":
test_login_errors()
Loading…
Cancel
Save