|
| 1 | +"""Nest API key GraphQL Mutations.""" |
| 2 | + |
| 3 | +import logging |
| 4 | +from datetime import datetime |
| 5 | +from uuid import UUID |
| 6 | + |
| 7 | +import strawberry |
| 8 | +from django.db.utils import IntegrityError |
| 9 | +from django.utils import timezone |
| 10 | +from strawberry.types import Info |
| 11 | + |
| 12 | +from apps.nest.graphql.nodes.api_key import ApiKeyNode |
| 13 | +from apps.nest.graphql.permissions import IsAuthenticated |
| 14 | +from apps.nest.models.api_key import MAX_ACTIVE_KEYS, MAX_WORD_LENGTH, ApiKey |
| 15 | + |
| 16 | +logger = logging.getLogger(__name__) |
| 17 | + |
| 18 | + |
| 19 | +@strawberry.type |
| 20 | +class RevokeApiKeyResult: |
| 21 | + """Payload for API key revocation result.""" |
| 22 | + |
| 23 | + ok: bool |
| 24 | + code: str | None = None |
| 25 | + message: str | None = None |
| 26 | + |
| 27 | + |
| 28 | +@strawberry.type |
| 29 | +class CreateApiKeyResult: |
| 30 | + """Result of creating an API key.""" |
| 31 | + |
| 32 | + ok: bool |
| 33 | + api_key: ApiKeyNode | None = None |
| 34 | + raw_key: str | None = None |
| 35 | + code: str | None = None |
| 36 | + message: str | None = None |
| 37 | + |
| 38 | + |
| 39 | +@strawberry.type |
| 40 | +class ApiKeyMutations: |
| 41 | + """GraphQL mutation class for API keys.""" |
| 42 | + |
| 43 | + @strawberry.mutation(permission_classes=[IsAuthenticated]) |
| 44 | + def create_api_key(self, info: Info, name: str, expires_at: datetime) -> CreateApiKeyResult: |
| 45 | + """Create a new API key for the authenticated user.""" |
| 46 | + if not name or not name.strip(): |
| 47 | + return CreateApiKeyResult(ok=False, code="INVALID_NAME", message="Name is required") |
| 48 | + |
| 49 | + if len(name.strip()) > MAX_WORD_LENGTH: |
| 50 | + return CreateApiKeyResult(ok=False, code="INVALID_NAME", message="Name too long") |
| 51 | + |
| 52 | + if expires_at <= timezone.now(): |
| 53 | + return CreateApiKeyResult( |
| 54 | + ok=False, code="INVALID_DATE", message="Expiry date must be in future" |
| 55 | + ) |
| 56 | + |
| 57 | + try: |
| 58 | + if not ( |
| 59 | + result := ApiKey.create( |
| 60 | + expires_at=expires_at, |
| 61 | + name=name, |
| 62 | + user=info.context.request.user, |
| 63 | + ) |
| 64 | + ): |
| 65 | + return CreateApiKeyResult( |
| 66 | + ok=False, |
| 67 | + code="LIMIT_REACHED", |
| 68 | + message=f"You can have at most {MAX_ACTIVE_KEYS} active API keys.", |
| 69 | + ) |
| 70 | + |
| 71 | + instance, raw_key = result |
| 72 | + return CreateApiKeyResult( |
| 73 | + ok=True, |
| 74 | + api_key=instance, |
| 75 | + raw_key=raw_key, |
| 76 | + code="SUCCESS", |
| 77 | + message="API key created successfully.", |
| 78 | + ) |
| 79 | + except IntegrityError as err: |
| 80 | + logger.warning("Error creating API key: %s", err) |
| 81 | + return CreateApiKeyResult( |
| 82 | + ok=False, |
| 83 | + code="ERROR", |
| 84 | + message="Something went wrong.", |
| 85 | + ) |
| 86 | + |
| 87 | + @strawberry.mutation(permission_classes=[IsAuthenticated]) |
| 88 | + def revoke_api_key(self, info: Info, uuid: UUID) -> RevokeApiKeyResult: |
| 89 | + """Revoke an API key for the authenticated user.""" |
| 90 | + try: |
| 91 | + api_key = ApiKey.objects.get( |
| 92 | + uuid=uuid, |
| 93 | + user=info.context.request.user, |
| 94 | + ) |
| 95 | + api_key.is_revoked = True |
| 96 | + api_key.save(update_fields=("is_revoked", "updated_at")) |
| 97 | + except ApiKey.DoesNotExist: |
| 98 | + logger.warning("API Key does not exist") |
| 99 | + return RevokeApiKeyResult( |
| 100 | + ok=False, |
| 101 | + code="NOT_FOUND", |
| 102 | + message="API key not found.", |
| 103 | + ) |
| 104 | + else: |
| 105 | + return RevokeApiKeyResult( |
| 106 | + ok=True, code="SUCCESS", message="API key revoked successfully." |
| 107 | + ) |
0 commit comments