# Path: apps/core/backends/token.py
# def token_issue_email_auth(user, newbie=False):
#     EmailAuthToken.objects.filter(user=user).delete()
#     while True:
#         tokenid = token_hex(24)
#         if not EmailAuthToken.objects.filter(tokenid=tokenid).count():
#             break
# 
#     tomorrow = timezone.now() + datetime.timedelta(days=1)
#     EmailAuthToken.objects.filter(user=user).delete()
#     EmailAuthToken(tokenid=tokenid, expire_time=tomorrow, user=user).save()
# 
#     email = user.profile.email_new if user.profile.email_authed else user.email
#     url = f'{settings.DOMAIN}/account/email/verify/{tokenid}/'
#     template = EMAIL_NEWBIE_MSG_BODY if newbie else EMAIL_AUTH_MSG_BODY
#     msg = template.format(
#         name=user.first_name,
#         email=email,
#         link=url,
#     )
#     send_mail(EMAIL_AUTH_MSG_TITLE, '', EMAIL_SENDER,
#               [email], html_message=msg)
# 
# Path: apps/core/backends/util.py
# def validate_email(email, exclude=''):
#     if email == exclude:
#         return True
# 
#     m = re.match(r'^([^@]+)@([^@]+)$', email)
#     if not m:
#         return False
# 
#     domain = m.group(2).strip().lower()
#     if domain == 'sso.sparcs.org':
#         return False
#     elif EmailDomain.objects.filter(domain=domain, is_banned=True).exists():
#         return False
#     return User.objects.filter(email=email).count() == 0
# 
# Path: apps/core/forms.py
# class UserForm(ModelForm):
#     def __init__(self, *args, **kwargs):
#         super(UserForm, self).__init__(*args, **kwargs)
# 
#     class Meta:
#         model = User
#         fields = ('email', 'password', 'first_name', 'last_name')
# 
# Path: apps/core/models.py
# class UserProfile(models.Model):
#     """
#     denotes additional information of single user
#     - user:            user object
#     - gender:          gender; *H / *M / *F / *E or others
#     - birthday:        birthday
#     - point:           point for public services
#     - point_test:      point for test services
#     - email_new:       new email before auth
#     - email_authed:    email authed state
#     - test_only:       indicate test only account
#     - test_enabled:    test mode state
#     - facebook_id:     facebook unique id
#     - twitter_id:      twitter unique id
#     - kaist_id:        kaist uid
#     - kaist_info:      additional kaist info
#     - kaist_info_time: kaist info updated time
#     - sparcs_id:       sparcs id iff sparcs member
#     - expire_time:     expire time for permanent deletion
#     """
#     user = models.OneToOneField(User, on_delete=models.CASCADE,
#                                 related_name='profile')
#     gender = models.CharField(max_length=30)
#     birthday = models.DateField(blank=True, null=True)
#     point = models.IntegerField(default=0)
#     point_test = models.IntegerField(default=0)
#     email_new = models.EmailField(blank=True, null=True)
#     email_authed = models.BooleanField(default=False)
#     test_only = models.BooleanField(default=False)
#     test_enabled = models.BooleanField(default=False)
#     facebook_id = models.CharField(max_length=50, blank=True, null=True)
#     twitter_id = models.CharField(max_length=50, blank=True, null=True)
#     kaist_id = models.CharField(max_length=50, blank=True, null=True)
#     kaist_info = models.TextField(blank=True, null=True)
#     kaist_info_time = models.DateField(blank=True, null=True)
#     sparcs_id = models.CharField(max_length=50, blank=True, null=True)
#     expire_time = models.DateTimeField(blank=True, null=True)
# 
#     @property
#     def flags(self):
#         return {
#             'test': self.test_enabled,
#             'test-only': self.test_only,
#             'dev': self.user.is_staff or bool(self.sparcs_id),
#             'sparcs': bool(self.sparcs_id),
#             'sysop': self.user.is_staff,
#         }
# 
#     def gender_display(self):
#         if self.gender == '*M':
#             return 'Male'
#         elif self.gender == '*F':
#             return 'Female'
#         elif self.gender == '*H':
#             return 'Hide'
#         elif self.gender == '*E':
#             return 'etc'
#         return self.gender
# 
#     def activate(self):
#         if self.expire_time:
#             self.expire_time = None
#             self.save()
#             return True
#         return False
# 
#     def save_kaist_info(self, info):
#         self.kaist_id = info['userid']
#         self.kaist_info = json.dumps(info['kaist_info'])
#         self.kaist_info_time = timezone.now()
#         self.save()
# 
#     def __str__(self):
#         return f'{self.user}''s profile'


from secrets import token_hex
from django.contrib.auth.models import User
from apps.core.backends.token import token_issue_email_auth
from apps.core.backends.util import validate_email
from apps.core.forms import UserForm
from apps.core.models import UserProfile

    token_issue_email_auth(user, newbie=True)
    return user


# signup using social
def signup_social(typ, profile):
    while True:
        username = token_hex(10)
        if not User.objects.filter(username=username).count():
            break

    first_name = profile.get('first_name', '')
    last_name = profile.get('last_name', '')

    email = profile.get('email', '')
    if not email:
        email = f'random-{token_hex(6)}@sso.sparcs.org'

    while True:
        if not User.objects.filter(email=email).count():
            break
        email = f'random-{token_hex(6)}@sso.sparcs.org'

    user = User.objects.create_user(username=username,
                                    first_name=first_name,
                                    last_name=last_name,
                                    email=email)
    user.save()


# Path: apps/core/backends/token.py
# def token_issue_email_auth(user, newbie=False):
#     EmailAuthToken.objects.filter(user=user).delete()
#     while True:
#         tokenid = token_hex(24)
#         if not EmailAuthToken.objects.filter(tokenid=tokenid).count():
#             break
# 
#     tomorrow = timezone.now() + datetime.timedelta(days=1)
#     EmailAuthToken.objects.filter(user=user).delete()
#     EmailAuthToken(tokenid=tokenid, expire_time=tomorrow, user=user).save()
# 
#     email = user.profile.email_new if user.profile.email_authed else user.email
#     url = f'{settings.DOMAIN}/account/email/verify/{tokenid}/'
#     template = EMAIL_NEWBIE_MSG_BODY if newbie else EMAIL_AUTH_MSG_BODY
#     msg = template.format(
#         name=user.first_name,
#         email=email,
#         link=url,
#     )
#     send_mail(EMAIL_AUTH_MSG_TITLE, '', EMAIL_SENDER,
#               [email], html_message=msg)
# 
# Path: apps/core/backends/util.py
# def validate_email(email, exclude=''):
#     if email == exclude:
#         return True
# 
#     m = re.match(r'^([^@]+)@([^@]+)$', email)
#     if not m:
#         return False
# 
#     domain = m.group(2).strip().lower()
#     if domain == 'sso.sparcs.org':
#         return False
#     elif EmailDomain.objects.filter(domain=domain, is_banned=True).exists():
#         return False
#     return User.objects.filter(email=email).count() == 0
# 
# Path: apps/core/forms.py
# class UserForm(ModelForm):
#     def __init__(self, *args, **kwargs):
#         super(UserForm, self).__init__(*args, **kwargs)
# 
#     class Meta:
#         model = User
#         fields = ('email', 'password', 'first_name', 'last_name')
# 
# Path: apps/core/models.py
# class UserProfile(models.Model):
#     """
#     denotes additional information of single user
#     - user:            user object
#     - gender:          gender; *H / *M / *F / *E or others
#     - birthday:        birthday
#     - point:           point for public services
#     - point_test:      point for test services
#     - email_new:       new email before auth
#     - email_authed:    email authed state
#     - test_only:       indicate test only account
#     - test_enabled:    test mode state
#     - facebook_id:     facebook unique id
#     - twitter_id:      twitter unique id
#     - kaist_id:        kaist uid
#     - kaist_info:      additional kaist info
#     - kaist_info_time: kaist info updated time
#     - sparcs_id:       sparcs id iff sparcs member
#     - expire_time:     expire time for permanent deletion
#     """
#     user = models.OneToOneField(User, on_delete=models.CASCADE,
#                                 related_name='profile')
#     gender = models.CharField(max_length=30)
#     birthday = models.DateField(blank=True, null=True)
#     point = models.IntegerField(default=0)
#     point_test = models.IntegerField(default=0)
#     email_new = models.EmailField(blank=True, null=True)
#     email_authed = models.BooleanField(default=False)
#     test_only = models.BooleanField(default=False)
#     test_enabled = models.BooleanField(default=False)
#     facebook_id = models.CharField(max_length=50, blank=True, null=True)
#     twitter_id = models.CharField(max_length=50, blank=True, null=True)
#     kaist_id = models.CharField(max_length=50, blank=True, null=True)
#     kaist_info = models.TextField(blank=True, null=True)
#     kaist_info_time = models.DateField(blank=True, null=True)
#     sparcs_id = models.CharField(max_length=50, blank=True, null=True)
#     expire_time = models.DateTimeField(blank=True, null=True)
# 
#     @property
#     def flags(self):
#         return {
#             'test': self.test_enabled,
#             'test-only': self.test_only,
#             'dev': self.user.is_staff or bool(self.sparcs_id),
#             'sparcs': bool(self.sparcs_id),
#             'sysop': self.user.is_staff,
#         }
# 
#     def gender_display(self):
#         if self.gender == '*M':
#             return 'Male'
#         elif self.gender == '*F':
#             return 'Female'
#         elif self.gender == '*H':
#             return 'Hide'
#         elif self.gender == '*E':
#             return 'etc'
#         return self.gender
# 
#     def activate(self):
#         if self.expire_time:
#             self.expire_time = None
#             self.save()
#             return True
#         return False
# 
#     def save_kaist_info(self, info):
#         self.kaist_id = info['userid']
#         self.kaist_info = json.dumps(info['kaist_info'])
#         self.kaist_info_time = timezone.now()
#         self.save()
# 
#     def __str__(self):
#         return f'{self.user}''s profile'


# Path: apps/core/backends/signup.py
from secrets import token_hex
from django.contrib.auth.models import User
from apps.core.backends.token import token_issue_email_auth
from apps.core.backends.util import validate_email
from apps.core.forms import UserForm
from apps.core.models import UserProfile


    token_issue_email_auth(user, newbie=True)
    return user


# signup using social
def signup_social(typ, profile):
    while True:
        username = token_hex(10)
        if not User.objects.filter(username=username).count():
            break

    first_name = profile.get('first_name', '')
    last_name = profile.get('last_name', '')

    email = profile.get('email', '')
    if not email:
        email = f'random-{token_hex(6)}@sso.sparcs.org'

    while True:
        if not User.objects.filter(email=email).count():
            break
        email = f'random-{token_hex(6)}@sso.sparcs.org'

    user = User.objects.create_user(username=username,
                                    first_name=first_name,
                                    last_name=last_name,
                                    email=email)
    user.save()


    user.profile = UserProfile(gender=profile.get('gender', '*H'))