64 lines
2.6 KiB
Python
64 lines
2.6 KiB
Python
"""
|
|
Management command to create the OAuth2 Application record and a demo user.
|
|
|
|
Usage:
|
|
python manage.py setup_oauth
|
|
"""
|
|
from django.core.management.base import BaseCommand
|
|
from django.contrib.auth import get_user_model
|
|
from oauth2_provider.models import Application
|
|
|
|
User = get_user_model()
|
|
|
|
CLIENT_ID = 'react-oauth-client'
|
|
REDIRECT_URI = 'http://localhost:5173/callback'
|
|
|
|
|
|
class Command(BaseCommand):
|
|
help = 'Create the OAuth2 Application and a demo superuser'
|
|
|
|
def handle(self, *args, **kwargs):
|
|
# ── Demo user ──────────────────────────────────────────────────────────
|
|
user, user_created = User.objects.get_or_create(
|
|
username='admin',
|
|
defaults={
|
|
'email': 'admin@example.com',
|
|
'is_staff': True,
|
|
'is_superuser': True,
|
|
},
|
|
)
|
|
if user_created:
|
|
user.set_password('admin123')
|
|
user.save()
|
|
self.stdout.write(self.style.SUCCESS('Created superuser: admin / admin123'))
|
|
else:
|
|
self.stdout.write('Superuser "admin" already exists — skipping.')
|
|
|
|
# ── OAuth2 Application ─────────────────────────────────────────────────
|
|
app, app_created = Application.objects.get_or_create(
|
|
client_id=CLIENT_ID,
|
|
defaults={
|
|
'name': 'React Frontend',
|
|
'user': user,
|
|
'client_type': Application.CLIENT_PUBLIC,
|
|
'authorization_grant_type': Application.GRANT_AUTHORIZATION_CODE,
|
|
'redirect_uris': REDIRECT_URI,
|
|
'skip_authorization': False,
|
|
},
|
|
)
|
|
if not app_created:
|
|
# Ensure redirect URI is current if re-running
|
|
if REDIRECT_URI not in app.redirect_uris.split():
|
|
app.redirect_uris = REDIRECT_URI
|
|
app.save()
|
|
self.stdout.write('OAuth2 Application already exists — skipping.')
|
|
else:
|
|
self.stdout.write(self.style.SUCCESS(f'Created OAuth2 Application: {app.name}'))
|
|
|
|
self.stdout.write('')
|
|
self.stdout.write(self.style.SUCCESS('── OAuth2 Application Details ──'))
|
|
self.stdout.write(f' Client ID : {app.client_id}')
|
|
self.stdout.write(f' Redirect URI : {app.redirect_uris}')
|
|
self.stdout.write(f' Grant type : {app.authorization_grant_type}')
|
|
self.stdout.write(f' PKCE required: True (enforced in settings)')
|