Ejemplo n.º 1
0
    date = models.DateTimeField(
        verbose_name=_('date'), db_column='authdate', auto_now_add=True
    )

    class Meta:
        db_table = 'radpostauth'
        verbose_name = _('post auth')
        verbose_name_plural = _('post auth log')
        abstract = True

    def __str__(self):
        return str(self.username)


_get_csv_file_private_storage = PrivateFileSystemStorage(
    location=settings.PRIVATE_STORAGE_ROOT,
    base_url=urljoin(app_settings.RADIUS_API_BASEURL, app_settings.CSV_URL_PATH),
)


def _get_csv_file_location(instance, filename):
    return os.path.join(str(instance.organization.pk), filename)


class AbstractRadiusBatch(OrgMixin, TimeStampedEditableModel):
    strategy = models.CharField(
        _('strategy'),
        max_length=16,
        choices=_STRATEGIES,
        db_index=True,
        help_text=_('Import users from a CSV or generate using a prefix'),
    )
Ejemplo n.º 2
0
class AbstractFirmwareImage(TimeStampedEditableModel):
    build = models.ForeignKey(get_model_name('Build'),
                              on_delete=models.CASCADE)
    file = PrivateFileField(
        'File',
        upload_to=get_build_directory,
        max_file_size=app_settings.MAX_FILE_SIZE,
        storage=PrivateFileSystemStorage(
            base_url=urljoin(FIRMWARE_API_BASEURL, IMAGE_URL_PATH)),
    )
    type = models.CharField(
        blank=True,
        max_length=128,
        choices=FIRMWARE_IMAGE_TYPE_CHOICES,
        help_text=_('firmware image type: model or '
                    'architecture. Leave blank to attempt '
                    'determining automatically'),
    )

    class Meta:
        abstract = True
        verbose_name = _('Firmware Image')
        verbose_name_plural = _('Firmware Images')
        unique_together = ('build', 'type')

    def __str__(self):
        if hasattr(self, 'build') and self.type:
            return f'{self.build}: {self.get_type_display()}'
        return super().__str__()

    @property
    def boards(self):
        return FIRMWARE_IMAGE_MAP[self.type]['boards']

    def clean(self):
        self._clean_type()
        try:
            self.boards
        except KeyError:
            raise ValidationError(
                {'type': 'Could not find boards for this type'})

    def delete(self, *args, **kwargs):
        super().delete(*args, **kwargs)
        self._remove_file()
        self._remove_empty_directory()

    def _clean_type(self):
        """
        auto determine type if missing
        """
        if self.type:
            return
        filename = self.file.name
        # removes leading prefix
        self.type = '-'.join(filename.split('-')[1:])

    def _remove_file(self):
        path = self.file.path
        if os.path.isfile(path):
            os.remove(path)
        else:
            msg = 'firmware image not found while deleting {0}:\n{1}'
            logger.error(msg.format(self, path))

    def _remove_empty_directory(self):
        path = os.path.dirname(self.file.path)
        # TODO: precauton when migrating to private storage
        # avoid accidentally deleting the MEDIA_ROOT dir
        # remove this before or after first release
        is_media_root = Path(path).absolute() != Path(
            settings.MEDIA_ROOT).absolute()
        if not os.listdir(path) and is_media_root:
            os.rmdir(path)
Ejemplo n.º 3
0
    date = models.DateTimeField(verbose_name=_('date'),
                                db_column='authdate',
                                auto_now_add=True)

    class Meta:
        db_table = 'radpostauth'
        verbose_name = _('post auth')
        verbose_name_plural = _('post auth log')
        abstract = True

    def __str__(self):
        return str(self.username)


_get_csv_file_private_storage = PrivateFileSystemStorage(
    location=settings.PRIVATE_STORAGE_ROOT,
    base_url='/radiusbatch/csv/',
)


def _get_csv_file_location(instance, filename):
    return os.path.join(str(instance.organization.pk), filename)


class AbstractRadiusBatch(OrgMixin, TimeStampedEditableModel):
    strategy = models.CharField(
        _('strategy'),
        max_length=16,
        choices=_STRATEGIES,
        db_index=True,
        help_text=_('Import users from a CSV or generate using a prefix'),
    )
Ejemplo n.º 4
0
from cryptography.fernet import Fernet
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
from django.template.defaultfilters import slugify
from django.utils.timezone import now
from encrypted_model_fields.fields import EncryptedCharField
from ckeditor_uploader.fields import RichTextUploadingField
from private_storage.fields import PrivateFileField
from private_storage.storage.files import PrivateFileSystemStorage
from simple_history.models import HistoricalRecords

storage2 = PrivateFileSystemStorage(
    location='/home/ubuntu/tesis/media/group-private/',
    base_url='/group-private/'
)


class CommonInfo(models.Model):
    created_at = models.DateTimeField("created_at", default=now, blank=True)
    last_modified_at = models.DateTimeField("last_modified_at", default=now, blank=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name="Created by", related_name="%(app_label)s_%(class)s_created", on_delete=models.CASCADE, null=True, blank=True)
    last_modified_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name="Last modified by", related_name="%(app_label)s_%(class)s_last_modified", on_delete=models.CASCADE, null=True, blank=True)

    def save(self, *args, **kwargs):
        if not self.created_at:
            self.created_at = now()
        self.last_modified_at = now()
        super(CommonInfo, self).save(*args, **kwargs)
Ejemplo n.º 5
0
class Migration(migrations.Migration):

    dependencies = [
        ('persons', '0004_family'),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Attendee',
            fields=[
                ('user',
                 models.OneToOneField(blank=True,
                                      default=None,
                                      null=True,
                                      on_delete=models.deletion.SET_NULL,
                                      to=settings.AUTH_USER_MODEL)),
                ('id',
                 model_utils.fields.UUIDField(default=uuid4,
                                              editable=False,
                                              primary_key=True,
                                              serialize=False)),
                ('created',
                 model_utils.fields.AutoCreatedField(
                     default=django.utils.timezone.now,
                     editable=False,
                     verbose_name='created')),
                ('modified',
                 model_utils.fields.AutoLastModifiedField(
                     default=django.utils.timezone.now,
                     editable=False,
                     verbose_name='modified')),
                ('is_removed', models.BooleanField(default=False)),
                ('first_name',
                 models.CharField(blank=True,
                                  db_index=True,
                                  max_length=25,
                                  null=True)),
                ('last_name',
                 models.CharField(blank=True,
                                  db_index=True,
                                  max_length=25,
                                  null=True)),
                ('first_name2',
                 models.CharField(blank=True,
                                  db_index=True,
                                  max_length=12,
                                  null=True)),
                ('last_name2',
                 models.CharField(blank=True,
                                  db_index=True,
                                  max_length=8,
                                  null=True)),
                ('gender',
                 models.CharField(choices=GenderEnum.choices(),
                                  default=GenderEnum.UNSPECIFIED,
                                  max_length=11)),
                ('actual_birthday', models.DateField(blank=True, null=True)),
                ('estimated_birthday', models.DateField(blank=True,
                                                        null=True)),
                ('deathday', models.DateField(blank=True, null=True)),
                ('progressions',
                 JSONField(
                     blank=True,
                     default=dict,
                     help_text=
                     'Example: {"Christian": true, "baptized": {"time": "12/31/2020", "place":"SF"}}. Please keep {} here even no data',
                     null=True)),
                ('photo',
                 PrivateFileField(blank=True,
                                  null=True,
                                  storage=PrivateFileSystemStorage(),
                                  upload_to='attendees',
                                  verbose_name='Photo')),
                ('infos',
                 JSONField(
                     blank=True,
                     default=dict,
                     help_text=
                     'Example: {"food allergy": "peanuts", "public_name": "John", "other_name": "Apostle"}. Please keep {} here even no data',
                     null=True)),
            ],
            options={
                'db_table': 'persons_attendees',
                'ordering': ['last_name', 'first_name'],
            },
            bases=(utility.Utility, models.Model),
        ),
        migrations.AddIndex(
            model_name='attendee',
            index=django.contrib.postgres.indexes.GinIndex(
                fields=['infos'], name='attendee_infos_gin'),
        ),
        migrations.AddIndex(
            model_name='attendee',
            index=django.contrib.postgres.indexes.GinIndex(
                fields=['progressions'], name='attendee_progressions_gin'),
        ),
    ]
Ejemplo n.º 6
0
class PrivateStreamformStorageView(PrivateStorageView):
    storage = PrivateFileSystemStorage(location=os.path.join(
        settings.BASE_DIR, 'media/streamforms/'),
                                       base_url='/media/streamforms/')
Ejemplo n.º 7
0
from django.db import models
from django.dispatch import receiver
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.utils.timezone import now
from django.conf import settings
from private_storage.storage.files import PrivateFileSystemStorage
from simple_history.models import HistoricalRecords
from django.template.defaultfilters import slugify
from encrypted_model_fields.fields import EncryptedCharField
from ckeditor_uploader.fields import RichTextUploadingField
from private_storage.fields import PrivateFileField


storage1 = PrivateFileSystemStorage(
    location='/home/ubuntu/tesis/media/user-private/',
    base_url='/user-private/'
)


def custom_upload_to(instance, filename):
    old_instance = Profile.objects.get(pk=instance.pk)
    old_instance.avatar.delete()
    return 'profiles/' + filename


class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    avatar = models.ImageField(upload_to=custom_upload_to, null=True, blank=True)
    birthday = models.DateField(null=True, blank=True)
    job = models.CharField(max_length=50, blank=True, null=True)
Ejemplo n.º 8
0
class Migration(migrations.Migration):

    dependencies = [
        ('persons', '0005_family'),
        ('whereabouts', '0004_division'),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Attendee',
            fields=[
                ('id',
                 model_utils.fields.UUIDField(default=uuid4,
                                              editable=False,
                                              primary_key=True,
                                              serialize=False)),
                ('user',
                 models.OneToOneField(blank=True,
                                      default=None,
                                      null=True,
                                      on_delete=models.deletion.SET_NULL,
                                      to=settings.AUTH_USER_MODEL)),
                ('created',
                 model_utils.fields.AutoCreatedField(
                     default=django.utils.timezone.now,
                     editable=False,
                     verbose_name='created')),
                ('modified',
                 model_utils.fields.AutoLastModifiedField(
                     default=django.utils.timezone.now,
                     editable=False,
                     verbose_name='modified')),
                ('is_removed', models.BooleanField(default=False)),
                ('division',
                 models.ForeignKey(default=0,
                                   blank=False,
                                   null=False,
                                   on_delete=models.SET(0),
                                   to='whereabouts.Division')),
                ('actual_birthday', models.DateField(blank=True, null=True)),
                ('estimated_birthday', models.DateField(blank=True,
                                                        null=True)),
                ('deathday', models.DateField(blank=True, null=True)),
                ('first_name',
                 models.CharField(blank=True,
                                  db_index=True,
                                  max_length=25,
                                  null=True)),
                ('last_name',
                 models.CharField(blank=True,
                                  db_index=True,
                                  max_length=25,
                                  null=True)),
                ('first_name2',
                 models.CharField(blank=True,
                                  db_index=True,
                                  max_length=12,
                                  null=True)),
                ('last_name2',
                 models.CharField(blank=True,
                                  db_index=True,
                                  max_length=8,
                                  null=True)),
                ('gender',
                 models.CharField(choices=GenderEnum.choices(),
                                  default=GenderEnum.UNSPECIFIED,
                                  max_length=11)),
                ('photo',
                 PrivateFileField(blank=True,
                                  null=True,
                                  storage=PrivateFileSystemStorage(),
                                  upload_to='attendee_portrait',
                                  verbose_name='Photo')),
                ('progressions',
                 JSONField(
                     blank=True,
                     default=dict,
                     help_text=
                     'Example: {"Christian": true, "baptized": {"time": "12/31/2020", "place":"SF"}}. Please keep {} here even no data',
                     null=True)),
                ('infos',
                 JSONField(
                     blank=True,
                     null=True,
                     default=Utility.attendee_infos,
                     help_text=
                     'Example: {"fixed": {"food_pref": "peanut allergy", "nick_name": "John"}}. Please keep {} here even no data'
                 )),
            ],
            options={
                'db_table': 'persons_attendees',
                'ordering': ['last_name', 'first_name'],
            },
            bases=(Utility, models.Model),
        ),
        # migrations.RunSQL(
        #     sql="""
        #         ALTER TABLE persons_attendees DROP COLUMN full_name;
        #         ALTER TABLE persons_attendees ADD COLUMN full_name VARCHAR(70)
        #               GENERATED ALWAYS AS (TRIM(
        #                 COALESCE(first_name, '') || ' ' ||
        #                 COALESCE(last_name, '')  || ' ' ||
        #                 COALESCE(last_name2, '')   ||
        #                 COALESCE(first_name2, '')
        #               )) STORED;
        #         CREATE INDEX attendee_full_name_raw
        #           ON persons_attendees (full_name);
        #         """,
        #     # reverse_sql="",
        # ),  # switching to use opencc for language conversion in Attendee.save()
        migrations.AddIndex(
            model_name='attendee',
            index=django.contrib.postgres.indexes.GinIndex(
                fields=['infos'], name='attendee_infos_gin'),
        ),
        migrations.AddIndex(
            model_name='attendee',
            index=django.contrib.postgres.indexes.GinIndex(
                fields=['progressions'], name='attendee_progressions_gin'),
        ),
    ]