# Path: server/apps/authentication/models.py
# class Account(AbstractBaseUser):
# 
#     TZ_CHOICES = [(tz, tz) for tz in pytz.common_timezones]
# 
#     email = models.EmailField(unique=True)
#     username = models.CharField(max_length=40, unique=True)
#     slug = models.SlugField(max_length=60, unique=True)
# 
#     name = models.CharField(verbose_name='Full Name', max_length=120, blank=True)
#     tagline = models.CharField(max_length=260, blank=True)
# 
#     external_avatar_url = models.CharField(max_length=260, blank=True, null=True)
# 
#     is_staff = models.BooleanField(default=False)
#     is_active = models.BooleanField(default=True)
#     is_admin = models.BooleanField(default=False)
# 
#     time_zone = models.CharField(max_length=64, null=True, default=settings.TIME_ZONE)
# 
#     created_at = models.DateTimeField(auto_now_add=True)
#     updated_at = models.DateTimeField(auto_now=True)
# 
#     objects = AccountManager()
# 
#     USERNAME_FIELD = 'email'
#     REQUIRED_FIELDS = ['username']
# 
#     class Meta:
#         ordering = ['slug']
# 
#     def save(self, *args, **kwargs):
# 
#         slug = slugify(self.username)
#         self.slug = slug
#         count = 0
#         while Account.objects.filter(slug=self.slug).exclude(pk=self.id).exists():
#             self.slug = '{0}{1}'.format(slug, count)
#             logger.debug('Slug conflict. Trying again with {0}'.format(self.slug))
#             count += 1
# 
#         super(Account, self).save(*args, **kwargs)
# 
#     def __str__(self):
#         return '@{0}'.format(self.username)
# 
#     def get_full_name(self):
#         return self.name
# 
#     def get_short_name(self):
#         if (self.name != ''):
#             # Try to extract the first name
#             names = self.name.split()
#             first_name = names[0]
#             return first_name
#         return self.username
# 
#     # For full access to Permission system, we needed to add the PermissionMixin
#     def has_perm(self, perm, obj=None):
#         return True
# 
#     def has_perms(perm_list, obj=None):
#         return True
# 
#     def has_module_perms(self, app_label):
#         return True
# 
#     # Custom Methods
#     # --------------
#     def get_absolute_url(self):
#         return '/account/%s/' % self.slug
# 
#     def get_edit_url(self):
#         return '%sedit/' % self.get_absolute_url()
# 
#     def get_token(self):
#         try:
#             token = Token.objects.get(user=self)
#         except:
#             token = Token.objects.create(user=self)
#         return token
# 
#     def get_gravatar_thumbnail_url(self, size=100):
#         # Set your variables here
#         email = self.email
#         default = 'identicon'
# 
#         # construct the url
#         gravatar_url = "https://secure.gravatar.com/avatar/" + hashlib.md5(email.lower().encode('utf-8')).hexdigest() + "?"
#         try:
#             # Python 3.4
#             gravatar_url += urllib.parse.urlencode({'d': default, 's': str(size)})
#         except:
#             # Python 2.7
#             gravatar_url += urllib.urlencode({'d': default, 's': str(size)})
# 
#         return gravatar_url


import pytz
from captcha.fields import ReCaptchaField
from django import forms as forms
from django.conf import settings
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from django.core.exceptions import ValidationError
from django.forms import ModelForm
from allauth.account.forms import LoginForm, SignupForm
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Field, Layout, Submit
from .models import Account

    class Meta:
        model = Account
        fields = ('username', 'email', 'name', 'is_staff', )

    def clean_password2(self):
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super(AdminUserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user


class AdminUserChangeForm(forms.ModelForm):
    """A form for updating users. Includes all the fields on
    the user, but replaces the password field with admin's
    password hash display field.
    """
    password = ReadOnlyPasswordHashField()

    class Meta:

# Path: server/apps/authentication/models.py
# class Account(AbstractBaseUser):
# 
#     TZ_CHOICES = [(tz, tz) for tz in pytz.common_timezones]
# 
#     email = models.EmailField(unique=True)
#     username = models.CharField(max_length=40, unique=True)
#     slug = models.SlugField(max_length=60, unique=True)
# 
#     name = models.CharField(verbose_name='Full Name', max_length=120, blank=True)
#     tagline = models.CharField(max_length=260, blank=True)
# 
#     external_avatar_url = models.CharField(max_length=260, blank=True, null=True)
# 
#     is_staff = models.BooleanField(default=False)
#     is_active = models.BooleanField(default=True)
#     is_admin = models.BooleanField(default=False)
# 
#     time_zone = models.CharField(max_length=64, null=True, default=settings.TIME_ZONE)
# 
#     created_at = models.DateTimeField(auto_now_add=True)
#     updated_at = models.DateTimeField(auto_now=True)
# 
#     objects = AccountManager()
# 
#     USERNAME_FIELD = 'email'
#     REQUIRED_FIELDS = ['username']
# 
#     class Meta:
#         ordering = ['slug']
# 
#     def save(self, *args, **kwargs):
# 
#         slug = slugify(self.username)
#         self.slug = slug
#         count = 0
#         while Account.objects.filter(slug=self.slug).exclude(pk=self.id).exists():
#             self.slug = '{0}{1}'.format(slug, count)
#             logger.debug('Slug conflict. Trying again with {0}'.format(self.slug))
#             count += 1
# 
#         super(Account, self).save(*args, **kwargs)
# 
#     def __str__(self):
#         return '@{0}'.format(self.username)
# 
#     def get_full_name(self):
#         return self.name
# 
#     def get_short_name(self):
#         if (self.name != ''):
#             # Try to extract the first name
#             names = self.name.split()
#             first_name = names[0]
#             return first_name
#         return self.username
# 
#     # For full access to Permission system, we needed to add the PermissionMixin
#     def has_perm(self, perm, obj=None):
#         return True
# 
#     def has_perms(perm_list, obj=None):
#         return True
# 
#     def has_module_perms(self, app_label):
#         return True
# 
#     # Custom Methods
#     # --------------
#     def get_absolute_url(self):
#         return '/account/%s/' % self.slug
# 
#     def get_edit_url(self):
#         return '%sedit/' % self.get_absolute_url()
# 
#     def get_token(self):
#         try:
#             token = Token.objects.get(user=self)
#         except:
#             token = Token.objects.create(user=self)
#         return token
# 
#     def get_gravatar_thumbnail_url(self, size=100):
#         # Set your variables here
#         email = self.email
#         default = 'identicon'
# 
#         # construct the url
#         gravatar_url = "https://secure.gravatar.com/avatar/" + hashlib.md5(email.lower().encode('utf-8')).hexdigest() + "?"
#         try:
#             # Python 3.4
#             gravatar_url += urllib.parse.urlencode({'d': default, 's': str(size)})
#         except:
#             # Python 2.7
#             gravatar_url += urllib.urlencode({'d': default, 's': str(size)})
# 
#         return gravatar_url


# Path: server/apps/authentication/forms.py
import pytz
from captcha.fields import ReCaptchaField
from django import forms as forms
from django.conf import settings
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from django.core.exceptions import ValidationError
from django.forms import ModelForm
from allauth.account.forms import LoginForm, SignupForm
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Field, Layout, Submit
from .models import Account


    class Meta:
        model = Account
        fields = ('username', 'email', 'name', 'is_staff', )

    def clean_password2(self):
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super(AdminUserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user


class AdminUserChangeForm(forms.ModelForm):
    """A form for updating users. Includes all the fields on
    the user, but replaces the password field with admin's
    password hash display field.
    """
    password = ReadOnlyPasswordHashField()

    class Meta:

        model = Account