示例#1
0
class Migration(migrations.Migration):

    dependencies = [
        ("ui", "0030_edxendpoint_expires_in"),
    ]

    operations = [
        migrations.RunPython(assign_collection_endpoints_from_global_default,
                             migrations.RunPython.noop),
        migrations.AddField(
            model_name="edxendpoint",
            name="client_id",
            field=models.CharField(max_length=512, null=True),
        ),
        migrations.AddField(
            model_name="edxendpoint",
            name="secret_key",
            field=models.CharField(max_length=512, null=True),
        ),
        migrations.RunPython(set_client_id_and_secret_key,
                             migrations.RunPython.noop),
        migrations.AlterField(
            model_name="edxendpoint",
            name="client_id",
            field=EncryptedCharField(max_length=100),
        ),
        migrations.AlterField(
            model_name="edxendpoint",
            name="secret_key",
            field=EncryptedCharField(max_length=100),
        ),
    ]
示例#2
0
class CredentialsFieldsMixin(models.Model):
    class Meta:
        abstract = True

    username = models.CharField(verbose_name="Username",
                                max_length=50,
                                blank=True)
    password = EncryptedCharField(verbose_name="Password",
                                  max_length=50,
                                  blank=True)
    domain = models.CharField(verbose_name="Domain", max_length=50, blank=True)

    private_key = models.TextField(verbose_name="Private Key", blank=True)
    passphrase = EncryptedCharField(verbose_name="Passphrase",
                                    blank=True,
                                    max_length=32)

    # save password on init,
    # so we know how to revert on saving provided blank password
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.cred_password_original = self.password

        # check if provided password is blank. If it is, save old password

    def save(self, *args, **kwargs):
        if not self.password:
            self.password = self.cred_password_original

        super().save(*args, **kwargs)
示例#3
0
class SalesforceOrg(models.Model):
    org_id = models.CharField(primary_key=True, max_length=64)
    org_name = models.CharField(max_length=256)
    instance_url = models.URLField(max_length=512, blank=True)
    access_token = EncryptedCharField(
        max_length=256,
        null=True,
        help_text='Salesforce connected app oauth access token.',
    )
    refresh_token = EncryptedCharField(
        max_length=256,
        null=True,
        help_text='Salesforce connected app refresh access token.',
    )
    package_version = models.CharField(max_length=8, blank=True, default='1.0')
    created_at = models.DateTimeField(auto_now=False, auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True, auto_now_add=False)

    objects = MyModelManager()

    class Meta:
        ordering = ['org_name']
        get_latest_by = 'created_date'
        verbose_name_plural = 'Salesforce Organizations'

    def __str__(self):
        result = [
            f'Org Id: {self.org_id}',
            f'Org Name: {self.org_name}',
            f'Org Instance URL: {self.instance_url}',
            f'Package version installed: {self.package_version}',
        ]
        return ', '.join((str(x) for x in result))
class Profile(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE)
    consumer_key =  EncryptedCharField(max_length=50, blank=True)
    consumer_secret = EncryptedCharField(max_length=50, blank=True)
    access_token = EncryptedCharField(max_length=50, blank=True)
    access_token_secret = EncryptedCharField(max_length=50, blank=True)

    def __str__(self):
        return 'Profile: ' + self.user.username
示例#5
0
class InstapaperCredentials(models.Model):
    oauth_token = EncryptedCharField(_('Password'), max_length=255, null=True)
    oauth_token_secret = EncryptedCharField(_('Password'),
                                            max_length=255,
                                            null=True)
    owner = models.OneToOneField(User, on_delete=models.CASCADE)
    last_polled = models.DateTimeField(default=None, null=True)
    polled_bookmarks = JSONField(null=True, default=dict)
    invalid = models.NullBooleanField(null=True, default=None)
示例#6
0
class BillingInfo(models.Model):
    delivery_address = models.OneToOneField(Address,
                                            on_delete=models.CASCADE,
                                            default=None,
                                            null=True)
    stripe_customer_id = EncryptedCharField(max_length=100, null=True)
    stripe_subscription_id = EncryptedCharField(max_length=100, null=True)
    customer = models.ForeignKey(User,
                                 on_delete=models.CASCADE,
                                 db_column='customer')
示例#7
0
class Profile(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    consumer_key = EncryptedCharField(max_length=50, blank=True)
    consumer_secret = EncryptedCharField(max_length=50, blank=True)
    access_token = EncryptedCharField(max_length=50, blank=True)
    access_token_secret = EncryptedCharField(max_length=50, blank=True)
    social_platform = models.TextField(max_length=50)

    def __str__(self):
        return 'Profile: ' + self.user.username
示例#8
0
class ExchangeAccount(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    exchange = models.ForeignKey(Exchange, on_delete=models.CASCADE)
    key = EncryptedCharField(max_length=1024)
    secret = EncryptedCharField(max_length=1024)
    passphrase = EncryptedCharField(max_length=1024,
                                    default=None,
                                    blank=True,
                                    null=True,
                                    help_text='<ul><li>Optional</li></ul>')

    def __str__(self):
        return "%s %s" % (self.user.username, self.exchange.label)
示例#9
0
class Instance(models.Model):
    system = models.ForeignKey(System, on_delete=models.PROTECT)
    environment = models.ForeignKey(Environment, on_delete=models.PROTECT)
    host = models.CharField(max_length=100, null=True, blank=True)
    port = models.IntegerField(null=True, blank=True)
    db = models.CharField(max_length=100, null=True, blank=True)
    schema = models.CharField(max_length=100, null=True, blank=True)
    login = models.CharField(max_length=100, null=True, blank=True)
    password = EncryptedCharField(max_length=100, null=True, blank=True)
    extra_json = models.JSONField(null=True, blank=True)
    unique_together = ((system, environment), )

    class Meta:
        ordering = ("-pk", )

    def __unicode__(self):
        return "%s" % self.pk

    def get_url(self, action):
        return reverse(f"systems:instance_{action}", args=(self.pk, ))

    def get_absolute_url(self):
        self.get_url("update")

    def get_name(self):
        return f"{self.system.name} / {self.environment.name}"
示例#10
0
class AWS(models.Model):
    identifier = models.CharField(max_length=255, unique=True)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    region = models.CharField(max_length=255, default='eu-west-1')
    access_key = EncryptedCharField(max_length=255,
                                    help_text='database encrypted',
                                    blank=True,
                                    null=True)
    secret_key = EncryptedCharField(
        max_length=255,
        help_text='database encrypted and hidden from display',
        blank=True,
        null=True)

    def __str__(self):
        return self.identifier
示例#11
0
文件: models.py 项目: nbrowning1/FYP
class EncryptedUser(AbstractUser):
    """Encrypted user override for Django's AbstractUser model, to wrap certain fields as encrypted."""

    # Field definitions are lifted directly from AbstractUser, and just wrapped in EncryptedFields
    first_name = EncryptedCharField(_('first name'), max_length=30, blank=True)
    last_name = EncryptedCharField(_('last name'), max_length=30, blank=True)
    email = EncryptedEmailField(_('email address'), blank=True)

    # Required because of encrypted email field - can't perform direct get() as usual so requires iteration
    @staticmethod
    def get_by_email(email):
        for user in EncryptedUser.objects.all():
            # Case-insensitive matching
            if email.lower() == user.email.lower():
                return user
        return None
示例#12
0
class Notebook(models.Model):
    uuid = models.UUIDField(default=uuid.uuid4, editable=False)
    name = EncryptedCharField(max_length=200)
    content = EncryptedCharField(max_length=20000, null=True)
    folder = models.ForeignKey(Folder,
                               on_delete=models.CASCADE,
                               related_name='folder_notebook_set')
    creator = models.ForeignKey(MyUser,
                                on_delete=models.CASCADE,
                                related_name='creator_notebook_set')
    employee = models.ManyToManyField(MyUser,
                                      related_name='employee_notebook_set')
    lastChange = models.DateTimeField(auto_now=True)

    def __str__(self):
        return "%s %s %s" % (self.name, self.folder, self.creator)
示例#13
0
class Secret(models.Model):
    computer = models.ForeignKey(Computer, on_delete=models.CASCADE)
    secret = EncryptedCharField(max_length=256)
    secret_type = models.CharField(max_length=256,
                                   choices=SECRET_TYPES,
                                   default="recovery_key")
    date_escrowed = models.DateTimeField(auto_now_add=True)
    rotation_required = models.BooleanField(default=False)

    def validate_unique(self, *args, **kwargs):
        if (self.secret in [
                str(s) for s in self.__class__.objects.filter(
                    secret_type=self.secret_type, computer=self.computer)
        ] and not self.rotation_required):
            raise ValidationError("already used")
        super(Secret, self).validate_unique(*args, **kwargs)

    def save(self, *args, **kwargs):
        self.validate_unique()
        super(Secret, self).save(*args, **kwargs)

    def __str__(self):
        return self.secret

    class Meta:
        ordering = ["-date_escrowed"]
示例#14
0
class Key(CommonInfo):
    name = models.CharField(verbose_name="Name", max_length=50)
    username = models.CharField(verbose_name="Username", max_length=50, blank=True, null=True)
    password = EncryptedCharField(verbose_name="Password", max_length=50, blank=True, null=True)
    note = models.CharField(verbose_name="Note", max_length=200, blank=True, null=True)
    url = models.CharField(verbose_name="URL", max_length=50, blank=True, null=True)
    file = PrivateFileField("File", storage=storage2, upload_to=upload_key, blank=True, null=True)
    set = models.ForeignKey(Set, on_delete=models.CASCADE)
    slug = models.SlugField()
    history = HistoricalRecords()

    class Meta:
        verbose_name = "Key"
        verbose_name_plural = "Keys"
        ordering = ['last_modified_at']

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Key, self).save(*args, **kwargs)
        if self.file:
            input_file = self.file.path
            output_file = self.file.path
            with open(input_file, 'rb') as f:
                data = f.read()
            fernet = Fernet(settings.SECRET_KEY)
            encrypted = fernet.encrypt(data)
            with open(output_file, 'wb') as f:
                f.write(encrypted)
示例#15
0
class CustomUser(AbstractUser):
    # add additional fields in here
    secret_santa_of = EncryptedCharField(max_length=128, null="True")

    def __str__(self):
        return self.email

    pass
示例#16
0
class TMS(models.Model):
    """This class represents the TMS account model.

    TODO: avoid duplicate endpoint/password combinations."""
    owner = models.ForeignKey('auth.User',
                              related_name='TMSAccounts',
                              on_delete=models.CASCADE)
    endpoint = models.CharField(max_length=60)
    username = models.CharField(max_length=60, null=True)
    password = EncryptedCharField(max_length=60, null=True)
    access_token = EncryptedCharField(max_length=2048, null=True)
    type = models.CharField(max_length=20, choices=TMSlib.TMS_TYPES)
    connectivity_status = JSONField(null=True)
    name = models.CharField(max_length=60, null=True)
    params = JSONField(null=True)

    def __str__(self):
        return "{}@{}".format(self.username, self.endpoint)
示例#17
0
class CalUser(models.Model):
    # TODO: Encrypt these fields
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    username = models.CharField(max_length=250)
    password = EncryptedCharField(max_length=250)
    token = models.CharField(max_length=500, null=True, blank=True)

    def __str__(self):
        return self.username
示例#18
0
class CustomerRawPassword(BaseAbstractModel):
    customer = models.OneToOneField(Customer, models.CASCADE)
    passw_text = EncryptedCharField(max_length=64)

    def __str__(self):
        return f"{self.customer} - {self.passw_text}"

    class Meta:
        db_table = "customer_raw_password"
示例#19
0
class Option(models.Model):
    parameter = models.CharField(max_length=255, primary_key=True)
    value     = EncryptedCharField(max_length=255, default='')

    def __str__(self):
        return self.parameter

    def get_bool_value(self):
        return self.value.lower() in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh']
class Migration(migrations.Migration):

    dependencies = [
        ('students', '0027_auto_20180819_1047'),
    ]

    operations = [
        migrations.AddField(
            model_name='student',
            name='temp_dob',
            field=models.DateField(verbose_name='Temp dob',
                                   null=True,
                                   blank=True,
                                   help_text='Format: MM-DD-YYYY'),
        ),
        migrations.AddField(
            model_name='student',
            name='temp_name',
            field=models.CharField(null=True,
                                   max_length=255,
                                   verbose_name='Full Name'),
        ),
        migrations.AlterField(
            model_name='student',
            name='name',
            field=models.CharField(null=True,
                                   max_length=255,
                                   verbose_name='Full Name'),
        ),
        migrations.RunPython(replicate_to_temporary),
        migrations.AlterField(
            model_name='student',
            name='dob',
            field=EncryptedDateField(verbose_name='dob',
                                     null=True,
                                     blank=True,
                                     help_text='Format: MM-DD-YYYY'),
        ),
        migrations.AlterField(
            model_name='student',
            name='name',
            field=EncryptedCharField(null=True,
                                     max_length=255,
                                     verbose_name='Full Name'),
        ),
        migrations.RunPython(replicate_to_real),
        migrations.RemoveField(model_name='student', name='temp_dob'),
        migrations.RemoveField(model_name='student', name='temp_name'),
        migrations.AlterField(
            model_name='student',
            name='name',
            field=models.CharField(null=False,
                                   max_length=255,
                                   verbose_name='Full Name'),
        )
    ]
示例#21
0
文件: models.py 项目: kpn/katka-core
class CredentialSecret(AuditedModel):
    key = models.CharField(max_length=50)
    value = EncryptedCharField(max_length=200)
    credential = models.ForeignKey(Credential, on_delete=models.CASCADE)

    class Meta:
        unique_together = ("credential", "key")

    def __str__(self):  # pragma: no cover
        return f"{self.credential.name}/{self.key}"
示例#22
0
class User(AbstractUser):
    username = models.TextField(unique=True)
    first_name = models.TextField()
    last_name = models.TextField()
    password = EncryptedCharField(max_length=100)
    email = models.EmailField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now_add=True)

    def publish(self):
        self.save()
示例#23
0
class Site(models.Model):
    name = models.CharField(max_length=200)
    login_url = models.URLField()
    username = models.CharField(max_length=200)
    username_label = models.CharField(max_length=200, default='username')
    password = EncryptedCharField(max_length=200)
    password_label = models.CharField(max_length=200, default='password')
    success = models.CharField(max_length=255)

    def __str__(self):
        return str(self.name)
示例#24
0
class Gateway(BaseAbstractModel):
    title = models.CharField(_("Title"), max_length=127, unique=True)
    ip_address = models.GenericIPAddressField(_("Ip address"), unique=True)
    ip_port = models.PositiveSmallIntegerField(_("Port"))
    auth_login = models.CharField(_("Auth login"), max_length=64)
    auth_passw = EncryptedCharField(_("Auth password"), max_length=127)
    gw_type = models.PositiveSmallIntegerField(
        _("Type"), choices=MyChoicesAdapter(GATEWAY_TYPES), default=0)
    is_default = models.BooleanField(_("Is default"), default=False)
    enabled = models.BooleanField(_("Enabled"), default=True)
    sites = models.ManyToManyField(Site, blank=True)

    def get_gw_manager(self) -> GatewayFacade:
        try:
            if hasattr(self, "_gw_mngr"):
                o = getattr(self, "_gw_mngr")
            else:
                o = GatewayFacade(
                    self.gw_type,
                    login=self.auth_login,
                    password=self.auth_passw,
                    ip=self.ip_address,
                    port=int(self.ip_port),
                    enabled=bool(self.enabled),
                )
                setattr(self, "_gw_mngr", o)
            return o
        except ConnectionResetError:
            raise GatewayNetworkError("ConnectionResetError")

    @staticmethod
    def get_user_credentials_by_gw(gw_id: int):
        with connection.cursor() as cur:
            cur.execute(
                "SELECT * FROM "
                "fetch_customers_srvnet_credentials_by_gw(%s::integer)",
                (str(gw_id), ))
            while True:
                # (customer_id, lease_id, lease_time, lease_mac, ip_address,
                #  speed_in, speed_out, speed_burst, service_start_time,
                #  service_deadline)
                customer_id, *other = cur.fetchone()
                if customer_id is None:
                    break
                yield [customer_id] + other

    def __str__(self):
        return self.title

    class Meta:
        db_table = "gateways"
        verbose_name = _("Network access server. Gateway")
        verbose_name_plural = _("Network access servers. Gateways")
        ordering = ("ip_address", )
示例#25
0
文件: models.py 项目: aradnaev/pmp
class TMS(models.Model):
    """This class represents the TMS account model."""
    owner = models.ForeignKey('auth.User',
                              related_name='TMSAccounts',
                              on_delete=models.CASCADE)
    endpoint = models.CharField(max_length=60)
    username = models.CharField(max_length=60, null=True)
    password = EncryptedCharField(max_length=60, null=True)
    type = models.CharField(max_length=20, choices=TMSlib.TMS_TYPES)
    connectivity_status = JSONField(null=True)
    name = models.CharField(max_length=60, null=True)
    params = JSONField(null=True)
    oauth2_token = models.ForeignKey(OAuth2Token,
                                     on_delete=models.CASCADE,
                                     null=True)

    def __str__(self):
        return "{}@{}".format(self.username, self.endpoint)

    def get_fresh_token(self):
        token = self.oauth2_token
        logger.debug('initial token: {}'.format(token))
        logger.debug('initial token vars: {}'.format(vars(token)))
        token_dict = token.to_token()
        logger.debug('initial token dict: {}'.format(token_dict))
        logger.info('priming TMS GET with oauth...')
        res = oauth.atlassian.get(Atlassian_API.ATLASSIAN_CLOUD_PROFILE,
                                  token=token_dict)
        logger.info('got oauth.atlassian result')
        logger.debug(res)
        logger.debug(vars(res))
        logger.debug('before TMS refresh from db self.oauth2_token: {}'.format(
            self.oauth2_token))
        logger.debug(
            'before TMS refresh from db vars self.oauth2_token: {}'.format(
                vars(self.oauth2_token)))
        logger.debug('before TMS refresh from db token vars: {}'.format(
            vars(token)))

        logger.debug('refreshing TMS from db')
        self.refresh_from_db()
        logger.debug('after refreshing from db self.oauth2_token: {}'.format(
            self.oauth2_token))
        logger.debug(
            'after refreshing from db vars self.oauth2_token: {}'.format(
                vars(self.oauth2_token)))
        logger.debug('after refreshing from db token vars: {}'.format(
            vars(token)))

        logger.debug('reassigning token to self.oauth2_token...')
        token = self.oauth2_token
        logger.debug('token vars: {}'.format(vars(token)))
        return token
示例#26
0
class TMS(models.Model):
    """This class represents the TMS account model."""
    owner = models.ForeignKey('auth.User',
                              related_name='TMSAccounts',
                              on_delete=models.CASCADE)
    endpoint = models.CharField(max_length=60)
    username = models.CharField(max_length=60)
    password = EncryptedCharField(max_length=60)
    type = models.CharField(max_length=20, choices=TMSlib.TMS_TYPES)

    def __str__(self):
        return "{}@{}".format(self.username, self.endpoint)
示例#27
0
class Credentials(models.Model):
    id = models.AutoField(db_column='id', primary_key=True)
    email = models.CharField(db_column='email', max_length=510)
    username = models.CharField(db_column='username', max_length=255)
    password = EncryptedCharField(db_column='password', max_length=255)

    class Meta:
        managed = True
        db_table = 'credentials'

    def __str__(self):
        return "Credentials: %s" % self.id
示例#28
0
class SlackIntegration(models.Model):
    id           = models.AutoField(primary_key=True)
    user         = models.ForeignKey(FeedUser, related_name='rel_slack_integrations', on_delete=models.CASCADE)
    team_name    = models.CharField(max_length=100, blank=False, null=False)
    channels     = models.CharField(max_length=100, blank=True, null=True, default="")
    access_token = EncryptedCharField(max_length=500, blank=False, null=False)

    class Meta:
        unique_together = (("team_name", "user"),)

    def __str__(self):
        return self.team_name + " // " + self.user.username
示例#29
0
class EmailToken(models.Model):

    challenge_email_address = models.EmailField()
    challenge_token = EncryptedCharField(max_length=255,
                                         default=random_hex,
                                         validators=[token_validator])
    challenge_generation_timestamp = models.DateTimeField(null=True,
                                                          blank=True,
                                                          auto_now_add=True,
                                                          editable=False)
    challenge_expiration_timestamp = models.DateTimeField(
        null=True, blank=True, default=get_challenge_expiration_timestamp)
    challenge_completed = models.BooleanField(default=False)
    challenge_completed_timestamp = models.DateTimeField(null=True, blank=True)
    token_expiration_timestamp = models.DateTimeField(null=True, blank=True)

    # Relationship Fields
    user = models.ForeignKey(get_user_model(),
                             related_name='user_email_tokens',
                             on_delete=models.CASCADE)

    def __repr__(self):
        return f"<EmailToken(id={self.id}, user_id={self.user_id}, user='******')>"

    def __str__(self):
        return self.__repr__()

    def save(self, *args, **kwargs):
        if not self._state.adding and self.challenge_completed:
            self.challenge_completed_timestamp = timezone.now()
            self.token_expiration_timestamp = timezone.now() + timedelta(
                seconds=settings.EMAIL_TOKEN_EXPIRATION_IN_SECS)
            self.challenge_expiration_timestamp = self.token_expiration_timestamp
        return super().save(*args, **kwargs)

    @property
    def is_challenge_within_expiry(self) -> bool:
        """"
        Returns whether email token is within its challenge expiration date
        """
        if not self.challenge_expiration_timestamp:
            return False
        return timezone.now() <= self.challenge_expiration_timestamp

    @property
    def is_token_within_expiry(self) -> bool:
        """"
        Returns whether email token is within its token expiration date
        """
        if not self.token_expiration_timestamp:
            return False
        return timezone.now() <= self.token_expiration_timestamp
示例#30
0
class Wallet(models.Model):
    """
    NOTE!! Since private_key is encrypted no filtering of any sort works on it
    If you need to query for specific wallets, use their address for the query
    """
    private_key = EncryptedCharField(max_length=66,
                                     unique=True,
                                     blank=False,
                                     null=False)
    address = models.CharField(max_length=42,
                               unique=True,
                               blank=False,
                               null=False)