# Path: sitegate/models.py
# class EmailConfirmation(InheritedModel, ModelWithCode):
# 
#     user = models.ForeignKey(USER_MODEL, verbose_name=_('User'), on_delete=models.CASCADE)
# 
#     class Meta:
#         verbose_name = _('Activation code')
#         verbose_name_plural = _('Activation codes')
# 
#     class Fields:
#         code = _('Activation code')
#         expired = {'help_text': _('Expired codes couldn\'t be used for repeated account activations.')}
# 
#     @classmethod
#     def add(cls, user: 'User') -> 'EmailConfirmation':
#         new_code = cls(user=user)
#         new_code.save(force_insert=True)
#         return new_code
# 
#     def activate(self):
#         self.expired = True
#         self.time_accepted = timezone.now()
#         self.save()
# 
#         user = self.user
#         user.is_active = True
#         user.save()
# 
# class RemoteRecord(ModelWithCode):
#     """Stores data used for sign ins using remote services."""
# 
#     remote = models.CharField(_('Remote alias'), max_length=20, db_index=True)
# 
#     remote_id = models.CharField(
#         _('Remote ID'), null=True, default=None, max_length=64, db_index=True, db_column='rid')
# 
#     user = models.ForeignKey(
#         USER_MODEL, null=True, blank=True,
#         related_name='remotes', verbose_name=_('User'), on_delete=models.CASCADE)
# 
#     expired = None
# 
#     class Meta:
#         verbose_name = _('Remote record')
#         verbose_name_plural = _('Remotes records')
# 
#     def __str__(self):
#         return f'{self.remote} {self.code}'
# 
#     @classmethod
#     def add(cls, *, remote: str, user: Optional['User']) -> 'RemoteRecord':
#         record = cls(
#             remote=remote,
#             user=user,
#         )
#         record.save(force_insert=True)
#         return record
# 
#     @classmethod
#     def cleanup(cls, *, ago: int = None):
#         """Removes remote records not linked to certain user.
#         Useful for periodic background cleaning.
# 
#         :param ago: Days. Allows cleanup for stale records created X days ago.
#             Defaults to None (cleanup all stale).
# 
#         """
#         filter_kwargs = {
#             'remote_id__isnull': True,
#             'user_id__isnull': True,
#         }
# 
#         if ago:
#             filter_kwargs['time_created__lte'] = timezone.now() - timedelta(days=int(ago))
# 
#         cls.objects.filter(**filter_kwargs).delete()
# 
# Path: sitegate/settings.py
# SIGNUP_VERIFY_EMAIL_ERROR_TEXT = getattr(
#     settings, 'SITEGATE_SIGNUP_VERIFY_EMAIL_ERROR_TEXT',
#     _('Unable to verify an e-mail. User account was not activated.'))
# 
# SIGNUP_VERIFY_EMAIL_SUCCESS_TEXT = getattr(
#     settings, 'SITEGATE_SIGNUP_VERIFY_EMAIL_SUCCESS_TEXT',
#     _('E-mail was successfully verified. You can now proceed to sign in.'))
# 
# Path: sitegate/utils.py
# def get_registered_remotes() -> Dict[str, 'Remote']:
#     """Returns registered remotes dict indexed by their aliases."""
#     return _REMOTES_REGISTRY


from django.contrib import messages
from django.http import HttpRequest, HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed
from django.shortcuts import redirect
from django.views.decorators.csrf import requires_csrf_token
from .models import EmailConfirmation, RemoteRecord
from .settings import SIGNUP_VERIFY_EMAIL_ERROR_TEXT, SIGNUP_VERIFY_EMAIL_SUCCESS_TEXT
from .utils import get_registered_remotes
            user_data=user_data,
            remote_record=remote_record,
            user=user,
        )

    # this is GET
    return remote.auth_continue(request)


def remote_auth_start(request: HttpRequest, alias: str) -> HttpResponse:
    """Performs a redirect to another service for remote auth.

    :param request:
    :param alias: remote service alias

    """
    if not request.method == 'POST':
        return HttpResponseNotAllowed(['post'])

    remote = get_registered_remotes().get(alias)

    if not remote:
        return HttpResponseBadRequest()

    user = request.user

    if user.is_anonymous:
        user = None

    else:

# Path: sitegate/models.py
# class EmailConfirmation(InheritedModel, ModelWithCode):
# 
#     user = models.ForeignKey(USER_MODEL, verbose_name=_('User'), on_delete=models.CASCADE)
# 
#     class Meta:
#         verbose_name = _('Activation code')
#         verbose_name_plural = _('Activation codes')
# 
#     class Fields:
#         code = _('Activation code')
#         expired = {'help_text': _('Expired codes couldn\'t be used for repeated account activations.')}
# 
#     @classmethod
#     def add(cls, user: 'User') -> 'EmailConfirmation':
#         new_code = cls(user=user)
#         new_code.save(force_insert=True)
#         return new_code
# 
#     def activate(self):
#         self.expired = True
#         self.time_accepted = timezone.now()
#         self.save()
# 
#         user = self.user
#         user.is_active = True
#         user.save()
# 
# class RemoteRecord(ModelWithCode):
#     """Stores data used for sign ins using remote services."""
# 
#     remote = models.CharField(_('Remote alias'), max_length=20, db_index=True)
# 
#     remote_id = models.CharField(
#         _('Remote ID'), null=True, default=None, max_length=64, db_index=True, db_column='rid')
# 
#     user = models.ForeignKey(
#         USER_MODEL, null=True, blank=True,
#         related_name='remotes', verbose_name=_('User'), on_delete=models.CASCADE)
# 
#     expired = None
# 
#     class Meta:
#         verbose_name = _('Remote record')
#         verbose_name_plural = _('Remotes records')
# 
#     def __str__(self):
#         return f'{self.remote} {self.code}'
# 
#     @classmethod
#     def add(cls, *, remote: str, user: Optional['User']) -> 'RemoteRecord':
#         record = cls(
#             remote=remote,
#             user=user,
#         )
#         record.save(force_insert=True)
#         return record
# 
#     @classmethod
#     def cleanup(cls, *, ago: int = None):
#         """Removes remote records not linked to certain user.
#         Useful for periodic background cleaning.
# 
#         :param ago: Days. Allows cleanup for stale records created X days ago.
#             Defaults to None (cleanup all stale).
# 
#         """
#         filter_kwargs = {
#             'remote_id__isnull': True,
#             'user_id__isnull': True,
#         }
# 
#         if ago:
#             filter_kwargs['time_created__lte'] = timezone.now() - timedelta(days=int(ago))
# 
#         cls.objects.filter(**filter_kwargs).delete()
# 
# Path: sitegate/settings.py
# SIGNUP_VERIFY_EMAIL_ERROR_TEXT = getattr(
#     settings, 'SITEGATE_SIGNUP_VERIFY_EMAIL_ERROR_TEXT',
#     _('Unable to verify an e-mail. User account was not activated.'))
# 
# SIGNUP_VERIFY_EMAIL_SUCCESS_TEXT = getattr(
#     settings, 'SITEGATE_SIGNUP_VERIFY_EMAIL_SUCCESS_TEXT',
#     _('E-mail was successfully verified. You can now proceed to sign in.'))
# 
# Path: sitegate/utils.py
# def get_registered_remotes() -> Dict[str, 'Remote']:
#     """Returns registered remotes dict indexed by their aliases."""
#     return _REMOTES_REGISTRY


# Path: sitegate/views.py
from django.contrib import messages
from django.http import HttpRequest, HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed
from django.shortcuts import redirect
from django.views.decorators.csrf import requires_csrf_token
from .models import EmailConfirmation, RemoteRecord
from .settings import SIGNUP_VERIFY_EMAIL_ERROR_TEXT, SIGNUP_VERIFY_EMAIL_SUCCESS_TEXT
from .utils import get_registered_remotes

            user_data=user_data,
            remote_record=remote_record,
            user=user,
        )

    # this is GET
    return remote.auth_continue(request)


def remote_auth_start(request: HttpRequest, alias: str) -> HttpResponse:
    """Performs a redirect to another service for remote auth.

    :param request:
    :param alias: remote service alias

    """
    if not request.method == 'POST':
        return HttpResponseNotAllowed(['post'])

    remote = get_registered_remotes().get(alias)

    if not remote:
        return HttpResponseBadRequest()

    user = request.user

    if user.is_anonymous:
        user = None

    else:

        if RemoteRecord.objects.filter(user=user, remote=alias).exists():