You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

67 lines
2.2 KiB

import logging
from celery import shared_task
logger = logging.getLogger(__name__)
@shared_task(name="send_notification_task")
def send_notification_task(user_id: int, title: str, body: str, data: dict = None):
"""
Celery background task to dispatch notifications.
Can be connected to Firebase Cloud Messaging (FCM), APNS, or email.
"""
try:
from apps.account.models import User, Notification
user = User.objects.get(id=user_id)
# Save in-app notification record
Notification.objects.create(
user=user,
title=title,
message=body,
notification_type=data.get('type') if data else 'general',
action=data.get('action', 'navigate') if data else 'navigate',
navigate_to=data.get('navigate_to', '') if data else '',
)
logger.info(f"Notification recorded for user #{user_id}: {title}")
return True
except Exception as e:
logger.error(f"Error sending notification to user #{user_id}: {e}")
return False
@shared_task(name="cleanup_expired_tokens_task")
def cleanup_expired_tokens_task():
"""
Periodic task to clean up old or expired auth tokens/sessions.
"""
logger.info("Executing cleanup_expired_tokens_task...")
return True
@shared_task(name="send_2fa_email_otp_task")
def send_2fa_email_otp_task(recipient_email: str, otp_code: str) -> bool:
"""
Centralized Celery task to send a 2FA verification code via email.
"""
try:
from utils import send_email
return bool(send_email(recipient_email, otp_code))
except Exception as e:
logger.error(f"Error sending 2FA email OTP to {recipient_email}: {e}")
return False
def dispatch_2fa_email_otp(recipient_email: str, otp_code: str) -> bool:
"""
Dispatches 2FA email OTP using the centralized email service.
"""
if not recipient_email:
return False
try:
from utils import send_email
return bool(send_email(recipient_email, otp_code))
except Exception as e:
logger.warning(f"Fallback/Error in dispatch_2fa_email_otp for {recipient_email}: {e}")
return False