commit b966bfd1901a8047652b8126555878a67bf11cc0 Author: saani Date: Wed Nov 12 11:51:27 2025 +0000 Add initial Django project structure with user authentication and profile management diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..af0e9c8 --- /dev/null +++ b/.env.example @@ -0,0 +1,30 @@ +# Server Configuration +DEBUG=True +ALLOWED_HOSTS=localhost,127.0.0.1 +PORT=8080 + +# Database Configuration +DB_HOST=localhost +DB_PORT=5432 +DB_USER=postgres +DB_PASSWORD=123 +DB_NAME=booking_system +DB_SSLMODE=disable + +# JWT Configuration +JWT_SECRET=your-super-secret-jwt-key-change-in-production + +# Stripe Configuration +STRIPE_SECRET_KEY=sk_test_your_stripe_secret_key +STRIPE_WEBHOOK_SECRET=whsec_your_webhook_secret +STRIPE_PUBLISHABLE_KEY=pk_test_your_publishable_key + +# SMTP Configuration +SMTP_HOST=smtp.hostinger.com +SMTP_PORT=465 +SMTP_USERNAME=hello@attunehearttherapy.com +SMTP_PASSWORD=G&n2S;ffTc8f +SMTP_FROM=hello@attunehearttherapy.com + +# Jitsi Configuration +JITSI_BASE_URL=https://meet.attunehearttherapy.com \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3020e7d --- /dev/null +++ b/.gitignore @@ -0,0 +1,172 @@ + +### Django ### +*.log +*.pot +*.pyc +__pycache__/ +local_settings.py +db.sqlite3 +db.sqlite3-journal +media + +# If your build process includes running collectstatic, then you probably don't need or want to include staticfiles/ +# in your Git repository. Update and uncomment the following line accordingly. +# /staticfiles/ + +### Django.Python Stack ### +# Byte-compiled / optimized / DLL files +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo + +# Django stuff: + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +# End of https://www.toptal.com/developers/gitignore/api/django \ No newline at end of file diff --git a/booking_system/__init__.py b/booking_system/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/booking_system/asgi.py b/booking_system/asgi.py new file mode 100644 index 0000000..1074db8 --- /dev/null +++ b/booking_system/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for booking_system project. + +It exposes the ASGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/5.2/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'booking_system.settings') + +application = get_asgi_application() diff --git a/booking_system/settings.py b/booking_system/settings.py new file mode 100644 index 0000000..c2400c9 --- /dev/null +++ b/booking_system/settings.py @@ -0,0 +1,203 @@ +import os +from pathlib import Path +from datetime import timedelta +from dotenv import load_dotenv + +load_dotenv() + +BASE_DIR = Path(__file__).resolve().parent.parent + +SECRET_KEY = os.getenv('JWT_SECRET', 'django-insecure-fallback-secret-key') + +DEBUG = os.getenv('DEBUG', 'False').lower() == 'true' + +ALLOWED_HOSTS = os.getenv('ALLOWED_HOSTS', 'localhost,127.0.0.1').split(',') + +INSTALLED_APPS = [ + 'jazzmin', + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + + # Third-party apps + 'rest_framework', + 'rest_framework_simplejwt', + 'corsheaders', + + # Local apps + 'users', + # 'meetings', +] + +MIDDLEWARE = [ + 'corsheaders.middleware.CorsMiddleware', + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', +] + +ROOT_URLCONF = 'booking_system.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'booking_system.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/5.2/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': BASE_DIR / 'db.sqlite3', + } +} + + +# Password validation +# https://docs.djangoproject.com/en/5.2/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + + +# JWT Configuration +SIMPLE_JWT = { + 'ACCESS_TOKEN_LIFETIME': timedelta(hours=24), # 24h as specified + 'REFRESH_TOKEN_LIFETIME': timedelta(days=7), + 'ROTATE_REFRESH_TOKENS': True, + 'BLACKLIST_AFTER_ROTATION': True, + 'SIGNING_KEY': os.getenv('JWT_SECRET', SECRET_KEY), +} + +# Stripe Configuration +STRIPE_PUBLISHABLE_KEY = os.getenv('STRIPE_PUBLISHABLE_KEY') +STRIPE_SECRET_KEY = os.getenv('STRIPE_SECRET_KEY') +STRIPE_WEBHOOK_SECRET = os.getenv('STRIPE_WEBHOOK_SECRET') + + + +# Jitsi Configuration +JITSI_BASE_URL = os.getenv('JITSI_BASE_URL', 'https://meet.jit.si') + +# Email Configuration +EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' +EMAIL_HOST = os.getenv('SMTP_HOST', 'smtp.hostinger.com') +EMAIL_PORT = int(os.getenv('SMTP_PORT', 465)) +EMAIL_USE_SSL = True # Since you're using port 465 +EMAIL_HOST_USER = os.getenv('SMTP_USERNAME', 'hello@attunehearttherapy.com') +EMAIL_HOST_PASSWORD = os.getenv('SMTP_PASSWORD', 'G&n2S;ffTc8f') +DEFAULT_FROM_EMAIL = os.getenv('SMTP_FROM', 'hello@attunehearttherapy.com') + + +# Django REST Framework +REST_FRAMEWORK = { + 'DEFAULT_AUTHENTICATION_CLASSES': ( + 'rest_framework_simplejwt.authentication.JWTAuthentication', + ), + 'DEFAULT_PERMISSION_CLASSES': ( + 'rest_framework.permissions.IsAuthenticated', + ), + 'DEFAULT_RENDERER_CLASSES': ( + 'rest_framework.renderers.JSONRenderer', + ), +} + +# CORS Configuration +CORS_ALLOWED_ORIGINS = [ + "http://localhost:3000", + "http://127.0.0.1:3000", + "http://localhost:8080", + "http://127.0.0.1:8080", +] + +CORS_ALLOW_CREDENTIALS = True + + + +ROOT_URLCONF = 'booking_system.urls' + +# Custom User Model +AUTH_USER_MODEL = 'users.CustomUser' + +# Authentication backends +AUTHENTICATION_BACKENDS = [ + 'users.backends.EmailBackend', + 'django.contrib.auth.backends.ModelBackend', +] + +# Email templates +EMAIL_TEMPLATES = { + 'MEETING_BOOKED': 'emails/meeting_booked.html', + 'MEETING_INVITATION': 'emails/meeting_invitation.html', + 'MEETING_REMINDER': 'emails/meeting_reminder.html', + 'MEETING_CANCELLED': 'emails/meeting_cancelled.html', + 'PAYMENT_SUCCESS': 'emails/payment_success.html', +} + + +# Internationalization +LANGUAGE_CODE = 'en-us' +TIME_ZONE = 'UTC' +USE_I18N = True +USE_TZ = True + +# Static files (CSS, JavaScript, Images) +STATIC_URL = '/static/' +STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') + +# Default primary key field type +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' + +# Celery Configuration (if using Redis) +CELERY_BROKER_URL = 'redis://localhost:6379/0' +CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' +CELERY_ACCEPT_CONTENT = ['json'] +CELERY_TASK_SERIALIZER = 'json' + +# Logging +LOGGING = { + 'version': 1, + 'disable_existing_loggers': False, + 'handlers': { + 'console': { + 'class': 'logging.StreamHandler', + }, + }, + 'root': { + 'handlers': ['console'], + 'level': 'INFO', + }, +} \ No newline at end of file diff --git a/booking_system/urls.py b/booking_system/urls.py new file mode 100644 index 0000000..a452274 --- /dev/null +++ b/booking_system/urls.py @@ -0,0 +1,8 @@ +from django.contrib import admin +from django.urls import path, include + +urlpatterns = [ + path('admin/', admin.site.urls), + path('api/auth/', include('users.urls')), + # path('api/', include('meetings.urls')), +] \ No newline at end of file diff --git a/booking_system/wsgi.py b/booking_system/wsgi.py new file mode 100644 index 0000000..7911a9a --- /dev/null +++ b/booking_system/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for booking_system project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/5.2/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'booking_system.settings') + +application = get_wsgi_application() diff --git a/manage.py b/manage.py new file mode 100644 index 0000000..a330967 --- /dev/null +++ b/manage.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + """Run administrative tasks.""" + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'booking_system.settings') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == '__main__': + main() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..f6bbd53 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,16 @@ +asgiref==3.10.0 +certifi==2025.10.5 +charset-normalizer==3.4.4 +Django==5.2.8 +django-cors-headers==4.9.0 +djangorestframework==3.16.1 +djangorestframework_simplejwt==5.5.1 +idna==3.11 +PyJWT==2.10.1 +python-dotenv==1.2.1 +requests==2.32.5 +sqlparse==0.5.3 +stripe==13.2.0 +typing_extensions==4.15.0 +tzdata==2025.2 +urllib3==2.5.0 diff --git a/templates/emails/booking_confirmation.html b/templates/emails/booking_confirmation.html new file mode 100644 index 0000000..e69de29 diff --git a/users/__init__.py b/users/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/users/admin.py b/users/admin.py new file mode 100644 index 0000000..d68cce1 --- /dev/null +++ b/users/admin.py @@ -0,0 +1,19 @@ +from django.contrib import admin +from .models import CustomUser, UserProfile + +# Register your models here. + +@admin.register(CustomUser) +class UserAdmin(admin.ModelAdmin): + list_display = ('email', 'username', 'first_name', 'last_name', 'is_staff') + search_fields = ('email', 'username', 'first_name', 'last_name') + ordering = ('email',) + + +@admin.register(UserProfile) +class UserProfileAdmin(admin.ModelAdmin): + list_display = ('user', 'timezone', 'created_at', 'updated_at') + search_fields = ('user__email', 'user__username') + ordering = ('user__email',) + + diff --git a/users/apps.py b/users/apps.py new file mode 100644 index 0000000..72b1401 --- /dev/null +++ b/users/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class UsersConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'users' diff --git a/users/backends.py b/users/backends.py new file mode 100644 index 0000000..d440044 --- /dev/null +++ b/users/backends.py @@ -0,0 +1,11 @@ +from django.contrib.auth.backends import ModelBackend +from .models import CustomUser + +class EmailBackend(ModelBackend): + def authenticate(self, request, email=None, password=None, **kwargs): + try: + user = CustomUser.objects.get(email=email) + if user.check_password(password): + return user + except CustomUser.DoesNotExist: + return None \ No newline at end of file diff --git a/users/migrations/0001_initial.py b/users/migrations/0001_initial.py new file mode 100644 index 0000000..90e4546 --- /dev/null +++ b/users/migrations/0001_initial.py @@ -0,0 +1,58 @@ +# Generated by Django 5.2.8 on 2025-11-12 06:32 + +import django.contrib.auth.models +import django.contrib.auth.validators +import django.db.models.deletion +import django.utils.timezone +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('auth', '0012_alter_user_first_name_max_length'), + ] + + operations = [ + migrations.CreateModel( + name='CustomUser', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('password', models.CharField(max_length=128, verbose_name='password')), + ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), + ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), + ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')), + ('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')), + ('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')), + ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), + ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), + ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), + ('email', models.EmailField(max_length=254, unique=True)), + ('phone_number', models.CharField(blank=True, max_length=20)), + ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.group', verbose_name='groups')), + ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.permission', verbose_name='user permissions')), + ], + options={ + 'verbose_name': 'user', + 'verbose_name_plural': 'users', + 'abstract': False, + }, + managers=[ + ('objects', django.contrib.auth.models.UserManager()), + ], + ), + migrations.CreateModel( + name='UserProfile', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('bio', models.TextField(blank=True, max_length=500)), + ('timezone', models.CharField(default='UTC', max_length=50)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='profile', to=settings.AUTH_USER_MODEL)), + ], + ), + ] diff --git a/users/migrations/__init__.py b/users/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/users/models.py b/users/models.py new file mode 100644 index 0000000..54626d6 --- /dev/null +++ b/users/models.py @@ -0,0 +1,22 @@ +from django.contrib.auth.models import AbstractUser +from django.db import models + +class CustomUser(AbstractUser): + email = models.EmailField(unique=True) + phone_number = models.CharField(max_length=20, blank=True) + + USERNAME_FIELD = 'email' + REQUIRED_FIELDS = ['username'] + + def __str__(self): + return self.email + +class UserProfile(models.Model): + user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, related_name='profile') + bio = models.TextField(max_length=500, blank=True) + timezone = models.CharField(max_length=50, default='UTC') + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + + def __str__(self): + return f"{self.user.email} Profile" \ No newline at end of file diff --git a/users/serializers.py b/users/serializers.py new file mode 100644 index 0000000..77c46ca --- /dev/null +++ b/users/serializers.py @@ -0,0 +1,44 @@ +from rest_framework import serializers +from django.contrib.auth.password_validation import validate_password +from .models import CustomUser, UserProfile + +class UserProfileSerializer(serializers.ModelSerializer): + class Meta: + model = UserProfile + fields = ['bio', 'timezone', 'created_at', 'updated_at'] + +class UserRegistrationSerializer(serializers.ModelSerializer): + password = serializers.CharField(write_only=True, required=True, validators=[validate_password]) + password2 = serializers.CharField(write_only=True, required=True) + profile = UserProfileSerializer(read_only=True) + + class Meta: + model = CustomUser + fields = ['email', 'username', 'password', 'password2', 'first_name', 'last_name', 'profile'] + extra_kwargs = { + 'first_name': {'required': True}, + 'last_name': {'required': True} + } + + def validate(self, attrs): + if attrs['password'] != attrs['password2']: + raise serializers.ValidationError({"password": "Password fields didn't match."}) + return attrs + + def create(self, validated_data): + validated_data.pop('password2') + user = CustomUser.objects.create_user( + email=validated_data['email'], + username=validated_data['username'], + password=validated_data['password'], + first_name=validated_data['first_name'], + last_name=validated_data['last_name'], + ) + return user + +class UserSerializer(serializers.ModelSerializer): + profile = UserProfileSerializer(read_only=True) + + class Meta: + model = CustomUser + fields = ['id', 'email', 'username', 'first_name', 'last_name', 'phone_number', 'profile'] \ No newline at end of file diff --git a/users/tests.py b/users/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/users/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/users/urls.py b/users/urls.py new file mode 100644 index 0000000..5efd45c --- /dev/null +++ b/users/urls.py @@ -0,0 +1,12 @@ +from django.urls import path +from rest_framework_simplejwt.views import TokenRefreshView +from . import views + +urlpatterns = [ + path('register/', views.register_user, name='register'), + path('login/', views.login_user, name='login'), + path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), + path('profile/', views.get_user_profile, name='profile'), + path('profile/update/', views.update_user_profile, name='update_profile'), + path('me/', views.UserDetailView.as_view(), name='user_detail'), +] \ No newline at end of file diff --git a/users/views.py b/users/views.py new file mode 100644 index 0000000..9abedab --- /dev/null +++ b/users/views.py @@ -0,0 +1,72 @@ +from rest_framework import status, generics +from rest_framework.decorators import api_view, permission_classes +from rest_framework.response import Response +from rest_framework.permissions import AllowAny, IsAuthenticated +from rest_framework_simplejwt.tokens import RefreshToken +from django.contrib.auth import authenticate +from .models import CustomUser, UserProfile +from .serializers import UserRegistrationSerializer, UserSerializer + +@api_view(['POST']) +@permission_classes([AllowAny]) +def register_user(request): + serializer = UserRegistrationSerializer(data=request.data) + if serializer.is_valid(): + user = serializer.save() + + # Create user profile + UserProfile.objects.create(user=user) + + # Generate tokens + refresh = RefreshToken.for_user(user) + + return Response({ + 'user': UserSerializer(user).data, + 'refresh': str(refresh), + 'access': str(refresh.access_token), + }, status=status.HTTP_201_CREATED) + + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + +@api_view(['POST']) +@permission_classes([AllowAny]) +def login_user(request): + email = request.data.get('email') + password = request.data.get('password') + + user = authenticate(request, email=email, password=password) + + if user is not None: + refresh = RefreshToken.for_user(user) + return Response({ + 'user': UserSerializer(user).data, + 'refresh': str(refresh), + 'access': str(refresh.access_token), + }) + else: + return Response( + {'error': 'Invalid credentials'}, + status=status.HTTP_401_UNAUTHORIZED + ) + +@api_view(['GET']) +@permission_classes([IsAuthenticated]) +def get_user_profile(request): + serializer = UserSerializer(request.user) + return Response(serializer.data) + +@api_view(['PUT']) +@permission_classes([IsAuthenticated]) +def update_user_profile(request): + serializer = UserSerializer(request.user, data=request.data, partial=True) + if serializer.is_valid(): + serializer.save() + return Response(serializer.data) + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + +class UserDetailView(generics.RetrieveAPIView): + serializer_class = UserSerializer + permission_classes = [IsAuthenticated] + + def get_object(self): + return self.request.user \ No newline at end of file