diff --git a/django_project/minisass/management/commands/generate_token.py b/django_project/minisass/management/commands/generate_token.py new file mode 100644 index 000000000..7182e8618 --- /dev/null +++ b/django_project/minisass/management/commands/generate_token.py @@ -0,0 +1,27 @@ +from django.core.management.base import BaseCommand +from django.contrib.auth.models import User +from rest_framework_simplejwt.tokens import AccessToken +from datetime import timedelta + +class Command(BaseCommand): + help = 'Manually generate a special token for a given user email' + + def add_arguments(self, parser): + parser.add_argument('email', type=str, help="The user's email for whom the token should be generated") + + def handle(self, *args, **kwargs): + email = kwargs['email'] + + try: + user = User.objects.get(email=email) + except User.DoesNotExist: + self.stdout.write(self.style.ERROR(f"User with email {email} not found")) + return + + # Generate token for the user + token = AccessToken.for_user(user) + # Set token expiry to 100 years + token.set_exp(lifetime=timedelta(days=365 * 100)) + + # Output the token in the console + self.stdout.write(self.style.SUCCESS(f"Generated token for {email}: {str(token)}")) diff --git a/django_project/minisass_authentication/tests/test_views.py b/django_project/minisass_authentication/tests/test_views.py index 1a9792b35..72f34ee45 100644 --- a/django_project/minisass_authentication/tests/test_views.py +++ b/django_project/minisass_authentication/tests/test_views.py @@ -14,51 +14,6 @@ from rest_framework import status -class GenerateSpecialTokenTest(APITestCase): - def setUp(self): - # Create a test admin user - self.admin_user = User.objects.create_user( - username='adminuser', - email='admin@example.com', - password='adminpassword', - is_staff=True - ) - - # Create a test regular user - self.regular_user = User.objects.create_user( - username='regularuser', - email='regular@example.com', - password='regularpassword' - ) - - def test_generate_token_success_for_admin(self): - # Use the admin user's email to generate a token - url = reverse('generate_special_token', args=[self.admin_user.email]) - response = self.client.post(url) - - # Check that the response is successful - self.assertEqual(response.status_code, status.HTTP_200_OK) - self.assertIn('token', response.json()) - - def test_generate_token_forbidden_for_regular_user(self): - # Use the regular user's email to generate a token - url = reverse('generate_special_token', args=[self.regular_user.email]) - response = self.client.post(url) - - # Check that the response indicates the user is not an admin - self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) - self.assertEqual(response.json(), {'error': 'User is not an admin'}) - - def test_generate_token_user_not_found(self): - # Use a non-existent email - url = reverse('generate_special_token', args=['nonexistent@example.com']) - response = self.client.post(url) - - # Check that the response indicates the user was not found - self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) - self.assertEqual(response.json(), {'error': 'User not found'}) - - class PasswordResetTest(APITestCase): def setUp(self): diff --git a/django_project/minisass_authentication/urls.py b/django_project/minisass_authentication/urls.py index 4a4f0129f..7ed1ddbd1 100644 --- a/django_project/minisass_authentication/urls.py +++ b/django_project/minisass_authentication/urls.py @@ -20,13 +20,11 @@ UploadCertificate, UpdatePassword, check_is_expert, - retrieve_email_by_username, - generate_special_token + retrieve_email_by_username ) urlpatterns = [ - path('api/generate-special-token/', generate_special_token, name='generate_special_token'), path('api/request-reset/', request_password_reset, name='request_password_reset'), path('api/verify-password-reset///', verify_password_reset, name='verify_password_reset'), path('api/update-password-reset///', update_password, name='update_password_reset'), diff --git a/django_project/minisass_authentication/views.py b/django_project/minisass_authentication/views.py index c8b4f46f1..745bcf053 100644 --- a/django_project/minisass_authentication/views.py +++ b/django_project/minisass_authentication/views.py @@ -49,17 +49,6 @@ # Get an instance of a logger logger = logging.getLogger(__name__) -def generate_special_token(request, email): - try: - user = User.objects.get(email=email) - except User.DoesNotExist: - return JsonResponse({'error': 'User not found'}, status=404) - - token = AccessToken.for_user(user) - # Set a very long expiration time, e.g., 100 years - token.set_exp(lifetime=timedelta(days=365 * 100)) - - return JsonResponse({'token': str(token)}, status=200) @api_view(['POST']) @permission_classes([IsAuthenticated]) diff --git a/django_project/monitor/tests/test_sites.py b/django_project/monitor/tests/test_sites.py index 00286030e..1c5b652c9 100644 --- a/django_project/monitor/tests/test_sites.py +++ b/django_project/monitor/tests/test_sites.py @@ -86,15 +86,15 @@ def setUp(self): elec_cond="2.50", elec_cond_unit="mS/m" ) - self.token = self.generate_token_for_user(self.user_token.email) + self.token = self.generate_token_for_user(self.user_token) self.client = APIClient() self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + self.token) - def generate_token_for_user(self, email): - url = reverse('generate_special_token', args=[email]) - response = self.client.post(url) - self.assertEqual(response.status_code, status.HTTP_200_OK) - return response.json().get('token') + def generate_token_for_user(self, user): + token = AccessToken.for_user(user) + token.set_exp(lifetime=timedelta(days=365 * 100)) + + return str(token) def test_get_all_sites_with_observations(self):