Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
wbauth / authentication / models.py
Size: Mime:
# -*- encoding: utf-8 -*-
import unicodedata
from django.contrib.auth.models import (AbstractBaseUser, BaseUserManager,
                                        PermissionsMixin)
from django.contrib.postgres.fields import JSONField
from django.core.mail import EmailMultiAlternatives
from django.db import models
from django.template.loader import get_template
from django.utils import timezone
from django.utils.crypto import get_random_string
from django.utils.encoding import force_text
from django.utils.html import strip_tags
from crm.models.entries import Person


class UserManager(BaseUserManager):
    use_in_migrations = True

    @classmethod
    def normalize_username(cls, username):
        return unicodedata.normalize('NFKC', force_text(username))

    def _create_user(self, username, email, password, **extra_fields):
        if not email:
            raise ValueError('No E-Mail provided')
        email = self.normalize_email(email)
        if not username:
            raise ValueError('No Username provided')
        username = UserManager.normalize_username(username)
        user = self.model(email=email, username=username, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, username, email, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_superuser', False)
        extra_fields.setdefault('is_active', True)
        return self._create_user(username, email, password, **extra_fields)

    def create_superuser(self, username, email, password, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_active', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(username, email, password, **extra_fields)

def get_default_frontend_settings():
    return {
       '/app/calendar': '{"specs":{"className":"calendar-widget","dimension":{"w":905.5,"h":675.5},"position":{"left":0,"top":0},"state":"NORMAL","focus":false,"title":"Calendar"},"content":"<CalendarView><->{}<->{\\"controllerSettings\\":{}}"}',
       '/app/crm': '{"specs":{"className":"crm-main-widget","dimension":{"w":1050.5,"h":689.5},"position":{"left":0,"top":0},"state":"NORMAL","focus":false,"title":"CRM"},"content":"<CRMMainView><->{}<->{\\"controllerSettings\\":{\\"widget-1.CRMMainView.CRMCompanyListView.Controller\\":{\\"filterValues\\":{}},\\"undefined\\":{\\"selectedTab\\":2}}}"}',
       '/app/dashboard': '{"specs":{"className":"stainly-news-widget","dimension":{"w":575.5,"h":452},"position":{"left":0,"top":0},"state":"NORMAL","focus":false,"title":"News"},"content":"<StainlyNewsView><->{}<->{\\"controllerSettings\\":{}}"}<=>{"specs":{"className":"rebate-list-widget","dimension":{"w":575.5,"h":452},"position":{"left":575.5,"top":0},"state":"NORMAL","focus":false,"title":"Retrocessions"},"content":"<RebateListView><->{}<->{\\"controllerSettings\\":{\\"widget-2.RebateListView\\":{\\"ordering\\":\\"search_name\\"}}}"}<=>{"specs":{"className":"claim-widget","dimension":{"w":1151,"h":452},"position":{"left":0,"top":452},"state":"NORMAL","focus":false,"title":"Claims"},"content":"<PMClaimListView><->{}<->{\\"controllerSettings\\":{\\"widget-3.InvestmentView.PMClaimListView\\":{\\"filterValues\\":{}}}}"}',
       '/app/portfolio': '{"specs":{"className":"portfolio-manager-widget","dimension":{"w":946.5,"h":686.5},"position":{"left":0,"top":0},"state":"NORMAL","focus":false,"title":"Portfolio Manager"},"content":"<PMMainView><->{}<->{\\"controllerSettings\\":{\\"widget-1.PMInvestmentsView\\":{\\"filterValues\\":{\\"start_date,end_date\\":[\\"2018-10-01\\",\\"2018-12-31\\"]}}},\\"selectedTab\\":0}"}'
   }

class EmailAbstractUser(AbstractBaseUser, PermissionsMixin):
    first_name = models.CharField(max_length=255, blank=True, default='')
    last_name = models.CharField(max_length=255, blank=True, default='')
    email = models.EmailField('email address', unique=True)
    username = models.CharField('username', max_length=255, unique=True)
    profile = models.OneToOneField(Person, on_delete=models.CASCADE, related_name='user_account')
    is_staff = models.BooleanField(
        'staff status',
        default=False,
        help_text='Designates whether the user can log into this admin site.',
    )
    is_active = models.BooleanField(
        'active',
        default=False,
        help_text='Designates whether this user should be treated as active. '
        'Unselect this instead of deleting accounts.',
    )
    date_joined = models.DateTimeField('date joined', default=timezone.now)
    frontend_settings = JSONField(null=True, blank=True, default=get_default_frontend_settings)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username','first_name','last_name']

    class Meta:
        verbose_name = 'user'
        verbose_name_plural = 'users'
        abstract = True


    def get_full_name(self):
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def get_short_name(self):
        return self.first_name

    def save(self, *args, **kwargs):
        try:
            self.profile
        except:
            self.profile = Person.create_with_user(self)
            self.profile.initialize_additional_fields()
            self.profile.save()

        super().save(*args, **kwargs)

    def reset_password(self):
        html = get_template('authentication/emails/reset_password.html')
        password = self.__class__.objects.make_random_password()
        self.set_password(password)
        self.save()
        context = {'person': self.profile, 'password': password}
        html_content = html.render(context)

        msg = EmailMultiAlternatives('Password Reset', strip_tags(html_content), 'system@restbench.com', [self.email])
        msg.attach_alternative(html_content, "text/html")
        msg.send()

class User(EmailAbstractUser):

    class Meta(EmailAbstractUser.Meta):
        swappable = 'AUTH_USER_MODEL'