|
1 |
| -from django.conf import settings |
2 | 1 | from rest_framework.authentication import BaseAuthentication
|
3 |
| -from rest_framework.exceptions import AuthenticationFailed |
4 |
| -from django.contrib.auth import get_user_model, authenticate |
5 |
| -from appwrite.services.account import Account |
6 | 2 |
|
7 |
| -from django_appwrite.utilities import initialize_appwrite_client, get_appwrite_settings, log_error |
8 |
| - |
9 |
| -User = get_user_model() |
| 3 | +from django_appwrite.utilities import get_appwrite_settings, extract_token, \ |
| 4 | + get_appwrite_user_info, check_verification, get_or_create_django_user |
10 | 5 |
|
11 | 6 |
|
12 | 7 | class AppwriteAuthentication(BaseAuthentication):
|
13 | 8 | def authenticate(self, request):
|
14 |
| - # Extract the Appwrite token from the request headers |
15 |
| - auth_header = request.headers.get('Authorization') |
16 |
| - if not auth_header or not auth_header.startswith('Bearer '): |
17 |
| - return None # No authentication attempt |
18 |
| - |
19 |
| - token = auth_header.split('Bearer ')[1] |
20 |
| - |
21 |
| - # Verify the token with Appwrite |
22 |
| - client = initialize_appwrite_client() |
23 |
| - client.set_jwt(token) |
24 |
| - |
25 |
| - try: |
26 |
| - user_info = Account(client).get() |
27 |
| - except Exception as e: |
28 |
| - if settings.DEBUG: |
29 |
| - log_error(e) |
30 |
| - raise AuthenticationFailed('Invalid Appwrite token or other Appwrite authentication issue.') |
31 |
| - |
32 | 9 | appwrite_settings = get_appwrite_settings()
|
| 10 | + token = extract_token(request, appwrite_settings) |
33 | 11 |
|
34 |
| - email = appwrite_settings['prefix_email'] + user_info['email'] |
35 |
| - password = settings.SECRET_KEY + user_info['$id'] |
36 |
| - |
37 |
| - username_field = getattr(User, 'USERNAME_FIELD', 'username') |
38 |
| - |
39 |
| - # Get or create a corresponding Django user |
40 |
| - django_user = User.objects.filter(**{username_field: email}).first() |
41 |
| - if not django_user: |
42 |
| - User.objects.create_user(**{username_field: email, 'password': password}) |
| 12 | + # Verify the token with Appwrite |
| 13 | + user_info = get_appwrite_user_info(token) |
43 | 14 |
|
44 |
| - # Ensure the user can be authenticated with Django's system |
45 |
| - auth_user = authenticate(request, **{username_field: email, 'password': password}) |
46 |
| - if not auth_user: |
47 |
| - raise AuthenticationFailed('The user could not be authenticated with Django.') |
| 15 | + # Check email and phone verification |
| 16 | + check_verification(user_info, appwrite_settings) |
48 | 17 |
|
49 |
| - return auth_user, token |
| 18 | + # Authenticate or create Django user |
| 19 | + return get_or_create_django_user(request, user_info, appwrite_settings), token |
0 commit comments