index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
38,319 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/admin/migrations/0002_migrate_from_modoboa_admin.py | 4,5 | 1,38 | rename_and_clean | 6,28 | 5,28 | from django.db import models, migrations
def rename_and_clean(apps, schema_editor):
FILL_FUNC_BODYclass Migration(migrations.Migration):
dependencies = [
("admin", "0001_initial"),
("contenttypes", "0002_remove_content_type_name"),
]
operations = [
migrations.RunPython(rename_and... | from django.db import models, migrations
def rename_and_clean(apps, schema_editor):
"""Rename old content types if necessary, remove permissions."""
FILL_FUNC_BODYclass Migration(migrations.Migration):
dependencies = [
("admin", "0001_initial"),
("contenttypes", "0002_remove_content_type_name... | ContentType = apps.get_model("contenttypes", "ContentType")
for ct in ContentType.objects.filter(app_label="admin"):
try:
old_ct = ContentType.objects.get(app_label="modoboa_admin", model=ct.model)
except ContentType.DoesNotExist:
continue
old_ct.app_label = "admi... | """Rename old content types if necessary, remove permissions."""
ContentType = apps.get_model("contenttypes", "ContentType")
for ct in ContentType.objects.filter(app_label="admin"):
try:
old_ct = ContentType.objects.get(app_label="modoboa_admin", model=ct.model)
except ContentTyp... | 52 | 130 | 276 | 406 | from django.db import models, migrations
def rename_and_clean(apps, schema_editor):
FILL_FUNC_BODYclass Migration(migrations.Migration):
dependencies = [
("admin", "0001_initial"),
("contenttypes", "0002_remove_content_type_name"),
]
operations = [
migrations.RunPython(rename_and... | from django.db import models, migrations
def rename_and_clean(apps, schema_editor):
"""Rename old content types if necessary, remove permissions."""
FILL_FUNC_BODYclass Migration(migrations.Migration):
dependencies = [
("admin", "0001_initial"),
("contenttypes", "0002_remove_content_type_name... | |
38,320 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/admin/migrations/0006_auto_20161104_1900.py | 6,7 | 1,68 | move_dates | 8,19 | 7,19 | # Generated by Django 1.9.5 on 2016-11-04 18:00
from django.db import migrations, models
import django.utils.timezone
def move_dates(apps, schema_editor):
FILL_FUNC_BODYclass Migration(migrations.Migration):
dependencies = [
("admin", "0005_auto_20161026_1003"),
]
operations = [
migratio... | # Generated by Django 1.9.5 on 2016-11-04 18:00
from django.db import migrations, models
import django.utils.timezone
def move_dates(apps, schema_editor):
"""Move dates to models."""
FILL_FUNC_BODYclass Migration(migrations.Migration):
dependencies = [
("admin", "0005_auto_20161026_1003"),
]
... | Domain = apps.get_model("admin", "Domain")
DomainAlias = apps.get_model("admin", "DomainAlias")
Mailbox = apps.get_model("admin", "Mailbox")
Alias = apps.get_model("admin", "Alias")
for model in [Domain, DomainAlias, Mailbox, Alias]:
for instance in model.objects.all():
instance.... | """Move dates to models."""
Domain = apps.get_model("admin", "Domain")
DomainAlias = apps.get_model("admin", "DomainAlias")
Mailbox = apps.get_model("admin", "Mailbox")
Alias = apps.get_model("admin", "Alias")
for model in [Domain, DomainAlias, Mailbox, Alias]:
for instance in model.obje... | 34 | 520 | 149 | 669 | # Generated by Django 1.9.5 on 2016-11-04 18:00
from django.db import migrations, models
import django.utils.timezone
def move_dates(apps, schema_editor):
FILL_FUNC_BODYclass Migration(migrations.Migration):
dependencies = [
("admin", "0005_auto_20161026_1003"),
]
operations = [
migratio... | # Generated by Django 1.9.5 on 2016-11-04 18:00
from django.db import migrations, models
import django.utils.timezone
def move_dates(apps, schema_editor):
"""Move dates to models."""
FILL_FUNC_BODYclass Migration(migrations.Migration):
dependencies = [
("admin", "0005_auto_20161026_1003"),
]
... | |
38,321 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/admin/migrations/0015_rename_view_permissions.py | 14,15 | 1,45 | rename_view_permissions | 15,36 | 15,36 | # Generated by Django 2.1.15 on 2020-01-13 09:22
import sys
from django.db import IntegrityError, migrations, transaction
VIEW_PERMISSION_CODENAMES = {
"view_aliases": "view_alias",
"view_domaliases": "view_domainalias",
"view_mailboxes": "view_mailbox",
}
def rename_view_permissions(apps, schema_edito... | # Generated by Django 2.1.15 on 2020-01-13 09:22
import sys
from django.db import IntegrityError, migrations, transaction
VIEW_PERMISSION_CODENAMES = {
"view_aliases": "view_alias",
"view_domaliases": "view_domainalias",
"view_mailboxes": "view_mailbox",
}
def rename_view_permissions(apps, schema_edito... | Permission = apps.get_model("auth", "Permission")
db_alias = schema_editor.connection.alias
# Iterate over permissions and try to rename the codename
for perm in Permission.objects.using(db_alias).filter(
codename__in=VIEW_PERMISSION_CODENAMES.keys()
):
codename = perm.codename
... | Permission = apps.get_model("auth", "Permission")
db_alias = schema_editor.connection.alias
# Iterate over permissions and try to rename the codename
for perm in Permission.objects.using(db_alias).filter(
codename__in=VIEW_PERMISSION_CODENAMES.keys()
):
codename = perm.codename
... | 55 | 214 | 230 | 444 | # Generated by Django 2.1.15 on 2020-01-13 09:22
import sys
from django.db import IntegrityError, migrations, transaction
VIEW_PERMISSION_CODENAMES = {
"view_aliases": "view_alias",
"view_domaliases": "view_domainalias",
"view_mailboxes": "view_mailbox",
}
def rename_view_permissions(apps, schema_edito... | # Generated by Django 2.1.15 on 2020-01-13 09:22
import sys
from django.db import IntegrityError, migrations, transaction
VIEW_PERMISSION_CODENAMES = {
"view_aliases": "view_alias",
"view_domaliases": "view_domainalias",
"view_mailboxes": "view_mailbox",
}
def rename_view_permissions(apps, schema_edito... | |
38,322 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/admin/migrations/0019_update_disabled_accounts_aliases.py | 6,7 | 1,28 | update_disabled_accounts_aliases | 7,18 | 7,18 | # Generated by Django 2.2.17 on 2021-01-28 13:40
from django.db import migrations
def update_disabled_accounts_aliases(apps, schema_editor):
FILL_FUNC_BODYclass Migration(migrations.Migration):
dependencies = [
("admin", "0018_auto_20201204_0935"),
("core", "0022_user_tfa_enabled"),
]
o... | # Generated by Django 2.2.17 on 2021-01-28 13:40
from django.db import migrations
def update_disabled_accounts_aliases(apps, schema_editor):
FILL_FUNC_BODYclass Migration(migrations.Migration):
dependencies = [
("admin", "0018_auto_20201204_0935"),
("core", "0022_user_tfa_enabled"),
]
o... | User = apps.get_model("core", "User")
Alias = apps.get_model("admin", "Alias")
disabled_accounts = User.objects.filter(mailbox__isnull=False, is_active=False)
Alias.objects.filter(
address__in=list(disabled_accounts.values_list("email", flat=True)),
enabled=True,
).update(enabled=F... | User = apps.get_model("core", "User")
Alias = apps.get_model("admin", "Alias")
disabled_accounts = User.objects.filter(mailbox__isnull=False, is_active=False)
Alias.objects.filter(
address__in=list(disabled_accounts.values_list("email", flat=True)),
enabled=True,
).update(enabled=F... | 17 | 165 | 121 | 286 | # Generated by Django 2.2.17 on 2021-01-28 13:40
from django.db import migrations
def update_disabled_accounts_aliases(apps, schema_editor):
FILL_FUNC_BODYclass Migration(migrations.Migration):
dependencies = [
("admin", "0018_auto_20201204_0935"),
("core", "0022_user_tfa_enabled"),
]
o... | # Generated by Django 2.2.17 on 2021-01-28 13:40
from django.db import migrations
def update_disabled_accounts_aliases(apps, schema_editor):
FILL_FUNC_BODYclass Migration(migrations.Migration):
dependencies = [
("admin", "0018_auto_20201204_0935"),
("core", "0022_user_tfa_enabled"),
]
o... | |
38,323 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/admin/migrations/0023_auto_20240320_1037.py | 6,7 | 1,26 | set_missing_permission | 7,17 | 7,17 | # Generated by Django 4.2.11 on 2024-03-20 10:37
from django.db import migrations
def set_missing_permission(apps, schema_editor):
FILL_FUNC_BODYclass Migration(migrations.Migration):
dependencies = [
("admin", "0022_alter_alarm_domain"),
]
operations = [
migrations.RunPython(set_missin... | # Generated by Django 4.2.11 on 2024-03-20 10:37
from django.db import migrations
def set_missing_permission(apps, schema_editor):
FILL_FUNC_BODYclass Migration(migrations.Migration):
dependencies = [
("admin", "0022_alter_alarm_domain"),
]
operations = [
migrations.RunPython(set_missin... | Permission = apps.get_model("auth", "Permission")
Group = apps.get_model("auth", "Group")
group = Group.objects.filter(name="DomainAdmins").first()
if not group:
# Fresh install, nothing to do
return
perm = Permission.objects.get(codename="view_domainalias")
group.permissions.add... | Permission = apps.get_model("auth", "Permission")
Group = apps.get_model("auth", "Group")
group = Group.objects.filter(name="DomainAdmins").first()
if not group:
# Fresh install, nothing to do
return
perm = Permission.objects.get(codename="view_domainalias")
group.permissions.add... | 25 | 141 | 113 | 254 | # Generated by Django 4.2.11 on 2024-03-20 10:37
from django.db import migrations
def set_missing_permission(apps, schema_editor):
FILL_FUNC_BODYclass Migration(migrations.Migration):
dependencies = [
("admin", "0022_alter_alarm_domain"),
]
operations = [
migrations.RunPython(set_missin... | # Generated by Django 4.2.11 on 2024-03-20 10:37
from django.db import migrations
def set_missing_permission(apps, schema_editor):
FILL_FUNC_BODYclass Migration(migrations.Migration):
dependencies = [
("admin", "0022_alter_alarm_domain"),
]
operations = [
migrations.RunPython(set_missin... | |
38,324 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/admin/models/alarm.py | 55,56 | 19,68 | close | Alarm | 57,61 | 56,61 | class Alarm(models.Model):
"""A simple alarm to attach to a domain and/or mailbox."""
domain = models.ForeignKey(
"admin.Domain",
on_delete=models.CASCADE,
related_name="alarms",
blank=True,
null=True,
)
mailbox = models.ForeignKey(
"admin.Mailbox",
... | class Alarm(models.Model):
"""A simple alarm to attach to a domain and/or mailbox."""
domain = models.ForeignKey(
"admin.Domain",
on_delete=models.CASCADE,
related_name="alarms",
blank=True,
null=True,
)
mailbox = models.ForeignKey(
"admin.Mailbox",
... | self.status = constants.ALARM_CLOSED
self.closed = timezone.now()
self.save()
| """Close this alarm."""
self.status = constants.ALARM_CLOSED
self.closed = timezone.now()
self.save()
| 7 | 392 | 37 | 429 | """Alert related models."""
from django.db import models
from django.utils import timezone
from reversion import revisions as reversion
from .. import constants
class AlarmQuerySet(models.QuerySet):
"""Custom queryset for Alarm."""
def opened(self):
"""Return opened alarms."""
return self.... | """Alert related models."""
from django.db import models
from django.utils import timezone
from reversion import revisions as reversion
from .. import constants
class AlarmQuerySet(models.QuerySet):
"""Custom queryset for Alarm."""
def opened(self):
"""Return opened alarms."""
return self.... |
38,325 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/admin/models/alarm.py | 14,15 | 11,19 | opened | AlarmQuerySet | 16,19 | 15,19 | class AlarmQuerySet(models.QuerySet):
"""Custom queryset for Alarm."""
def opened(self):
FILL_FUNC_BODY | class AlarmQuerySet(models.QuerySet):
"""Custom queryset for Alarm."""
def opened(self):
"""Return opened alarms."""
FILL_FUNC_BODY | return self.filter(status=constants.ALARM_OPENED)
| """Return opened alarms."""
return self.filter(status=constants.ALARM_OPENED)
| 2 | 49 | 25 | 74 | """Alert related models."""
from django.db import models
from django.utils import timezone
from reversion import revisions as reversion
from .. import constants
class AlarmQuerySet(models.QuerySet):
"""Custom queryset for Alarm."""
def opened(self):
FILL_FUNC_BODYclass Alarm(models.Model):
"""A simple... | """Alert related models."""
from django.db import models
from django.utils import timezone
from reversion import revisions as reversion
from .. import constants
class AlarmQuerySet(models.QuerySet):
"""Custom queryset for Alarm."""
def opened(self):
"""Return opened alarms."""
FILL_FUNC_BODYclass ... |
38,327 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/admin/models/alias.py | 207,208 | 87,280 | remove_recipient_or_delete | Alias | 212,222 | 208,222 | class Alias(AdminObject):
"""Mailbox alias."""
address = models.CharField(
gettext_lazy("address"),
max_length=254,
help_text=gettext_lazy("The alias address."),
)
domain = models.ForeignKey(Domain, null=True, on_delete=models.CASCADE)
enabled = models.BooleanField(
... | class Alias(AdminObject):
"""Mailbox alias."""
address = models.CharField(
gettext_lazy("address"),
max_length=254,
help_text=gettext_lazy("The alias address."),
)
domain = models.ForeignKey(Domain, null=True, on_delete=models.CASCADE)
enabled = models.BooleanField(
... | alias_recipients = list(self.recipients)
if recipient_to_delete in alias_recipients:
if len(alias_recipients) == 1:
# Only recipient, we delete the Alias
self.delete()
else:
alias_recipients.remove(recipient_to_delete)
... | """
Delete the selected recipient from this alias
or delete the whole alias if only one is left.
"""
alias_recipients = list(self.recipients)
if recipient_to_delete in alias_recipients:
if len(alias_recipients) == 1:
# Only recipient, we delete... | 23 | 1,779 | 117 | 1,896 | """Models related to aliases management."""
import hashlib
import random
from django.core.exceptions import ValidationError
from django.db import models
from django.urls import reverse
from django.utils.encoding import force_bytes, force_str, smart_str
from django.utils.translation import gettext as _, gettext_lazy
... | """Models related to aliases management."""
import hashlib
import random
from django.core.exceptions import ValidationError
from django.db import models
from django.urls import reverse
from django.utils.encoding import force_bytes, force_str, smart_str
from django.utils.translation import gettext as _, gettext_lazy
... |
38,328 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/admin/models/alias.py | 64,65 | 61,87 | create | AliasManager | 66,75 | 65,75 | class AliasManager(models.Manager):
"""Custom manager for Alias."""
def create(self, *args, **kwargs):
FILL_FUNC_BODY def modify_or_create(self, address, recipients, creator, domain):
"""Add recipient if the alias already exists or create it."""
alias = self.get_queryset().filter(address=ad... | class AliasManager(models.Manager):
"""Custom manager for Alias."""
def create(self, *args, **kwargs):
"""Custom create method."""
FILL_FUNC_BODY def modify_or_create(self, address, recipients, creator, domain):
"""Add recipient if the alias already exists or create it."""
alias = s... | creator = kwargs.pop("creator", None)
recipients = kwargs.pop("recipients", None)
alias = super().create(*args, **kwargs)
if creator:
alias.post_create(creator)
if recipients:
alias.set_recipients(recipients)
return alias
| """Custom create method."""
creator = kwargs.pop("creator", None)
recipients = kwargs.pop("recipients", None)
alias = super().create(*args, **kwargs)
if creator:
alias.post_create(creator)
if recipients:
alias.set_recipients(recipients)
ret... | 20 | 166 | 97 | 263 | """Models related to aliases management."""
import hashlib
import random
from django.core.exceptions import ValidationError
from django.db import models
from django.urls import reverse
from django.utils.encoding import force_bytes, force_str, smart_str
from django.utils.translation import gettext as _, gettext_lazy
... | """Models related to aliases management."""
import hashlib
import random
from django.core.exceptions import ValidationError
from django.db import models
from django.urls import reverse
from django.utils.encoding import force_bytes, force_str, smart_str
from django.utils.translation import gettext as _, gettext_lazy
... |
38,329 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/admin/models/base.py | 47,49 | 24,72 | from_db | AdminObject | 50,54 | 49,54 | class AdminObject(models.Model):
"""Abstract model to support dates.
Inherit from this model to automatically add the "dates" feature
to another model. It defines the appropriate field and handles
saves.
"""
creation = models.DateTimeField(default=timezone.now)
last_modification = models.D... | class AdminObject(models.Model):
"""Abstract model to support dates.
Inherit from this model to automatically add the "dates" feature
to another model. It defines the appropriate field and handles
saves.
"""
creation = models.DateTimeField(default=timezone.now)
last_modification = models.D... | instance = super().from_db(db, field_names, values)
instance._loaded_values = dict(zip(field_names, values))
return instance
| """Store loaded values."""
instance = super().from_db(db, field_names, values)
instance._loaded_values = dict(zip(field_names, values))
return instance
| 11 | 390 | 45 | 435 | """Base admin models."""
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
from django.utils import timezone
from modoboa.core import models as core_models
from modoboa.lib.permissions import grant_access_to_object, ungrant_access_to_object
class AdminObjectManager(models.M... | """Base admin models."""
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
from django.utils import timezone
from modoboa.core import models as core_models
from modoboa.lib.permissions import grant_access_to_object, ungrant_access_to_object
class AdminObjectManager(models.M... |
38,330 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/admin/models/base.py | 13,14 | 11,24 | get_for_admin | AdminObjectManager | 19,24 | 14,24 | class AdminObjectManager(models.Manager):
def get_for_admin(self, admin):
FILL_FUNC_BODY | class AdminObjectManager(models.Manager):
def get_for_admin(self, admin):
"""Return the objects belonging to this admin
The result is a ``QuerySet`` object, so this function can be used
to fill ``ModelChoiceField`` objects.
"""
FILL_FUNC_BODY | if admin.is_superuser:
return self.get_queryset()
return self.get_queryset().prefetch_related("owners").filter(owners__user=admin)
| """Return the objects belonging to this admin
The result is a ``QuerySet`` object, so this function can be used
to fill ``ModelChoiceField`` objects.
"""
if admin.is_superuser:
return self.get_queryset()
return self.get_queryset().prefetch_related("owners").f... | 6 | 79 | 52 | 131 | """Base admin models."""
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
from django.utils import timezone
from modoboa.core import models as core_models
from modoboa.lib.permissions import grant_access_to_object, ungrant_access_to_object
class AdminObjectManager(models.M... | """Base admin models."""
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
from django.utils import timezone
from modoboa.core import models as core_models
from modoboa.lib.permissions import grant_access_to_object, ungrant_access_to_object
class AdminObjectManager(models.M... |
38,332 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/admin/models/domain_alias.py | 60,61 | 29,98 | from_csv | DomainAlias | 69,86 | 61,86 | class DomainAlias(AdminObject):
"""Domain aliases."""
name = models.CharField(
gettext_lazy("name"),
max_length=100,
unique=True,
help_text=gettext_lazy("The alias name"),
)
target = models.ForeignKey(
Domain,
verbose_name=gettext_lazy("target"),
... | class DomainAlias(AdminObject):
"""Domain aliases."""
name = models.CharField(
gettext_lazy("name"),
max_length=100,
unique=True,
help_text=gettext_lazy("The alias name"),
)
target = models.ForeignKey(
Domain,
verbose_name=gettext_lazy("target"),
... | if len(row) < 4:
raise BadRequest(_("Invalid line"))
self.name = row[1].strip().lower()
for model in [DomainAlias, Domain]:
if model.objects.filter(name=self.name).exists():
raise Conflict
domname = row[2].strip()
try:
self.targ... | """Create a domain alias from a CSV row
Expected format: ["domainalias", domain alias name, targeted domain,
enabled]
:param user: a ``User`` object
:param row: a list containing the alias definition
"""
if len(row) < 4:
raise BadRe... | 48 | 443 | 226 | 669 | """Models related to domain aliases management."""
from reversion import revisions as reversion
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
from django.utils.encoding import smart_str
from django.utils.translation import gettext as _, gettext_lazy
from modoboa.core imp... | """Models related to domain aliases management."""
from reversion import revisions as reversion
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
from django.utils.encoding import smart_str
from django.utils.translation import gettext as _, gettext_lazy
from modoboa.core imp... |
38,333 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/admin/models/domain_alias.py | 18,19 | 16,29 | get_for_admin | DomainAliasManager | 24,29 | 19,29 | class DomainAliasManager(models.Manager):
def get_for_admin(self, admin):
FILL_FUNC_BODY | class DomainAliasManager(models.Manager):
def get_for_admin(self, admin):
"""Return the domain aliases belonging to this admin.
The result is a ``QuerySet`` object, so this function can be used
to fill ``ModelChoiceField`` objects.
"""
FILL_FUNC_BODY | if admin.is_superuser:
return self.get_queryset()
return self.get_queryset().filter(owners__user=admin)
| """Return the domain aliases belonging to this admin.
The result is a ``QuerySet`` object, so this function can be used
to fill ``ModelChoiceField`` objects.
"""
if admin.is_superuser:
return self.get_queryset()
return self.get_queryset().filter(owners__user=... | 6 | 83 | 45 | 128 | """Models related to domain aliases management."""
from reversion import revisions as reversion
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
from django.utils.encoding import smart_str
from django.utils.translation import gettext as _, gettext_lazy
from modoboa.core imp... | """Models related to domain aliases management."""
from reversion import revisions as reversion
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
from django.utils.encoding import smart_str
from django.utils.translation import gettext as _, gettext_lazy
from modoboa.core imp... |
38,334 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/admin/models/mixins.py | 20,22 | 6,26 | sent_messages_in_percent | MessageLimitMixin | 23,26 | 22,26 | class MessageLimitMixin:
"""A mixin to add message limit support."""
@property
def message_counter_key(self):
raise NotImplementedError
@property
def sent_messages(self):
"""Return number of sent messages for the current day."""
if self.message_limit is None:
re... | class MessageLimitMixin:
"""A mixin to add message limit support."""
@property
def message_counter_key(self):
raise NotImplementedError
@property
def sent_messages(self):
"""Return number of sent messages for the current day."""
if self.message_limit is None:
re... | if not self.message_limit:
return None
return int(self.sent_messages / float(self.message_limit) * 100)
| """Return number of sent messages as a percentage."""
if not self.message_limit:
return None
return int(self.sent_messages / float(self.message_limit) * 100)
| 11 | 148 | 42 | 190 | """Admin model mixins."""
from modoboa.policyd.utils import get_message_counter
class MessageLimitMixin:
"""A mixin to add message limit support."""
@property
def message_counter_key(self):
raise NotImplementedError
@property
def sent_messages(self):
"""Return number of sent mes... | """Admin model mixins."""
from modoboa.policyd.utils import get_message_counter
class MessageLimitMixin:
"""A mixin to add message limit support."""
@property
def message_counter_key(self):
raise NotImplementedError
@property
def sent_messages(self):
"""Return number of sent mes... |
38,335 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/admin/models/mxrecord.py | 77,78 | 74,82 | blacklisted | DNSBLQuerySet | 79,82 | 78,82 | class DNSBLQuerySet(models.QuerySet):
"""Custom manager for DNSBLResultManager."""
def blacklisted(self):
FILL_FUNC_BODY | class DNSBLQuerySet(models.QuerySet):
"""Custom manager for DNSBLResultManager."""
def blacklisted(self):
"""Return blacklisted results."""
FILL_FUNC_BODY | return self.exclude(status="")
| """Return blacklisted results."""
return self.exclude(status="")
| 2 | 50 | 17 | 67 | """MX records storage."""
import datetime
from django.db import models
from django.utils import timezone
from modoboa.parameters import tools as param_tools
class MXRecordQuerySet(models.QuerySet):
"""Custom manager for MXRecord."""
def has_valids(self):
"""Return managed results."""
if pa... | """MX records storage."""
import datetime
from django.db import models
from django.utils import timezone
from modoboa.parameters import tools as param_tools
class MXRecordQuerySet(models.QuerySet):
"""Custom manager for MXRecord."""
def has_valids(self):
"""Return managed results."""
if pa... |
38,336 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/admin/models/mxrecord.py | 65,66 | 54,74 | is_managed | MXRecord | 66,70 | 66,70 | class MXRecord(models.Model):
"""A model used to store MX records for Domain."""
domain = models.ForeignKey("admin.Domain", on_delete=models.CASCADE)
name = models.CharField(max_length=254)
address = models.GenericIPAddressField()
managed = models.BooleanField(default=False)
updated = models.Da... | class MXRecord(models.Model):
"""A model used to store MX records for Domain."""
domain = models.ForeignKey("admin.Domain", on_delete=models.CASCADE)
name = models.CharField(max_length=254)
address = models.GenericIPAddressField()
managed = models.BooleanField(default=False)
updated = models.Da... | if not param_tools.get_global_parameter("enable_mx_checks"):
return False
return bool(param_tools.get_global_parameter("valid_mxs").strip())
| if not param_tools.get_global_parameter("enable_mx_checks"):
return False
return bool(param_tools.get_global_parameter("valid_mxs").strip())
| 7 | 185 | 53 | 238 | """MX records storage."""
import datetime
from django.db import models
from django.utils import timezone
from modoboa.parameters import tools as param_tools
class MXRecordQuerySet(models.QuerySet):
"""Custom manager for MXRecord."""
def has_valids(self):
"""Return managed results."""
if pa... | """MX records storage."""
import datetime
from django.db import models
from django.utils import timezone
from modoboa.parameters import tools as param_tools
class MXRecordQuerySet(models.QuerySet):
"""Custom manager for MXRecord."""
def has_valids(self):
"""Return managed results."""
if pa... |
38,337 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/admin/models/mxrecord.py | 24,25 | 21,54 | get_or_create_for_domain | MXRecordManager | 29,54 | 25,54 | class MXRecordManager(models.Manager):
"""Custom manager for MXRecord."""
def get_or_create_for_domain(self, domain, ttl=7200):
FILL_FUNC_BODY | class MXRecordManager(models.Manager):
"""Custom manager for MXRecord."""
def get_or_create_for_domain(self, domain, ttl=7200):
"""Get or create MX record(s) for given domain.
DNS queries are not performed while `ttl` (in seconds) is still valid.
"""
FILL_FUNC_BODY | from .. import lib
now = timezone.now()
records = self.get_queryset().filter(domain=domain, updated__gt=now)
if records.exists():
for record in records:
yield record
return
self.get_queryset().filter(domain=domain).delete()
delta... | """Get or create MX record(s) for given domain.
DNS queries are not performed while `ttl` (in seconds) is still valid.
"""
from .. import lib
now = timezone.now()
records = self.get_queryset().filter(domain=domain, updated__gt=now)
if records.exists():
... | 49 | 97 | 244 | 341 | """MX records storage."""
import datetime
from django.db import models
from django.utils import timezone
from modoboa.parameters import tools as param_tools
class MXRecordQuerySet(models.QuerySet):
"""Custom manager for MXRecord."""
def has_valids(self):
"""Return managed results."""
if pa... | """MX records storage."""
import datetime
from django.db import models
from django.utils import timezone
from modoboa.parameters import tools as param_tools
class MXRecordQuerySet(models.QuerySet):
"""Custom manager for MXRecord."""
def has_valids(self):
"""Return managed results."""
if pa... |
38,338 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/admin/models/mxrecord.py | 14,15 | 11,21 | has_valids | MXRecordQuerySet | 16,21 | 15,21 | class MXRecordQuerySet(models.QuerySet):
"""Custom manager for MXRecord."""
def has_valids(self):
FILL_FUNC_BODY | class MXRecordQuerySet(models.QuerySet):
"""Custom manager for MXRecord."""
def has_valids(self):
"""Return managed results."""
FILL_FUNC_BODY | if param_tools.get_global_parameter("valid_mxs").strip():
return self.filter(managed=True).exists()
return self.exists()
| """Return managed results."""
if param_tools.get_global_parameter("valid_mxs").strip():
return self.filter(managed=True).exists()
return self.exists()
| 6 | 51 | 48 | 99 | """MX records storage."""
import datetime
from django.db import models
from django.utils import timezone
from modoboa.parameters import tools as param_tools
class MXRecordQuerySet(models.QuerySet):
"""Custom manager for MXRecord."""
def has_valids(self):
FILL_FUNC_BODYclass MXRecordManager(models.Manager)... | """MX records storage."""
import datetime
from django.db import models
from django.utils import timezone
from modoboa.parameters import tools as param_tools
class MXRecordQuerySet(models.QuerySet):
"""Custom manager for MXRecord."""
def has_valids(self):
"""Return managed results."""
FILL_FUNC_BOD... |
38,340 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/admin/views/alias.py | 38,39 | 1,123 | _new_alias | 39,59 | 39,59 | """Alias related views."""
from reversion import revisions as reversion
from django.contrib.auth import mixins as auth_mixins
from django.contrib.auth.decorators import login_required, permission_required
from django.db import IntegrityError
from django.shortcuts import render
from django.urls import reverse
from dja... | """Alias related views."""
from reversion import revisions as reversion
from django.contrib.auth import mixins as auth_mixins
from django.contrib.auth.decorators import login_required, permission_required
from django.db import IntegrityError
from django.shortcuts import render
from django.urls import reverse
from dja... | core_signals.can_create_object.send("new_alias", context=request.user, klass=Alias)
if request.method == "POST":
def callback(user, alias):
alias.post_create(user)
form = AliasForm(request.user, request.POST)
return _validate_alias(request, form, successmsg, callback)
... | core_signals.can_create_object.send("new_alias", context=request.user, klass=Alias)
if request.method == "POST":
def callback(user, alias):
alias.post_create(user)
form = AliasForm(request.user, request.POST)
return _validate_alias(request, form, successmsg, callback)
... | 40 | 1,003 | 197 | 1,200 | """Alias related views."""
from reversion import revisions as reversion
from django.contrib.auth import mixins as auth_mixins
from django.contrib.auth.decorators import login_required, permission_required
from django.db import IntegrityError
from django.shortcuts import render
from django.urls import reverse
from dja... | """Alias related views."""
from reversion import revisions as reversion
from django.contrib.auth import mixins as auth_mixins
from django.contrib.auth.decorators import login_required, permission_required
from django.db import IntegrityError
from django.shortcuts import render
from django.urls import reverse
from dja... | |
38,341 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/admin/views/alias.py | 118,119 | 105,123 | get_context_data | AliasDetailView | 120,123 | 119,123 | class AliasDetailView(auth_mixins.PermissionRequiredMixin, generic.DetailView):
"""DetailView for Alias."""
model = Alias
permission_required = "admin.add_alias"
def has_permission(self):
"""Check object-level access."""
result = super(AliasDetailView, self).has_permission()
if... | class AliasDetailView(auth_mixins.PermissionRequiredMixin, generic.DetailView):
"""DetailView for Alias."""
model = Alias
permission_required = "admin.add_alias"
def has_permission(self):
"""Check object-level access."""
result = super(AliasDetailView, self).has_permission()
if... | context = super(AliasDetailView, self).get_context_data(**kwargs)
context["selection"] = "identities"
return context
| """Add information to context."""
context = super(AliasDetailView, self).get_context_data(**kwargs)
context["selection"] = "identities"
return context
| 9 | 149 | 40 | 189 | """Alias related views."""
from reversion import revisions as reversion
from django.contrib.auth import mixins as auth_mixins
from django.contrib.auth.decorators import login_required, permission_required
from django.db import IntegrityError
from django.shortcuts import render
from django.urls import reverse
from dja... | """Alias related views."""
from reversion import revisions as reversion
from django.contrib.auth import mixins as auth_mixins
from django.contrib.auth.decorators import login_required, permission_required
from django.db import IntegrityError
from django.shortcuts import render
from django.urls import reverse
from dja... |
38,342 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/admin/views/dns.py | 47,48 | 32,52 | get_context_data | DNSBLDomainDetailView | 49,52 | 48,52 | class DNSBLDomainDetailView(auth_mixins.PermissionRequiredMixin, generic.DetailView):
"""View to display DNSBL summary."""
model = models.Domain
permission_required = "admin.view_domain"
template_name = "admin/dnsbl_domain_detail.html"
def get_queryset(self):
"""Add some prefetching."""
... | class DNSBLDomainDetailView(auth_mixins.PermissionRequiredMixin, generic.DetailView):
"""View to display DNSBL summary."""
model = models.Domain
permission_required = "admin.view_domain"
template_name = "admin/dnsbl_domain_detail.html"
def get_queryset(self):
"""Add some prefetching."""
... | context = super(DNSBLDomainDetailView, self).get_context_data(**kwargs)
context.update({"title": _("DNSBL summary for {}").format(self.object.name)})
return context
| """Add extra variables."""
context = super(DNSBLDomainDetailView, self).get_context_data(**kwargs)
context.update({"title": _("DNSBL summary for {}").format(self.object.name)})
return context
| 11 | 168 | 57 | 225 | """DNSBL related views."""
from django.contrib.auth import mixins as auth_mixins
from django.utils.translation import gettext as _
from django.views import generic
from .. import models
class MXDomainDetailView(auth_mixins.PermissionRequiredMixin, generic.DetailView):
"""View to display MX records."""
mode... | """DNSBL related views."""
from django.contrib.auth import mixins as auth_mixins
from django.utils.translation import gettext as _
from django.views import generic
from .. import models
class MXDomainDetailView(auth_mixins.PermissionRequiredMixin, generic.DetailView):
"""View to display MX records."""
mode... |
38,343 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/admin/views/dns.py | 25,26 | 10,32 | get_context_data | MXDomainDetailView | 27,32 | 26,32 | class MXDomainDetailView(auth_mixins.PermissionRequiredMixin, generic.DetailView):
"""View to display MX records."""
model = models.Domain
permission_required = "admin.view_domain"
template_name = "admin/mx_domain_detail.html"
def get_queryset(self):
"""Add some prefetching."""
ret... | class MXDomainDetailView(auth_mixins.PermissionRequiredMixin, generic.DetailView):
"""View to display MX records."""
model = models.Domain
permission_required = "admin.view_domain"
template_name = "admin/mx_domain_detail.html"
def get_queryset(self):
"""Add some prefetching."""
ret... | context = super(MXDomainDetailView, self).get_context_data(**kwargs)
context.update({"title": _("MX records of {}").format(self.object.name)})
return context
| """Add extra variables."""
context = super(MXDomainDetailView, self).get_context_data(**kwargs)
context.update({"title": _("MX records of {}").format(self.object.name)})
return context
| 11 | 163 | 59 | 222 | """DNSBL related views."""
from django.contrib.auth import mixins as auth_mixins
from django.utils.translation import gettext as _
from django.views import generic
from .. import models
class MXDomainDetailView(auth_mixins.PermissionRequiredMixin, generic.DetailView):
"""View to display MX records."""
mode... | """DNSBL related views."""
from django.contrib.auth import mixins as auth_mixins
from django.utils.translation import gettext as _
from django.views import generic
from .. import models
class MXDomainDetailView(auth_mixins.PermissionRequiredMixin, generic.DetailView):
"""View to display MX records."""
mode... |
38,345 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/admin/views/domain.py | 303,304 | 296,308 | get_queryset | DomainAlarmsView | 305,308 | 304,308 | class DomainAlarmsView(auth_mixins.PermissionRequiredMixin, generic.DetailView):
"""A view to list domain alarms."""
model = Domain
permission_required = "admin.view_domain"
template_name = "admin/domain_alarms.html"
def get_queryset(self):
FILL_FUNC_BODY | class DomainAlarmsView(auth_mixins.PermissionRequiredMixin, generic.DetailView):
"""A view to list domain alarms."""
model = Domain
permission_required = "admin.view_domain"
template_name = "admin/domain_alarms.html"
def get_queryset(self):
"""Add some prefetching."""
FILL_FUNC_BODY | return Domain.objects.get_for_admin(self.request.user).prefetch_related(
"alarms"
)
| """Add some prefetching."""
return Domain.objects.get_for_admin(self.request.user).prefetch_related(
"alarms"
)
| 4 | 100 | 37 | 137 | """Domain related views."""
from functools import reduce
from reversion import revisions as reversion
from django.contrib.auth import mixins as auth_mixins
from django.contrib.auth.decorators import (
login_required,
permission_required,
user_passes_test,
)
from django.db.models import Q, Sum
from django... | """Domain related views."""
from functools import reduce
from reversion import revisions as reversion
from django.contrib.auth import mixins as auth_mixins
from django.contrib.auth.decorators import (
login_required,
permission_required,
user_passes_test,
)
from django.db.models import Q, Sum
from django... |
38,346 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/admin/views/domain.py | 267,268 | 255,296 | get_context_data | DomainDetailView | 269,296 | 268,296 | class DomainDetailView(auth_mixins.PermissionRequiredMixin, generic.DetailView):
"""DetailView for Domain."""
model = Domain
permission_required = "admin.view_domain"
def get_queryset(self):
"""Add some prefetching."""
return Domain.objects.get_for_admin(self.request.user).prefetch_rel... | class DomainDetailView(auth_mixins.PermissionRequiredMixin, generic.DetailView):
"""DetailView for Domain."""
model = Domain
permission_required = "admin.view_domain"
def get_queryset(self):
"""Add some prefetching."""
return Domain.objects.get_for_admin(self.request.user).prefetch_rel... | context = super(DomainDetailView, self).get_context_data(**kwargs)
result = signals.extra_domain_dashboard_widgets.send(
self.__class__, user=self.request.user, domain=self.object
)
parameters = self.request.localconfig.parameters
context.update(
{
... | """Include extra widgets."""
context = super(DomainDetailView, self).get_context_data(**kwargs)
result = signals.extra_domain_dashboard_widgets.send(
self.__class__, user=self.request.user, domain=self.object
)
parameters = self.request.localconfig.parameters
... | 55 | 152 | 360 | 512 | """Domain related views."""
from functools import reduce
from reversion import revisions as reversion
from django.contrib.auth import mixins as auth_mixins
from django.contrib.auth.decorators import (
login_required,
permission_required,
user_passes_test,
)
from django.db.models import Q, Sum
from django... | """Domain related views."""
from functools import reduce
from reversion import revisions as reversion
from django.contrib.auth import mixins as auth_mixins
from django.contrib.auth.decorators import (
login_required,
permission_required,
user_passes_test,
)
from django.db.models import Q, Sum
from django... |
38,347 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/admin/views/export.py | 34,39 | 1,89 | export_identities | 39,65 | 39,65 | """Export related views."""
import csv
from io import StringIO
from django.contrib.auth.decorators import (
login_required,
permission_required,
user_passes_test,
)
from django.http import HttpResponse
from django.shortcuts import render
from django.urls import reverse
from django.utils.translation import... | """Export related views."""
import csv
from io import StringIO
from django.contrib.auth.decorators import (
login_required,
permission_required,
user_passes_test,
)
from django.http import HttpResponse
from django.shortcuts import render
from django.urls import reverse
from django.utils.translation import... | ctx = {
"title": _("Export identities"),
"action_label": _("Export"),
"action_classes": "submit",
"formid": "exportform",
"action": reverse("admin:identity_export"),
}
if request.method == "POST":
form = ExportDataForm(request.POST)
form.is_valid()
... | ctx = {
"title": _("Export identities"),
"action_label": _("Export"),
"action_classes": "submit",
"formid": "exportform",
"action": reverse("admin:identity_export"),
}
if request.method == "POST":
form = ExportDataForm(request.POST)
form.is_valid()
... | 55 | 577 | 276 | 853 | """Export related views."""
import csv
from io import StringIO
from django.contrib.auth.decorators import (
login_required,
permission_required,
user_passes_test,
)
from django.http import HttpResponse
from django.shortcuts import render
from django.urls import reverse
from django.utils.translation import... | """Export related views."""
import csv
from io import StringIO
from django.contrib.auth.decorators import (
login_required,
permission_required,
user_passes_test,
)
from django.http import HttpResponse
from django.shortcuts import render
from django.urls import reverse
from django.utils.translation import... | |
38,349 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/admin/views/identity.py | 223,224 | 209,239 | get_context_data | AccountDetailView | 225,239 | 224,239 | class AccountDetailView(auth_mixins.PermissionRequiredMixin, generic.DetailView):
"""DetailView for Account."""
model = User
permission_required = "core.add_user"
template_name = "admin/account_detail.html"
def has_permission(self):
"""Check object-level access."""
result = super(A... | class AccountDetailView(auth_mixins.PermissionRequiredMixin, generic.DetailView):
"""DetailView for Account."""
model = User
permission_required = "core.add_user"
template_name = "admin/account_detail.html"
def has_permission(self):
"""Check object-level access."""
result = super(A... | context = super(AccountDetailView, self).get_context_data(**kwargs)
del context["user"]
result = signals.extra_account_dashboard_widgets.send(
self.__class__, user=self.request.user, account=self.object
)
context["templates"] = {"left": [], "right": []}
for _r... | """Add information to context."""
context = super(AccountDetailView, self).get_context_data(**kwargs)
del context["user"]
result = signals.extra_account_dashboard_widgets.send(
self.__class__, user=self.request.user, account=self.object
)
context["templates"] ... | 43 | 160 | 209 | 369 | """Identity related views."""
from reversion import revisions as reversion
from django.contrib.auth import mixins as auth_mixins
from django.contrib.auth.decorators import (
login_required,
permission_required,
user_passes_test,
)
from django.shortcuts import render
from django.template.loader import rend... | """Identity related views."""
from reversion import revisions as reversion
from django.contrib.auth import mixins as auth_mixins
from django.contrib.auth.decorators import (
login_required,
permission_required,
user_passes_test,
)
from django.shortcuts import render
from django.template.loader import rend... |
38,350 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/admin/views/import_.py | 25,27 | 1,87 | importdata | 36,49 | 27,49 | """Import related views."""
import csv
import io
from reversion import revisions as reversion
from django.contrib.auth.decorators import (
login_required,
permission_required,
user_passes_test,
)
from django.db import transaction
from django.shortcuts import render
from django.urls import reverse
from dj... | """Import related views."""
import csv
import io
from reversion import revisions as reversion
from django.contrib.auth.decorators import (
login_required,
permission_required,
user_passes_test,
)
from django.db import transaction
from django.shortcuts import render
from django.urls import reverse
from dj... | msg = None
form = formclass(request.POST, request.FILES)
if form.is_valid():
status, msg = lib.import_data(
request.user, request.FILES["sourcefile"], form.cleaned_data
)
if status:
return render(
request, "admin/import_done.html", {"status": "... | """Generic import function
As the process of importing data from a CSV file is the same
whatever the type, we do a maximum of the work here.
:param request: a ``Request`` instance
:param typ: a string indicating the object type being imported
:return: a ``Response`` instance
"""
msg = ... | 35 | 634 | 144 | 778 | """Import related views."""
import csv
import io
from reversion import revisions as reversion
from django.contrib.auth.decorators import (
login_required,
permission_required,
user_passes_test,
)
from django.db import transaction
from django.shortcuts import render
from django.urls import reverse
from dj... | """Import related views."""
import csv
import io
from reversion import revisions as reversion
from django.contrib.auth.decorators import (
login_required,
permission_required,
user_passes_test,
)
from django.db import transaction
from django.shortcuts import render
from django.urls import reverse
from dj... | |
38,351 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/admin/views/user.py | 15,19 | 1,65 | forward | 19,65 | 19,65 | """SimpleUsers views."""
from reversion import revisions as reversion
from django.contrib.auth.decorators import login_required
from django.template.loader import render_to_string
from django.utils.translation import gettext as _
from modoboa.lib.web_utils import render_to_json_response
from ..forms import ForwardFo... | """SimpleUsers views."""
from reversion import revisions as reversion
from django.contrib.auth.decorators import login_required
from django.template.loader import render_to_string
from django.utils.translation import gettext as _
from modoboa.lib.web_utils import render_to_json_response
from ..forms import ForwardFo... | mb = request.user.mailbox
al = Alias.objects.filter(address=mb.full_address, internal=False).first()
if request.method == "POST":
form = ForwardForm(request.POST)
if form.is_valid():
recipients = form.cleaned_data["dest"]
if not recipients:
Alias.objec... | mb = request.user.mailbox
al = Alias.objects.filter(address=mb.full_address, internal=False).first()
if request.method == "POST":
form = ForwardForm(request.POST)
if form.is_valid():
recipients = form.cleaned_data["dest"]
if not recipients:
Alias.objec... | 114 | 157 | 574 | 731 | """SimpleUsers views."""
from reversion import revisions as reversion
from django.contrib.auth.decorators import login_required
from django.template.loader import render_to_string
from django.utils.translation import gettext as _
from modoboa.lib.web_utils import render_to_json_response
from ..forms import ForwardFo... | """SimpleUsers views."""
from reversion import revisions as reversion
from django.contrib.auth.decorators import login_required
from django.template.loader import render_to_string
from django.utils.translation import gettext as _
from modoboa.lib.web_utils import render_to_json_response
from ..forms import ForwardFo... | |
38,352 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/api/v1/serializers.py | 36,37 | 31,46 | validate_password | CheckPasswordTFASerializer | 37,46 | 37,46 | class CheckPasswordTFASerializer(serializers.Serializer):
"""Serializer used to check user password when modifying TFA."""
password = serializers.CharField()
def validate_password(self, value):
FILL_FUNC_BODY | class CheckPasswordTFASerializer(serializers.Serializer):
"""Serializer used to check user password when modifying TFA."""
password = serializers.CharField()
def validate_password(self, value):
FILL_FUNC_BODY | user = self.context["user"]
if not user.check_password(value):
logger.warning(
_("Failed TFA settings editing attempt from '%s' as user '%s'"),
self.context["remote_addr"],
escape(user.username),
)
raise serializers.Vali... | user = self.context["user"]
if not user.check_password(value):
logger.warning(
_("Failed TFA settings editing attempt from '%s' as user '%s'"),
self.context["remote_addr"],
escape(user.username),
)
raise serializers.Vali... | 25 | 62 | 95 | 157 | """Core API serializers."""
import logging
from django.utils.html import escape
from django.utils.translation import gettext as _
from rest_framework import serializers
logger = logging.getLogger("modoboa.auth")
class CheckTFASetupSerializer(serializers.Serializer):
"""Serializer used to finalize 2FA setup.""... | """Core API serializers."""
import logging
from django.utils.html import escape
from django.utils.translation import gettext as _
from rest_framework import serializers
logger = logging.getLogger("modoboa.auth")
class CheckTFASetupSerializer(serializers.Serializer):
"""Serializer used to finalize 2FA setup.""... |
38,353 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/api/v1/serializers.py | 24,25 | 13,31 | validate | CheckTFASetupSerializer | 25,31 | 25,31 | class CheckTFASetupSerializer(serializers.Serializer):
"""Serializer used to finalize 2FA setup."""
pin_code = serializers.CharField()
def validate_pin_code(self, value):
device = self.context["user"].totpdevice_set.first()
if not device.verify_token(value):
raise serializers.V... | class CheckTFASetupSerializer(serializers.Serializer):
"""Serializer used to finalize 2FA setup."""
pin_code = serializers.CharField()
def validate_pin_code(self, value):
device = self.context["user"].totpdevice_set.first()
if not device.verify_token(value):
raise serializers.V... | user = self.context["user"]
if user.tfa_enabled or user.staticdevice_set.exists():
raise serializers.ValidationError(_("2FA is already enabled"))
return data
| user = self.context["user"]
if user.tfa_enabled or user.staticdevice_set.exists():
raise serializers.ValidationError(_("2FA is already enabled"))
return data
| 14 | 123 | 57 | 180 | """Core API serializers."""
import logging
from django.utils.html import escape
from django.utils.translation import gettext as _
from rest_framework import serializers
logger = logging.getLogger("modoboa.auth")
class CheckTFASetupSerializer(serializers.Serializer):
"""Serializer used to finalize 2FA setup.""... | """Core API serializers."""
import logging
from django.utils.html import escape
from django.utils.translation import gettext as _
from rest_framework import serializers
logger = logging.getLogger("modoboa.auth")
class CheckTFASetupSerializer(serializers.Serializer):
"""Serializer used to finalize 2FA setup.""... |
38,354 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/api/v1/tests.py | 9,10 | 6,27 | test_unauthorized | OpenAPITestCase | 10,15 | 10,15 | class OpenAPITestCase(ModoTestCase):
openapi_schema_url = reverse_lazy("schema-v1-legacy")
def test_unauthorized(self):
FILL_FUNC_BODY def test_get_schema(self):
self.assertEqual(self.openapi_schema_url, "/docs/openapi.json")
response = self.client.get(self.openapi_schema_url)
self.... | class OpenAPITestCase(ModoTestCase):
openapi_schema_url = reverse_lazy("schema-v1-legacy")
def test_unauthorized(self):
FILL_FUNC_BODY def test_get_schema(self):
self.assertEqual(self.openapi_schema_url, "/docs/openapi.json")
response = self.client.get(self.openapi_schema_url)
self.... | self.client.logout()
response = self.client.get(self.openapi_schema_url)
self.assertEqual(response.status_code, 401)
| self.client.logout()
response = self.client.get(self.openapi_schema_url)
self.assertEqual(response.status_code, 401)
| 6 | 171 | 52 | 223 | from django.urls import reverse_lazy
from modoboa.lib.tests import ModoTestCase
class OpenAPITestCase(ModoTestCase):
openapi_schema_url = reverse_lazy("schema-v1-legacy")
def test_unauthorized(self):
FILL_FUNC_BODY def test_get_schema(self):
self.assertEqual(self.openapi_schema_url, "/docs/openap... | from django.urls import reverse_lazy
from modoboa.lib.tests import ModoTestCase
class OpenAPITestCase(ModoTestCase):
openapi_schema_url = reverse_lazy("schema-v1-legacy")
def test_unauthorized(self):
FILL_FUNC_BODY def test_get_schema(self):
self.assertEqual(self.openapi_schema_url, "/docs/openap... |
38,355 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/api/v1/viewsets.py | 36,39 | 19,90 | tfa_setup_check | AccountViewSet | 40,54 | 39,54 | class AccountViewSet(GetThrottleViewsetMixin, viewsets.ViewSet):
"""Account viewset.
Contains endpoints used to manipulate current user's account.
"""
permission_classes = (permissions.IsAuthenticated,)
serializer_class = None
@action(methods=["post"], detail=False, url_path="tfa/setup")
... | class AccountViewSet(GetThrottleViewsetMixin, viewsets.ViewSet):
"""Account viewset.
Contains endpoints used to manipulate current user's account.
"""
permission_classes = (permissions.IsAuthenticated,)
serializer_class = None
@action(methods=["post"], detail=False, url_path="tfa/setup")
... | serializer = serializers.CheckTFASetupSerializer(
data=request.data, context={"user": request.user}
)
serializer.is_valid(raise_exception=True)
# create static device for recovery purposes
device = StaticDevice.objects.create(
user=request.user, name="{} s... | """Check TFA setup."""
serializer = serializers.CheckTFASetupSerializer(
data=request.data, context={"user": request.user}
)
serializer.is_valid(raise_exception=True)
# create static device for recovery purposes
device = StaticDevice.objects.create(
... | 35 | 746 | 179 | 925 | """Core API viewsets."""
from django.utils.translation import gettext as _
import django_otp
from django_otp.plugins.otp_static.models import StaticDevice, StaticToken
from django_otp.plugins.otp_totp.models import TOTPDevice
from rest_framework import permissions, response, viewsets
from rest_framework.decorators i... | """Core API viewsets."""
from django.utils.translation import gettext as _
import django_otp
from django_otp.plugins.otp_static.models import StaticDevice, StaticToken
from django_otp.plugins.otp_totp.models import TOTPDevice
from rest_framework import permissions, response, viewsets
from rest_framework.decorators i... |
38,357 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/api/v2/serializers.py | 271,272 | 266,278 | validate_password | CheckPasswordSerializer | 272,278 | 272,278 | class CheckPasswordSerializer(serializers.Serializer):
"""Simple serializer to check user password."""
password = serializers.CharField()
def validate_password(self, value):
FILL_FUNC_BODY | class CheckPasswordSerializer(serializers.Serializer):
"""Simple serializer to check user password."""
password = serializers.CharField()
def validate_password(self, value):
FILL_FUNC_BODY | user = self.context["user"]
if not user.check_password(value):
raise serializers.ValidationError(_("Invalid password"))
return value
| user = self.context["user"]
if not user.check_password(value):
raise serializers.ValidationError(_("Invalid password"))
return value
| 11 | 55 | 47 | 102 | """Core API v2 serializers."""
import django_otp
import oath
from django.db.models import Q
from django.contrib.auth import password_validation
from django.contrib.sites.shortcuts import get_current_site
from django.contrib.auth.tokens import default_token_generator
from django.core.mail import send_mail
from django... | """Core API v2 serializers."""
import django_otp
import oath
from django.db.models import Q
from django.contrib.auth import password_validation
from django.contrib.sites.shortcuts import get_current_site
from django.contrib.auth.tokens import default_token_generator
from django.core.mail import send_mail
from django... |
38,359 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/api/v2/serializers.py | 250,251 | 241,254 | get_date_created | LogSerializer | 251,254 | 251,254 | class LogSerializer(serializers.ModelSerializer):
"""Log serializer."""
date_created = serializers.SerializerMethodField()
class Meta:
model = models.Log
fields = ("date_created", "message", "level", "logger")
def get_date_created(self, log) -> str:
FILL_FUNC_BODY | class LogSerializer(serializers.ModelSerializer):
"""Log serializer."""
date_created = serializers.SerializerMethodField()
class Meta:
model = models.Log
fields = ("date_created", "message", "level", "logger")
def get_date_created(self, log) -> str:
FILL_FUNC_BODY | return formats.date_format(log.date_created, "SHORT_DATETIME_FORMAT")
| return formats.date_format(log.date_created, "SHORT_DATETIME_FORMAT")
| 3 | 92 | 31 | 123 | """Core API v2 serializers."""
import django_otp
import oath
from django.db.models import Q
from django.contrib.auth import password_validation
from django.contrib.sites.shortcuts import get_current_site
from django.contrib.auth.tokens import default_token_generator
from django.core.mail import send_mail
from django... | """Core API v2 serializers."""
import django_otp
import oath
from django.db.models import Q
from django.contrib.auth import password_validation
from django.contrib.sites.shortcuts import get_current_site
from django.contrib.auth.tokens import default_token_generator
from django.core.mail import send_mail
from django... |
38,360 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/api/v2/serializers.py | 445,446 | 436,486 | get_user | PasswordRecoveryConfirmSerializer | 446,454 | 446,454 | class PasswordRecoveryConfirmSerializer(serializers.Serializer):
new_password1 = serializers.CharField()
new_password2 = serializers.CharField()
token = serializers.CharField()
id = serializers.CharField()
def get_user(self, user_id):
FILL_FUNC_BODY def validate(self, data):
# Valida... | class PasswordRecoveryConfirmSerializer(serializers.Serializer):
new_password1 = serializers.CharField()
new_password2 = serializers.CharField()
token = serializers.CharField()
id = serializers.CharField()
def get_user(self, user_id):
FILL_FUNC_BODY def validate(self, data):
# Valida... | try:
# urlsafe_base64_decode() decodes to bytestring
uid = urlsafe_base64_decode(user_id).decode()
user = User.objects.get(pk=uid)
except (TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
return user
| try:
# urlsafe_base64_decode() decodes to bytestring
uid = urlsafe_base64_decode(user_id).decode()
user = User.objects.get(pk=uid)
except (TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
return user
| 22 | 375 | 97 | 472 | """Core API v2 serializers."""
import django_otp
import oath
from django.db.models import Q
from django.contrib.auth import password_validation
from django.contrib.sites.shortcuts import get_current_site
from django.contrib.auth.tokens import default_token_generator
from django.core.mail import send_mail
from django... | """Core API v2 serializers."""
import django_otp
import oath
from django.db.models import Q
from django.contrib.auth import password_validation
from django.contrib.sites.shortcuts import get_current_site
from django.contrib.auth.tokens import default_token_generator
from django.core.mail import send_mail
from django... |
38,361 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/api/v2/serializers.py | 302,303 | 284,329 | save | PasswordRecoveryEmailSerializer | 303,329 | 303,329 | class PasswordRecoveryEmailSerializer(serializers.Serializer):
"""Serializer used by password recovery route."""
email = serializers.EmailField()
def validate(self, data):
clean_email = data["email"]
self.context["user"] = (
User.objects.filter(email__iexact=clean_email, is_act... | class PasswordRecoveryEmailSerializer(serializers.Serializer):
"""Serializer used by password recovery route."""
email = serializers.EmailField()
def validate(self, data):
clean_email = data["email"]
self.context["user"] = (
User.objects.filter(email__iexact=clean_email, is_act... | user = self.context["user"]
to_email = user.secondary_email
current_site = get_current_site(self.context["request"])
site_name = current_site.name
domain = current_site.domain
context = {
"email": to_email,
"domain": domain,
"site_name"... | user = self.context["user"]
to_email = user.secondary_email
current_site = get_current_site(self.context["request"])
site_name = current_site.name
domain = current_site.domain
context = {
"email": to_email,
"domain": domain,
"site_name"... | 61 | 188 | 307 | 495 | """Core API v2 serializers."""
import django_otp
import oath
from django.db.models import Q
from django.contrib.auth import password_validation
from django.contrib.sites.shortcuts import get_current_site
from django.contrib.auth.tokens import default_token_generator
from django.core.mail import send_mail
from django... | """Core API v2 serializers."""
import django_otp
import oath
from django.db.models import Q
from django.contrib.auth import password_validation
from django.contrib.sites.shortcuts import get_current_site
from django.contrib.auth.tokens import default_token_generator
from django.core.mail import send_mail
from django... |
38,362 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/api/v2/serializers.py | 381,382 | 377,409 | validate | PasswordRecoverySmsConfirmSerializer | 382,400 | 382,400 | class PasswordRecoverySmsConfirmSerializer(serializers.Serializer):
sms_totp = serializers.CharField(min_length=6, max_length=6)
def validate(self, data):
FILL_FUNC_BODY def save(self):
self.context["request"].session.pop("totp_secret")
user_pk = self.context["request"].session.pop("user_pk... | class PasswordRecoverySmsConfirmSerializer(serializers.Serializer):
sms_totp = serializers.CharField(min_length=6, max_length=6)
def validate(self, data):
FILL_FUNC_BODY def save(self):
self.context["request"].session.pop("totp_secret")
user_pk = self.context["request"].session.pop("user_pk... | try:
self.context["totp_secret"] = self.context["request"].session["totp_secret"]
except KeyError:
raise CustomValidationError(
{"reason": "totp secret not set in session"}, 403
)
if not oath.accept_totp(self.context["totp_secret"], data["sms_t... | try:
self.context["totp_secret"] = self.context["request"].session["totp_secret"]
except KeyError:
raise CustomValidationError(
{"reason": "totp secret not set in session"}, 403
)
if not oath.accept_totp(self.context["totp_secret"], data["sms_t... | 56 | 173 | 228 | 401 | """Core API v2 serializers."""
import django_otp
import oath
from django.db.models import Q
from django.contrib.auth import password_validation
from django.contrib.sites.shortcuts import get_current_site
from django.contrib.auth.tokens import default_token_generator
from django.core.mail import send_mail
from django... | """Core API v2 serializers."""
import django_otp
import oath
from django.db.models import Q
from django.contrib.auth import password_validation
from django.contrib.sites.shortcuts import get_current_site
from django.contrib.auth.tokens import default_token_generator
from django.core.mail import send_mail
from django... |
38,363 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/api/v2/serializers.py | 411,412 | 409,436 | validate | PasswordRecoverySmsResendSerializer | 412,428 | 412,428 | class PasswordRecoverySmsResendSerializer(serializers.Serializer):
def validate(self, data):
FILL_FUNC_BODY def save(self):
backend = sms_backends.get_active_backend(
self.context["request"].localconfig.parameters
)
send_sms_code(self.context["totp_secret"], backend, self.con... | class PasswordRecoverySmsResendSerializer(serializers.Serializer):
def validate(self, data):
FILL_FUNC_BODY def save(self):
backend = sms_backends.get_active_backend(
self.context["request"].localconfig.parameters
)
send_sms_code(self.context["totp_secret"], backend, self.con... | try:
self.context["totp_secret"] = self.context["request"].session["totp_secret"]
except KeyError:
raise CustomValidationError(
{"reason": "totp secret not set in session"}, status.HTTP_403_FORBIDDEN
)
# Attempt to get user, will raise an erro... | try:
self.context["totp_secret"] = self.context["request"].session["totp_secret"]
except KeyError:
raise CustomValidationError(
{"reason": "totp secret not set in session"}, status.HTTP_403_FORBIDDEN
)
# Attempt to get user, will raise an erro... | 47 | 109 | 182 | 291 | """Core API v2 serializers."""
import django_otp
import oath
from django.db.models import Q
from django.contrib.auth import password_validation
from django.contrib.sites.shortcuts import get_current_site
from django.contrib.auth.tokens import default_token_generator
from django.core.mail import send_mail
from django... | """Core API v2 serializers."""
import django_otp
import oath
from django.db.models import Q
from django.contrib.auth import password_validation
from django.contrib.sites.shortcuts import get_current_site
from django.contrib.auth.tokens import default_token_generator
from django.core.mail import send_mail
from django... |
38,364 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/api/v2/serializers.py | 345,346 | 341,377 | validate | PasswordRecoverySmsSerializer | 346,377 | 346,377 | class PasswordRecoverySmsSerializer(serializers.Serializer):
email = serializers.EmailField()
def validate(self, data, *args, **kwargs):
FILL_FUNC_BODY | class PasswordRecoverySmsSerializer(serializers.Serializer):
email = serializers.EmailField()
def validate(self, data, *args, **kwargs):
FILL_FUNC_BODY | request = self.context["request"]
clean_email = data["email"]
user = User.objects.filter(email__iexact=clean_email, is_active=True).first()
if user is None:
raise CustomValidationError(
{"type": "sms", "reason": "No valid user found."}, 404
)
... | request = self.context["request"]
clean_email = data["email"]
user = User.objects.filter(email__iexact=clean_email, is_active=True).first()
if user is None:
raise CustomValidationError(
{"type": "sms", "reason": "No valid user found."}, 404
)
... | 71 | 52 | 354 | 406 | """Core API v2 serializers."""
import django_otp
import oath
from django.db.models import Q
from django.contrib.auth import password_validation
from django.contrib.sites.shortcuts import get_current_site
from django.contrib.auth.tokens import default_token_generator
from django.core.mail import send_mail
from django... | """Core API v2 serializers."""
import django_otp
import oath
from django.db.models import Q
from django.contrib.auth import password_validation
from django.contrib.sites.shortcuts import get_current_site
from django.contrib.auth.tokens import default_token_generator
from django.core.mail import send_mail
from django... |
38,365 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/api/v2/serializers.py | 259,260 | 254,266 | validate_code | VerifyTFACodeSerializer | 260,266 | 260,266 | class VerifyTFACodeSerializer(serializers.Serializer):
"""Serializer used to verify 2FA code validity."""
code = serializers.CharField()
def validate_code(self, value):
FILL_FUNC_BODY | class VerifyTFACodeSerializer(serializers.Serializer):
"""Serializer used to verify 2FA code validity."""
code = serializers.CharField()
def validate_code(self, value):
FILL_FUNC_BODY | device = django_otp.match_token(self.context["user"], value)
if device is None:
raise serializers.ValidationError(_("This code is invalid"))
return device
| device = django_otp.match_token(self.context["user"], value)
if device is None:
raise serializers.ValidationError(_("This code is invalid"))
return device
| 15 | 60 | 56 | 116 | """Core API v2 serializers."""
import django_otp
import oath
from django.db.models import Q
from django.contrib.auth import password_validation
from django.contrib.sites.shortcuts import get_current_site
from django.contrib.auth.tokens import default_token_generator
from django.core.mail import send_mail
from django... | """Core API v2 serializers."""
import django_otp
import oath
from django.db.models import Q
from django.contrib.auth import password_validation
from django.contrib.sites.shortcuts import get_current_site
from django.contrib.auth.tokens import default_token_generator
from django.core.mail import send_mail
from django... |
38,366 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/api/v2/tests.py | 280,281 | 186,316 | test_api_token | AccountViewSetTestCase | 281,299 | 281,299 | class AccountViewSetTestCase(ModoAPITestCase):
def test_me(self):
url = reverse("v2:account-me")
resp = self.client.get(url)
self.assertEqual(resp.status_code, 200)
me = resp.json()
self.assertEqual(me["username"], "admin")
def test_me_password(self, password_ko="Toto12... | class AccountViewSetTestCase(ModoAPITestCase):
def test_me(self):
url = reverse("v2:account-me")
resp = self.client.get(url)
self.assertEqual(resp.status_code, 200)
me = resp.json()
self.assertEqual(me["username"], "admin")
def test_me_password(self, password_ko="Toto12... | # 1. Obtain a JWT token so we can safely play with basic token
url = reverse("v2:token_obtain_pair")
data = {"username": "admin", "password": "password"}
resp = self.client.post(url, data, format="json")
self.assertEqual(resp.status_code, 200)
self.client.credentials(
... | # 1. Obtain a JWT token so we can safely play with basic token
url = reverse("v2:token_obtain_pair")
data = {"username": "admin", "password": "password"}
resp = self.client.post(url, data, format="json")
self.assertEqual(resp.status_code, 200)
self.client.credentials(
... | 54 | 1,436 | 270 | 1,706 | """Core API related tests."""
import copy
import getpass
import oath
from unittest import mock
from django.core.cache import cache
from django.test import override_settings
from django.urls import reverse
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from modoboa.a... | """Core API related tests."""
import copy
import getpass
import oath
from unittest import mock
from django.core.cache import cache
from django.test import override_settings
from django.urls import reverse
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from modoboa.a... |
38,367 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/api/v2/tests.py | 540,542 | 538,576 | test_2fa | AuthenticationTestCase | 542,576 | 542,576 | class AuthenticationTestCase(ModoAPITestCase):
@mock.patch("django_otp.match_token")
def test_2fa(self, match_mock):
FILL_FUNC_BODY | class AuthenticationTestCase(ModoAPITestCase):
@mock.patch("django_otp.match_token")
def test_2fa(self, match_mock):
FILL_FUNC_BODY | url = reverse("v2:token_obtain_pair")
me_url = reverse("v2:account-me")
data = {"username": "admin", "password": "password"}
resp = self.client.post(url, data, format="json")
self.assertEqual(resp.status_code, 200)
self.client.credentials(
HTTP_AUTHORIZATION=... | url = reverse("v2:token_obtain_pair")
me_url = reverse("v2:account-me")
data = {"username": "admin", "password": "password"}
resp = self.client.post(url, data, format="json")
self.assertEqual(resp.status_code, 200)
self.client.credentials(
HTTP_AUTHORIZATION=... | 75 | 54 | 445 | 499 | """Core API related tests."""
import copy
import getpass
import oath
from unittest import mock
from django.core.cache import cache
from django.test import override_settings
from django.urls import reverse
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from modoboa.a... | """Core API related tests."""
import copy
import getpass
import oath
from unittest import mock
from django.core.cache import cache
from django.test import override_settings
from django.urls import reverse
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from modoboa.a... |
38,368 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/api/v2/tests.py | 586,587 | 584,590 | test_information | ComponentAPITestCase | 587,590 | 587,590 | class ComponentAPITestCase(ModoAPITestCase):
def test_information(self):
FILL_FUNC_BODY | class ComponentAPITestCase(ModoAPITestCase):
def test_information(self):
FILL_FUNC_BODY | url = reverse("v2:components_information")
resp = self.client.get(url)
self.assertEqual(resp.status_code, 200)
| url = reverse("v2:components_information")
resp = self.client.get(url)
self.assertEqual(resp.status_code, 200)
| 8 | 35 | 45 | 80 | """Core API related tests."""
import copy
import getpass
import oath
from unittest import mock
from django.core.cache import cache
from django.test import override_settings
from django.urls import reverse
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from modoboa.a... | """Core API related tests."""
import copy
import getpass
import oath
from unittest import mock
from django.core.cache import cache
from django.test import override_settings
from django.urls import reverse
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from modoboa.a... |
38,369 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/api/v2/tests.py | 578,579 | 576,584 | test_list | LanguageViewSetTestCase | 579,584 | 579,584 | class LanguageViewSetTestCase(ModoAPITestCase):
def test_list(self):
FILL_FUNC_BODY | class LanguageViewSetTestCase(ModoAPITestCase):
def test_list(self):
FILL_FUNC_BODY | url = reverse("v2:language-list")
resp = self.client.get(url)
self.assertEqual(resp.status_code, 200)
| url = reverse("v2:language-list")
resp = self.client.get(url)
self.assertEqual(resp.status_code, 200)
| 8 | 34 | 49 | 83 | """Core API related tests."""
import copy
import getpass
import oath
from unittest import mock
from django.core.cache import cache
from django.test import override_settings
from django.urls import reverse
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from modoboa.a... | """Core API related tests."""
import copy
import getpass
import oath
from unittest import mock
from django.core.cache import cache
from django.test import override_settings
from django.urls import reverse
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from modoboa.a... |
38,370 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/api/v2/tests.py | 88,92 | 82,186 | test_update | ParametersAPITestCase | 92,139 | 92,139 | class ParametersAPITestCase(ModoAPITestCase):
def setUp(self):
super().setUp()
cache.delete("password_scheme_choice")
@override_settings(
DOVEADM_LOOKUP_PATH=[DOVEADM_TEST_PATH], DOVECOT_USER=DOVECOT_USER
)
def test_update(self):
FILL_FUNC_BODY def test_doveadm_alarm(self):
... | class ParametersAPITestCase(ModoAPITestCase):
def setUp(self):
super().setUp()
cache.delete("password_scheme_choice")
@override_settings(
DOVEADM_LOOKUP_PATH=[DOVEADM_TEST_PATH], DOVECOT_USER=DOVECOT_USER
)
def test_update(self):
FILL_FUNC_BODY def test_doveadm_alarm(self):
... | url = reverse("v2:parameter-detail", args=["core"])
data = copy.copy(CORE_SETTINGS)
resp = self.client.put(url, data, format="json")
self.assertEqual(resp.status_code, 200)
self.assertIsNotNone(cache.get("password_scheme_choice"))
self.assertIn(("plain", "plain (weak)"),... | url = reverse("v2:parameter-detail", args=["core"])
data = copy.copy(CORE_SETTINGS)
resp = self.client.put(url, data, format="json")
self.assertEqual(resp.status_code, 200)
self.assertIsNotNone(cache.get("password_scheme_choice"))
self.assertIn(("plain", "plain (weak)"),... | 111 | 755 | 680 | 1,435 | """Core API related tests."""
import copy
import getpass
import oath
from unittest import mock
from django.core.cache import cache
from django.test import override_settings
from django.urls import reverse
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from modoboa.a... | """Core API related tests."""
import copy
import getpass
import oath
from unittest import mock
from django.core.cache import cache
from django.test import override_settings
from django.urls import reverse
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from modoboa.a... |
38,372 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/api/v2/viewsets.py | 110,113 | 22,143 | tfa_setup_check | AccountViewSet | 114,143 | 113,143 | class AccountViewSet(core_v1_viewsets.AccountViewSet):
"""Account viewset."""
@extend_schema(responses=admin_v1_serializers.AccountSerializer)
@action(methods=["get"], detail=False)
def me(self, request):
"""Return information about connected user."""
serializer = admin_v1_serializers.A... | class AccountViewSet(core_v1_viewsets.AccountViewSet):
"""Account viewset."""
@extend_schema(responses=admin_v1_serializers.AccountSerializer)
@action(methods=["get"], detail=False)
def me(self, request):
"""Return information about connected user."""
serializer = admin_v1_serializers.A... | serializer = core_v1_serializers.CheckTFASetupSerializer(
data=request.data, context={"user": request.user}
)
serializer.is_valid(raise_exception=True)
# create static device for recovery purposes
device = StaticDevice.objects.create(
user=request.user, na... | """Check TFA setup."""
serializer = core_v1_serializers.CheckTFASetupSerializer(
data=request.data, context={"user": request.user}
)
serializer.is_valid(raise_exception=True)
# create static device for recovery purposes
device = StaticDevice.objects.create(
... | 75 | 1,033 | 330 | 1,363 | """Core API v2 viewsets."""
from django_otp.plugins.otp_static.models import StaticDevice, StaticToken
from drf_spectacular.utils import extend_schema
from rest_framework import filters, permissions, response, viewsets
from rest_framework.authtoken.models import Token
from rest_framework.decorators import action
from ... | """Core API v2 viewsets."""
from django_otp.plugins.otp_static.models import StaticDevice, StaticToken
from drf_spectacular.utils import extend_schema
from rest_framework import filters, permissions, response, viewsets
from rest_framework.authtoken.models import Token
from rest_framework.decorators import action
from ... |
38,373 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/api/v2/viewsets.py | 164,165 | 159,169 | list | LanguageViewSet | 165,169 | 165,169 | class LanguageViewSet(GetThrottleViewsetMixin, viewsets.ViewSet):
"""Language viewset."""
permission_classes = (permissions.IsAuthenticated,)
def list(self, request, *args, **kwargs):
FILL_FUNC_BODY | class LanguageViewSet(GetThrottleViewsetMixin, viewsets.ViewSet):
"""Language viewset."""
permission_classes = (permissions.IsAuthenticated,)
def list(self, request, *args, **kwargs):
FILL_FUNC_BODY | languages = [
{"code": lang[0], "label": lang[1]} for lang in constants.LANGUAGES
]
return response.Response(languages)
| languages = [
{"code": lang[0], "label": lang[1]} for lang in constants.LANGUAGES
]
return response.Response(languages)
| 14 | 71 | 48 | 119 | """Core API v2 viewsets."""
from django_otp.plugins.otp_static.models import StaticDevice, StaticToken
from drf_spectacular.utils import extend_schema
from rest_framework import filters, permissions, response, viewsets
from rest_framework.authtoken.models import Token
from rest_framework.decorators import action
from ... | """Core API v2 viewsets."""
from django_otp.plugins.otp_static.models import StaticDevice, StaticToken
from drf_spectacular.utils import extend_schema
from rest_framework import filters, permissions, response, viewsets
from rest_framework.authtoken.models import Token
from rest_framework.decorators import action
from ... |
38,374 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/apps.py | 8,9 | 1,44 | load_core_settings | 14,30 | 9,30 | """Core config for admin."""
from django.apps import AppConfig
from django.db.models import signals
from django.utils.translation import gettext_lazy
def load_core_settings():
FILL_FUNC_BODYclass CoreConfig(AppConfig):
"""App configuration."""
name = "modoboa.core"
verbose_name = "Modoboa core"
def... | """Core config for admin."""
from django.apps import AppConfig
from django.db.models import signals
from django.utils.translation import gettext_lazy
def load_core_settings():
"""Load core settings.
This function must be manually called (see :file:`urls.py`) in
order to load base settings.
"""
FILL_... | from modoboa.parameters import tools as param_tools
from . import app_settings
from .api.v2 import serializers
param_tools.registry.add(
"global", app_settings.GeneralParametersForm, gettext_lazy("General")
)
param_tools.registry.add2(
"global",
"core",
gettext_l... | """Load core settings.
This function must be manually called (see :file:`urls.py`) in
order to load base settings.
"""
from modoboa.parameters import tools as param_tools
from . import app_settings
from .api.v2 import serializers
param_tools.registry.add(
"global", app_settings... | 26 | 218 | 150 | 368 | """Core config for admin."""
from django.apps import AppConfig
from django.db.models import signals
from django.utils.translation import gettext_lazy
def load_core_settings():
FILL_FUNC_BODYclass CoreConfig(AppConfig):
"""App configuration."""
name = "modoboa.core"
verbose_name = "Modoboa core"
def... | """Core config for admin."""
from django.apps import AppConfig
from django.db.models import signals
from django.utils.translation import gettext_lazy
def load_core_settings():
"""Load core settings.
This function must be manually called (see :file:`urls.py`) in
order to load base settings.
"""
FILL_... | |
38,375 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/apps.py | 36,37 | 30,44 | ready | CoreConfig | 37,44 | 37,44 | class CoreConfig(AppConfig):
"""App configuration."""
name = "modoboa.core"
verbose_name = "Modoboa core"
def ready(self):
FILL_FUNC_BODY | class CoreConfig(AppConfig):
"""App configuration."""
name = "modoboa.core"
verbose_name = "Modoboa core"
def ready(self):
FILL_FUNC_BODY | load_core_settings()
# Import these to force registration of checks and signals
from . import checks # NOQA:F401
from . import handlers
signals.post_migrate.connect(handlers.create_local_config, sender=self)
| load_core_settings()
# Import these to force registration of checks and signals
from . import checks # NOQA:F401
from . import handlers
signals.post_migrate.connect(handlers.create_local_config, sender=self)
| 23 | 57 | 77 | 134 | """Core config for admin."""
from django.apps import AppConfig
from django.db.models import signals
from django.utils.translation import gettext_lazy
def load_core_settings():
"""Load core settings.
This function must be manually called (see :file:`urls.py`) in
order to load base settings.
"""
f... | """Core config for admin."""
from django.apps import AppConfig
from django.db.models import signals
from django.utils.translation import gettext_lazy
def load_core_settings():
"""Load core settings.
This function must be manually called (see :file:`urls.py`) in
order to load base settings.
"""
f... |
38,376 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/checks/settings_checks.py | 16,18 | 1,27 | check_use_tz_enabled | 23,27 | 18,27 | from django.conf import settings
from django.core.checks import Warning, register
from django.utils.translation import gettext as _
W001 = Warning(
_(
"You have USE_TZ set to False, this may result in issues during "
"transitions between summer/winter time (ie the same local time occuring "
... | from django.conf import settings
from django.core.checks import Warning, register
from django.utils.translation import gettext as _
W001 = Warning(
_(
"You have USE_TZ set to False, this may result in issues during "
"transitions between summer/winter time (ie the same local time occuring "
... | errors = []
if not settings.USE_TZ:
errors.append(W001)
return errors
| """Ensure USE_TZ is enabled in settings.py
When USE_TZ is enabled all date/times are stored in UTC.
Fixes #1086 - https://github.com/modoboa/modoboa/issues/1086
"""
errors = []
if not settings.USE_TZ:
errors.append(W001)
return errors
| 9 | 245 | 35 | 280 | from django.conf import settings
from django.core.checks import Warning, register
from django.utils.translation import gettext as _
W001 = Warning(
_(
"You have USE_TZ set to False, this may result in issues during "
"transitions between summer/winter time (ie the same local time occuring "
... | from django.conf import settings
from django.core.checks import Warning, register
from django.utils.translation import gettext as _
W001 = Warning(
_(
"You have USE_TZ set to False, this may result in issues during "
"transitions between summer/winter time (ie the same local time occuring "
... | |
38,378 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/commands/help.py | 14,15 | 6,22 | handle | HelpCommand | 15,22 | 15,22 | class HelpCommand(Command):
help = "Display the help message associated to a specific command" # NOQA:A003
def __init__(self, *args, **kwargs):
super(HelpCommand, self).__init__(*args, **kwargs)
self._parser.add_argument("name", type=str, help="A command name")
def handle(self, parsed_ar... | class HelpCommand(Command):
help = "Display the help message associated to a specific command" # NOQA:A003
def __init__(self, *args, **kwargs):
super(HelpCommand, self).__init__(*args, **kwargs)
self._parser.add_argument("name", type=str, help="A command name")
def handle(self, parsed_ar... | if parsed_args.name not in self._commands:
print("Unknown command: %s" % parsed_args.name, file=sys.stderr)
sys.exit(1)
cmd = self._commands[parsed_args.name](self._commands)
cmd._parser.prog = "modoboa-admin.py %s" % parsed_args.name
cmd._parser.description = cmd... | if parsed_args.name not in self._commands:
print("Unknown command: %s" % parsed_args.name, file=sys.stderr)
sys.exit(1)
cmd = self._commands[parsed_args.name](self._commands)
cmd._parser.prog = "modoboa-admin.py %s" % parsed_args.name
cmd._parser.description = cmd... | 25 | 111 | 122 | 233 | import sys
from . import Command
class HelpCommand(Command):
help = "Display the help message associated to a specific command" # NOQA:A003
def __init__(self, *args, **kwargs):
super(HelpCommand, self).__init__(*args, **kwargs)
self._parser.add_argument("name", type=str, help="A command na... | import sys
from . import Command
class HelpCommand(Command):
help = "Display the help message associated to a specific command" # NOQA:A003
def __init__(self, *args, **kwargs):
super(HelpCommand, self).__init__(*args, **kwargs)
self._parser.add_argument("name", type=str, help="A command na... |
38,379 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/context_processors.py | 9,10 | 1,29 | top_notifications | 11,26 | 10,26 | """Custom context processors."""
from functools import reduce
from django.conf import settings
from . import signals
def top_notifications(request):
FILL_FUNC_BODYdef new_admin_url(*args):
"""A context processor to include new admin url."""
return {"new_admin": getattr(settings, "NEW_ADMIN_URL", "new-admin"... | """Custom context processors."""
from functools import reduce
from django.conf import settings
from . import signals
def top_notifications(request):
"""A context processor to include top notifications."""
FILL_FUNC_BODYdef new_admin_url(*args):
"""A context processor to include new admin url."""
return ... | if request.user.is_anonymous:
return {}
interval = request.localconfig.parameters.get_value(
"top_notifications_check_interval"
)
notifications = signals.get_top_notifications.send(
sender="top_notifications", include_all=False
)
notifications = reduce(lambda a, b: a + b,... | """A context processor to include top notifications."""
if request.user.is_anonymous:
return {}
interval = request.localconfig.parameters.get_value(
"top_notifications_check_interval"
)
notifications = signals.get_top_notifications.send(
sender="top_notifications", include_al... | 37 | 110 | 158 | 268 | """Custom context processors."""
from functools import reduce
from django.conf import settings
from . import signals
def top_notifications(request):
FILL_FUNC_BODYdef new_admin_url(*args):
"""A context processor to include new admin url."""
return {"new_admin": getattr(settings, "NEW_ADMIN_URL", "new-admin"... | """Custom context processors."""
from functools import reduce
from django.conf import settings
from . import signals
def top_notifications(request):
"""A context processor to include top notifications."""
FILL_FUNC_BODYdef new_admin_url(*args):
"""A context processor to include new admin url."""
return ... | |
38,380 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/drf_authentication.py | 24,25 | 21,48 | verify_user | JWTAuthenticationWith2FA | 25,38 | 25,38 | class JWTAuthenticationWith2FA(JWTAuthentication):
"""Add 2FA support."""
def verify_user(self, request, user):
FILL_FUNC_BODY def authenticate(self, request):
result = super().authenticate(request)
if result is None:
return None
user, token = result
if user.tfa_e... | class JWTAuthenticationWith2FA(JWTAuthentication):
"""Add 2FA support."""
def verify_user(self, request, user):
FILL_FUNC_BODY def authenticate(self, request):
result = super().authenticate(request)
if result is None:
return None
user, token = result
if user.tfa_e... | header = self.get_header(request)
raw_token = self.get_raw_token(header)
validated_token = self.get_validated_token(raw_token)
url_exceptions = (reverse("v2:account-tfa-verify-code"),)
if request.path in url_exceptions:
return
if constants.TFA_DEVICE_TOKEN_KEY... | header = self.get_header(request)
raw_token = self.get_raw_token(header)
validated_token = self.get_validated_token(raw_token)
url_exceptions = (reverse("v2:account-tfa-verify-code"),)
if request.path in url_exceptions:
return
if constants.TFA_DEVICE_TOKEN_KEY... | 39 | 119 | 194 | 313 | """Custom authentication for DRF."""
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from django_otp.models import Device
from drf_spectacular.contrib.rest_framework_simplejwt import SimpleJWTScheme
from rest_framework import status
from rest_framework.exceptions import APIExcep... | """Custom authentication for DRF."""
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from django_otp.models import Device
from drf_spectacular.contrib.rest_framework_simplejwt import SimpleJWTScheme
from rest_framework import status
from rest_framework.exceptions import APIExcep... |
38,381 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/extensions.py | 105,106 | 53,135 | get_urls | ExtensionsPool | 107,123 | 106,123 | class ExtensionsPool(object):
"""The extensions manager"""
def __init__(self):
self.extensions = {}
def register_extension(self, ext, show=True):
"""Register an extension.
:param ext: a class inheriting from ``Extension``
:param show: list the extension or not
"""
... | class ExtensionsPool(object):
"""The extensions manager"""
def __init__(self):
self.extensions = {}
def register_extension(self, ext, show=True):
"""Register an extension.
:param ext: a class inheriting from ``Extension``
:param show: list the extension or not
"""
... | result = []
for ext_name in list(self.extensions.keys()):
ext = self.get_extension(ext_name)
if category == "api":
root = ""
pattern = "{}.urls_api"
else:
root = r"^{}/".format(ext.get_url())
pattern = "{... | """Get all urls defined by extensions."""
result = []
for ext_name in list(self.extensions.keys()):
ext = self.get_extension(ext_name)
if category == "api":
root = ""
pattern = "{}.urls_api"
else:
root = r"^{}/".... | 41 | 603 | 158 | 761 | """Extension management."""
from django.conf import settings
from django.urls import include
from django.urls import re_path
from django.utils.encoding import smart_str
class ModoExtension(object):
"""
Base extension class.
Each Modoboa extension must inherit from this class to be
considered as vali... | """Extension management."""
from django.conf import settings
from django.urls import include
from django.urls import re_path
from django.utils.encoding import smart_str
class ModoExtension(object):
"""
Base extension class.
Each Modoboa extension must inherit from this class to be
considered as vali... |
38,382 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/extensions.py | 26,27 | 9,53 | get_url | ModoExtension | 28,32 | 27,32 | class ModoExtension(object):
"""
Base extension class.
Each Modoboa extension must inherit from this class to be
considered as valid.
"""
name = None
label = None
version = "NA"
description = ""
needs_media = False
always_active = False
url = None
topredirection_url... | class ModoExtension(object):
"""
Base extension class.
Each Modoboa extension must inherit from this class to be
considered as valid.
"""
name = None
label = None
version = "NA"
description = ""
needs_media = False
always_active = False
url = None
topredirection_url... | if self.url is None:
return self.name
return self.url
| """Return extension base url."""
if self.url is None:
return self.name
return self.url
| 8 | 270 | 26 | 296 | """Extension management."""
from django.conf import settings
from django.urls import include
from django.urls import re_path
from django.utils.encoding import smart_str
class ModoExtension(object):
"""
Base extension class.
Each Modoboa extension must inherit from this class to be
considered as vali... | """Extension management."""
from django.conf import settings
from django.urls import include
from django.urls import re_path
from django.utils.encoding import smart_str
class ModoExtension(object):
"""
Base extension class.
Each Modoboa extension must inherit from this class to be
considered as vali... |
38,383 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/forms.py | 145,154 | 134,166 | send_mail | PasswordResetForm | 155,166 | 154,166 | class PasswordResetForm(auth_forms.PasswordResetForm):
"""Custom password reset form."""
def get_users(self, email):
"""Return matching user(s) who should receive a reset."""
return (
get_user_model()
._default_manager.filter(email__iexact=email, is_active=True)
... | class PasswordResetForm(auth_forms.PasswordResetForm):
"""Custom password reset form."""
def get_users(self, email):
"""Return matching user(s) who should receive a reset."""
return (
get_user_model()
._default_manager.filter(email__iexact=email, is_active=True)
... | to_email = context["user"].secondary_email
super(PasswordResetForm, self).send_mail(
subject_template_name,
email_template_name,
context,
from_email,
to_email,
html_email_template_name,
)
| """Send message to secondary email instead."""
to_email = context["user"].secondary_email
super(PasswordResetForm, self).send_mail(
subject_template_name,
email_template_name,
context,
from_email,
to_email,
html_email_templa... | 12 | 195 | 85 | 280 | """Core forms."""
import oath
from django import forms
from django.contrib.auth import forms as auth_forms, get_user_model, password_validation
from django.db.models import Q
from django.utils.translation import gettext as _, gettext_lazy
import django_otp
from modoboa.core.models import User
from modoboa.lib.form_... | """Core forms."""
import oath
from django import forms
from django.contrib.auth import forms as auth_forms, get_user_model, password_validation
from django.db.models import Q
from django.utils.translation import gettext as _, gettext_lazy
import django_otp
from modoboa.core.models import User
from modoboa.lib.form_... |
38,384 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/forms.py | 82,83 | 31,120 | clean | ProfileForm | 83,109 | 83,109 | class ProfileForm(forms.ModelForm):
"""Form to update User profile."""
oldpassword = forms.CharField(
label=gettext_lazy("Old password"),
required=False,
widget=forms.PasswordInput(attrs={"class": "form-control"}),
)
newpassword = forms.CharField(
label=gettext_lazy("New... | class ProfileForm(forms.ModelForm):
"""Form to update User profile."""
oldpassword = forms.CharField(
label=gettext_lazy("Old password"),
required=False,
widget=forms.PasswordInput(attrs={"class": "form-control"}),
)
newpassword = forms.CharField(
label=gettext_lazy("New... | super().clean()
if self.errors:
return self.cleaned_data
oldpassword = self.cleaned_data.get("oldpassword")
newpassword = self.cleaned_data.get("newpassword")
confirmation = self.cleaned_data.get("confirmation")
if newpassword and confirmation:
if ... | super().clean()
if self.errors:
return self.cleaned_data
oldpassword = self.cleaned_data.get("oldpassword")
newpassword = self.cleaned_data.get("newpassword")
confirmation = self.cleaned_data.get("confirmation")
if newpassword and confirmation:
if ... | 65 | 603 | 283 | 886 | """Core forms."""
import oath
from django import forms
from django.contrib.auth import forms as auth_forms, get_user_model, password_validation
from django.db.models import Q
from django.utils.translation import gettext as _, gettext_lazy
import django_otp
from modoboa.core.models import User
from modoboa.lib.form_... | """Core forms."""
import oath
from django import forms
from django.contrib.auth import forms as auth_forms, get_user_model, password_validation
from django.db.models import Q
from django.utils.translation import gettext as _, gettext_lazy
import django_otp
from modoboa.core.models import User
from modoboa.lib.form_... |
38,385 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/forms.py | 190,191 | 185,196 | clean_tfa_code | Verify2FACodeForm | 191,196 | 191,196 | class Verify2FACodeForm(UserKwargModelFormMixin, forms.Form):
"""A form to verify 2FA codes validity."""
tfa_code = forms.CharField()
def clean_tfa_code(self):
FILL_FUNC_BODY | class Verify2FACodeForm(UserKwargModelFormMixin, forms.Form):
"""A form to verify 2FA codes validity."""
tfa_code = forms.CharField()
def clean_tfa_code(self):
FILL_FUNC_BODY | code = self.cleaned_data["tfa_code"]
device = django_otp.match_token(self.user, code)
if device is None:
raise forms.ValidationError(_("This code is invalid"))
return device
| code = self.cleaned_data["tfa_code"]
device = django_otp.match_token(self.user, code)
if device is None:
raise forms.ValidationError(_("This code is invalid"))
return device
| 18 | 72 | 66 | 138 | """Core forms."""
import oath
from django import forms
from django.contrib.auth import forms as auth_forms, get_user_model, password_validation
from django.db.models import Q
from django.utils.translation import gettext as _, gettext_lazy
import django_otp
from modoboa.core.models import User
from modoboa.lib.form_... | """Core forms."""
import oath
from django import forms
from django.contrib.auth import forms as auth_forms, get_user_model, password_validation
from django.db.models import Q
from django.utils.translation import gettext as _, gettext_lazy
import django_otp
from modoboa.core.models import User
from modoboa.lib.form_... |
38,386 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/forms.py | 178,179 | 166,185 | clean_code | VerifySMSCodeForm | 179,185 | 179,185 | class VerifySMSCodeForm(forms.Form):
"""A form to verify a code received by SMS."""
code = forms.CharField(
label=gettext_lazy("Verification code"),
widget=forms.widgets.TextInput(attrs={"class": "form-control"}),
)
def __init__(self, *args, **kwargs):
self.totp_secret = kwargs... | class VerifySMSCodeForm(forms.Form):
"""A form to verify a code received by SMS."""
code = forms.CharField(
label=gettext_lazy("Verification code"),
widget=forms.widgets.TextInput(attrs={"class": "form-control"}),
)
def __init__(self, *args, **kwargs):
self.totp_secret = kwargs... | code = self.cleaned_data["code"]
if not oath.accept_totp(self.totp_secret, code)[0]:
raise forms.ValidationError(_("Invalid code"))
return code
| code = self.cleaned_data["code"]
if not oath.accept_totp(self.totp_secret, code)[0]:
raise forms.ValidationError(_("Invalid code"))
return code
| 12 | 146 | 59 | 205 | """Core forms."""
import oath
from django import forms
from django.contrib.auth import forms as auth_forms, get_user_model, password_validation
from django.db.models import Q
from django.utils.translation import gettext as _, gettext_lazy
import django_otp
from modoboa.core.models import User
from modoboa.lib.form_... | """Core forms."""
import oath
from django import forms
from django.contrib.auth import forms as auth_forms, get_user_model, password_validation
from django.db.models import Q
from django.utils.translation import gettext as _, gettext_lazy
import django_otp
from modoboa.core.models import User
from modoboa.lib.form_... |
38,387 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/handlers.py | 50,52 | 1,132 | log_object_removal | 56,77 | 52,77 | """Modoboa core signal handlers."""
import logging
from reversion import revisions as reversion
from reversion.models import Version
from django.contrib.sites import models as sites_models
from django.db.models import signals
from django.dispatch import receiver
from django.urls import reverse
from django.utils.enco... | """Modoboa core signal handlers."""
import logging
from reversion import revisions as reversion
from reversion.models import Version
from django.contrib.sites import models as sites_models
from django.db.models import signals
from django.dispatch import receiver
from django.urls import reverse
from django.utils.enco... | if not reversion.is_registered(sender):
return
del_list = Version.objects.get_deleted(sender)
try:
version = del_list.get(object_id=instance.id)
except Version.DoesNotExist:
return
logger = logging.getLogger("modoboa.admin")
msg = _("%(object)s '%(name)s' %(action)s by ")... | """Custom post-delete hook.
We want to know who was responsible for an object deletion.
"""
if not reversion.is_registered(sender):
return
del_list = Version.objects.get_deleted(sender)
try:
version = del_list.get(object_id=instance.id)
except Version.DoesNotExist:
r... | 48 | 1,114 | 230 | 1,344 | """Modoboa core signal handlers."""
import logging
from reversion import revisions as reversion
from reversion.models import Version
from django.contrib.sites import models as sites_models
from django.db.models import signals
from django.dispatch import receiver
from django.urls import reverse
from django.utils.enco... | """Modoboa core signal handlers."""
import logging
from reversion import revisions as reversion
from reversion.models import Version
from django.contrib.sites import models as sites_models
from django.db.models import signals
from django.dispatch import receiver
from django.urls import reverse
from django.utils.enco... | |
38,388 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/loggers.py | 6,7 | 4,12 | emit | SQLHandler | 7,12 | 7,12 | class SQLHandler(logging.Handler):
def emit(self, record):
FILL_FUNC_BODY | class SQLHandler(logging.Handler):
def emit(self, record):
FILL_FUNC_BODY | from .models import Log
Log.objects.create(
message=record.getMessage(), level=record.levelname, logger=record.name
)
| from .models import Log
Log.objects.create(
message=record.getMessage(), level=record.levelname, logger=record.name
)
| 9 | 29 | 44 | 73 | import logging
class SQLHandler(logging.Handler):
def emit(self, record):
FILL_FUNC_BODY | import logging
class SQLHandler(logging.Handler):
def emit(self, record):
FILL_FUNC_BODY |
38,389 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/management/commands/clean_inactive_accounts.py | 52,53 | 12,82 | handle | Command | 54,82 | 53,82 | class Command(BaseCommand):
"""Management command to clean inactive accounts."""
help = "Inactive accounts cleanup" # NOQA:A003
def add_arguments(self, parser):
"""Add extra arguments to command line."""
parser.add_argument(
"--delete",
action="store_true",
... | class Command(BaseCommand):
"""Management command to clean inactive accounts."""
help = "Inactive accounts cleanup" # NOQA:A003
def add_arguments(self, parser):
"""Add extra arguments to command line."""
parser.add_argument(
"--delete",
action="store_true",
... | if not param_tools.get_global_parameter("enable_inactive_accounts"):
if options["verbose"]:
print("Inactive accounts detection is disabled.", file=self.stdout)
return
inactive_account_threshold = param_tools.get_global_parameter(
"inactive_account_thre... | """Command entry point."""
if not param_tools.get_global_parameter("enable_inactive_accounts"):
if options["verbose"]:
print("Inactive accounts detection is disabled.", file=self.stdout)
return
inactive_account_threshold = param_tools.get_global_parameter(... | 68 | 386 | 328 | 714 | """Inactive accounts cleanup tool."""
from dateutil.relativedelta import relativedelta
from django.core.management.base import BaseCommand
from django.utils import timezone
from modoboa.parameters import tools as param_tools
from ... import models
class Command(BaseCommand):
"""Management command to clean inac... | """Inactive accounts cleanup tool."""
from dateutil.relativedelta import relativedelta
from django.core.management.base import BaseCommand
from django.utils import timezone
from modoboa.parameters import tools as param_tools
from ... import models
class Command(BaseCommand):
"""Management command to clean inac... |
38,390 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/management/commands/cleanlogs.py | 16,17 | 11,45 | add_arguments | Command | 18,28 | 17,28 | class Command(BaseCommand):
"""Command class."""
help = "Log table cleanup" # NOQA:A003
def add_arguments(self, parser):
FILL_FUNC_BODY def __vprint(self, msg):
if not self.verbose:
return
print(msg)
def handle(self, *args, **options):
if options["debug"]:
... | class Command(BaseCommand):
"""Command class."""
help = "Log table cleanup" # NOQA:A003
def add_arguments(self, parser):
"""Add extra arguments to command line."""
FILL_FUNC_BODY def __vprint(self, msg):
if not self.verbose:
return
print(msg)
def handle(self, *... | parser.add_argument(
"--debug", action="store_true", default=False, help="Activate debug output"
)
parser.add_argument(
"--verbose",
action="store_true",
default=False,
help="Display informational messages",
)
| """Add extra arguments to command line."""
parser.add_argument(
"--debug", action="store_true", default=False, help="Activate debug output"
)
parser.add_argument(
"--verbose",
action="store_true",
default=False,
help="Display in... | 16 | 270 | 90 | 360 | import datetime
import logging
from django.core.management.base import BaseCommand
from django.utils import timezone
from modoboa.core.models import Log
from modoboa.parameters import tools as param_tools
class Command(BaseCommand):
"""Command class."""
help = "Log table cleanup" # NOQA:A003
def add_... | import datetime
import logging
from django.core.management.base import BaseCommand
from django.utils import timezone
from modoboa.core.models import Log
from modoboa.parameters import tools as param_tools
class Command(BaseCommand):
"""Command class."""
help = "Log table cleanup" # NOQA:A003
def add_... |
38,391 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/management/commands/communicate_with_public_api.py | 54,55 | 15,94 | handle | Command | 56,94 | 55,94 | class Command(BaseCommand):
"""Command class."""
help = "Communicate with Modoboa public API." # NOQA:A003
def send_notification(self, local_config, extensions):
"""Send email notification about updates."""
updates = {}
to_create = []
for extension in extensions:
... | class Command(BaseCommand):
"""Command class."""
help = "Communicate with Modoboa public API." # NOQA:A003
def send_notification(self, local_config, extensions):
"""Send email notification about updates."""
updates = {}
to_create = []
for extension in extensions:
... | local_config = models.LocalConfig.objects.select_related("site").first()
if not local_config.parameters.get_value("enable_api_communication"):
return
self.client = api_client.ModoAPIClient()
if not local_config.api_pk:
pk = self.client.register_instance(local_conf... | """Command entry point."""
local_config = models.LocalConfig.objects.select_related("site").first()
if not local_config.parameters.get_value("enable_api_communication"):
return
self.client = api_client.ModoAPIClient()
if not local_config.api_pk:
pk = self.... | 91 | 381 | 498 | 879 | """Management command to communicate with public API."""
from django.core.mail import EmailMessage
from django.core.management.base import BaseCommand, CommandError
from django.template.loader import render_to_string
from django.utils.translation import gettext as _
from modoboa.admin import models as admin_models
fr... | """Management command to communicate with public API."""
from django.core.mail import EmailMessage
from django.core.management.base import BaseCommand, CommandError
from django.template.loader import render_to_string
from django.utils.translation import gettext as _
from modoboa.admin import models as admin_models
fr... |
38,392 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/management/commands/generate_postfix_maps.py | 123,124 | 24,173 | __render_map_file | Command | 125,154 | 124,154 | class Command(BaseCommand):
"""Command class."""
help = "Generate/update postfix map files." # NOQA:A003
def add_arguments(self, parser):
"""Add extra arguments."""
parser.add_argument("--dburl", help="Custom database url")
parser.add_argument(
"--destdir", default="."... | class Command(BaseCommand):
"""Command class."""
help = "Generate/update postfix map files." # NOQA:A003
def add_arguments(self, parser):
"""Add extra arguments."""
parser.add_argument("--dburl", help="Custom database url")
parser.add_argument(
"--destdir", default="."... | fullpath = os.path.join(destdir, mapobject.filename)
if os.path.exists(fullpath) and not force_overwrite:
if not self.__check_file(fullpath):
print(
"Cannot upgrade '{}' map because it has been modified.".format(
mapobject.filename
... | """Render a map file."""
fullpath = os.path.join(destdir, mapobject.filename)
if os.path.exists(fullpath) and not force_overwrite:
if not self.__check_file(fullpath):
print(
"Cannot upgrade '{}' map because it has been modified.".format(
... | 77 | 1,261 | 379 | 1,640 | """Management command to generate/update postfix map files."""
import copy
import hashlib
import os
import sys
import dj_database_url
from django.conf import settings
from django.core.management.base import BaseCommand
from django.template import Context, Template
from django.utils import timezone
from django.utils.... | """Management command to generate/update postfix map files."""
import copy
import hashlib
import os
import sys
import dj_database_url
from django.conf import settings
from django.core.management.base import BaseCommand
from django.template import Context, Template
from django.utils import timezone
from django.utils.... |
38,393 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/management/commands/load_initial_data.py | 37,38 | 18,79 | handle | Command | 39,79 | 38,79 | class Command(BaseCommand):
"""Command definition."""
help = "Load Modoboa initial data" # NOQA:A003
def add_arguments(self, parser):
"""Add extra arguments to command."""
parser.add_argument(
"--admin-username",
default="admin",
help="Username of the i... | class Command(BaseCommand):
"""Command definition."""
help = "Load Modoboa initial data" # NOQA:A003
def add_arguments(self, parser):
"""Add extra arguments to command."""
parser.add_argument(
"--admin-username",
default="admin",
help="Username of the i... | extensions.exts_pool.load_all()
if not models.User.objects.filter(is_superuser=True).count():
admin = models.User(username=options["admin_username"], is_superuser=True)
admin.set_password("password")
admin.save()
models.ObjectAccess.objects.create(
... | """Command entry point."""
extensions.exts_pool.load_all()
if not models.User.objects.filter(is_superuser=True).count():
admin = models.User(username=options["admin_username"], is_superuser=True)
admin.set_password("password")
admin.save()
models.... | 93 | 177 | 462 | 639 | """
A management command to load Modoboa initial data.
* Create a default super admin if none exists
* Create groups and permissions
"""
from functools import reduce
from django.contrib.auth.models import Group
from django.core.management.base import BaseCommand
from modoboa.lib.permissions import add_permissions_... | """
A management command to load Modoboa initial data.
* Create a default super admin if none exists
* Create groups and permissions
"""
from functools import reduce
from django.contrib.auth.models import Group
from django.core.management.base import BaseCommand
from modoboa.lib.permissions import add_permissions_... |
38,394 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/management/commands/set_default_site.py | 16,17 | 11,28 | add_arguments | Command | 18,20 | 17,20 | class Command(BaseCommand):
"""Management command to set the default site."""
help = "Set default site (see django.contrib.sites)" # NOQA:A003
def add_arguments(self, parser):
FILL_FUNC_BODY def handle(self, *args, **options):
"""Command entry point."""
if "hostname" not in options:
... | class Command(BaseCommand):
"""Management command to set the default site."""
help = "Set default site (see django.contrib.sites)" # NOQA:A003
def add_arguments(self, parser):
"""Define command arguments."""
FILL_FUNC_BODY def handle(self, *args, **options):
"""Command entry point."""
... | parser.add_argument("hostname", type=str)
| """Define command arguments."""
parser.add_argument("hostname", type=str)
| 2 | 163 | 18 | 181 | """
A simple managemenent command to update the default site.
See `https://docs.djangoproject.com/en/dev/ref/contrib/sites/`_.
"""
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
"""Management command to set the default s... | """
A simple managemenent command to update the default site.
See `https://docs.djangoproject.com/en/dev/ref/contrib/sites/`_.
"""
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
"""Management command to set the default s... |
38,395 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/middleware.py | 13,14 | 10,18 | process_request | LocalConfigMiddleware | 15,18 | 14,18 | class LocalConfigMiddleware(MiddlewareMixin):
"""A middleware to inject LocalConfig into request."""
def process_request(self, request):
FILL_FUNC_BODY | class LocalConfigMiddleware(MiddlewareMixin):
"""A middleware to inject LocalConfig into request."""
def process_request(self, request):
"""Inject LocalConfig instance to request."""
FILL_FUNC_BODY | request.localconfig = models.LocalConfig.objects.first()
| """Inject LocalConfig instance to request."""
request.localconfig = models.LocalConfig.objects.first()
| 3 | 60 | 21 | 81 | """Core middlewares."""
from django import http
from django.urls import reverse
from django.utils.deprecation import MiddlewareMixin
from . import models
class LocalConfigMiddleware(MiddlewareMixin):
"""A middleware to inject LocalConfig into request."""
def process_request(self, request):
FILL_FUNC_BODYcl... | """Core middlewares."""
from django import http
from django.urls import reverse
from django.utils.deprecation import MiddlewareMixin
from . import models
class LocalConfigMiddleware(MiddlewareMixin):
"""A middleware to inject LocalConfig into request."""
def process_request(self, request):
"""Injec... |
38,396 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/migrations/0010_auto_20161026_1011.py | 5,6 | 1,64 | set_parameter | 7,21 | 6,21 | # Generated by Django 1.9.5 on 2016-10-26 08:11
from django.db import migrations, models
def set_parameter(store, parameter):
FILL_FUNC_BODYdef move_parameters(apps, schema_editor):
"""Move global and user parameters."""
Parameter = apps.get_model("lib", "Parameter")
LocalConfig = apps.get_model("core", "... | # Generated by Django 1.9.5 on 2016-10-26 08:11
from django.db import migrations, models
def set_parameter(store, parameter):
"""Add parameter to the specified store."""
FILL_FUNC_BODYdef move_parameters(apps, schema_editor):
"""Move global and user parameters."""
Parameter = apps.get_model("lib", "Parame... | app, name = parameter.name.split(".")
if app not in store:
store[app] = {}
# decode value
value = parameter.value.decode("unicode_escape")
if value == "yes":
value = True
elif value == "no":
value = False
elif value.isdigit():
value = int(value)
store[app]... | """Add parameter to the specified store."""
app, name = parameter.name.split(".")
if app not in store:
store[app] = {}
# decode value
value = parameter.value.decode("unicode_escape")
if value == "yes":
value = True
elif value == "no":
value = False
elif value.isdi... | 40 | 462 | 122 | 584 | # Generated by Django 1.9.5 on 2016-10-26 08:11
from django.db import migrations, models
def set_parameter(store, parameter):
FILL_FUNC_BODYdef move_parameters(apps, schema_editor):
"""Move global and user parameters."""
Parameter = apps.get_model("lib", "Parameter")
LocalConfig = apps.get_model("core", "... | # Generated by Django 1.9.5 on 2016-10-26 08:11
from django.db import migrations, models
def set_parameter(store, parameter):
"""Add parameter to the specified store."""
FILL_FUNC_BODYdef move_parameters(apps, schema_editor):
"""Move global and user parameters."""
Parameter = apps.get_model("lib", "Parame... | |
38,397 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/migrations/0012_auto_20170215_1034.py | 5,6 | 1,29 | rename_settings | 7,22 | 6,22 | # Generated by Django 1.10.5 on 2017-02-15 09:34
from django.db import migrations
def rename_settings(apps, schema_editor):
FILL_FUNC_BODYclass Migration(migrations.Migration):
dependencies = [
("core", "0011_auto_20161104_2217"),
]
operations = [migrations.RunPython(rename_settings)]
| # Generated by Django 1.10.5 on 2017-02-15 09:34
from django.db import migrations
def rename_settings(apps, schema_editor):
"""Rename settings."""
FILL_FUNC_BODYclass Migration(migrations.Migration):
dependencies = [
("core", "0011_auto_20161104_2217"),
]
operations = [migrations.RunPython(r... | LocalConfig = apps.get_model("core", "LocalConfig")
lc = LocalConfig.objects.first()
condition = (
lc
and "admin" in lc._parameters
and "default_domain_quota" in lc._parameters["admin"]
)
if condition:
lc._parameters["admin"]["default_mailbox_quota"] = lc._parameters[... | """Rename settings."""
LocalConfig = apps.get_model("core", "LocalConfig")
lc = LocalConfig.objects.first()
condition = (
lc
and "admin" in lc._parameters
and "default_domain_quota" in lc._parameters["admin"]
)
if condition:
lc._parameters["admin"]["default_mailbo... | 30 | 139 | 167 | 306 | # Generated by Django 1.10.5 on 2017-02-15 09:34
from django.db import migrations
def rename_settings(apps, schema_editor):
FILL_FUNC_BODYclass Migration(migrations.Migration):
dependencies = [
("core", "0011_auto_20161104_2217"),
]
operations = [migrations.RunPython(rename_settings)]
| # Generated by Django 1.10.5 on 2017-02-15 09:34
from django.db import migrations
def rename_settings(apps, schema_editor):
"""Rename settings."""
FILL_FUNC_BODYclass Migration(migrations.Migration):
dependencies = [
("core", "0011_auto_20161104_2217"),
]
operations = [migrations.RunPython(r... | |
38,398 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/migrations/0014_auto_20171010_1746.py | 5,6 | 1,32 | update_ldap_secured | 7,18 | 6,18 | # Generated by Django 1.10.7 on 2017-10-10 15:46
from django.db import migrations
def update_ldap_secured(apps, schema_editor):
FILL_FUNC_BODYdef forward(apps, schema_editor):
"""Empty forward method."""
pass
class Migration(migrations.Migration):
dependencies = [
("core", "0013_auto_20170707_1... | # Generated by Django 1.10.7 on 2017-10-10 15:46
from django.db import migrations
def update_ldap_secured(apps, schema_editor):
"""Update ldap_secured settings."""
FILL_FUNC_BODYdef forward(apps, schema_editor):
"""Empty forward method."""
pass
class Migration(migrations.Migration):
dependencies = ... | LocalConfig = apps.get_model("core", "LocalConfig")
lc = LocalConfig.objects.first()
if lc is None or "ldap_secured" not in lc._parameters:
return
if lc._parameters["ldap_secured"]:
lc._parameters["ldap_secured"] = "ssl"
else:
lc._parameters["ldap_secured"] = "none"
lc.sa... | """Update ldap_secured settings."""
LocalConfig = apps.get_model("core", "LocalConfig")
lc = LocalConfig.objects.first()
if lc is None or "ldap_secured" not in lc._parameters:
return
if lc._parameters["ldap_secured"]:
lc._parameters["ldap_secured"] = "ssl"
else:
lc._param... | 27 | 178 | 136 | 314 | # Generated by Django 1.10.7 on 2017-10-10 15:46
from django.db import migrations
def update_ldap_secured(apps, schema_editor):
FILL_FUNC_BODYdef forward(apps, schema_editor):
"""Empty forward method."""
pass
class Migration(migrations.Migration):
dependencies = [
("core", "0013_auto_20170707_1... | # Generated by Django 1.10.7 on 2017-10-10 15:46
from django.db import migrations
def update_ldap_secured(apps, schema_editor):
"""Update ldap_secured settings."""
FILL_FUNC_BODYdef forward(apps, schema_editor):
"""Empty forward method."""
pass
class Migration(migrations.Migration):
dependencies = ... | |
38,401 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/password_hashers/advanced.py | 176,177 | 139,185 | verify | ARGON2IDHasher | 177,182 | 177,182 | class ARGON2IDHasher(PasswordHasher):
"""
argon2 password hasher.
Supports rounds, memory and number of threads. To be set in settings.py.
It is the strongest scheme provided by modoboa
but can only be used with dovecot >= 2.3 and libsodium >= 1.0.13
"""
def... | class ARGON2IDHasher(PasswordHasher):
"""
argon2 password hasher.
Supports rounds, memory and number of threads. To be set in settings.py.
It is the strongest scheme provided by modoboa
but can only be used with dovecot >= 2.3 and libsodium >= 1.0.13
"""
def... | try:
return self.hasher.verify(hashed_value, clearvalue)
except argon2_exceptions.VerifyMismatchError:
return False
| try:
return self.hasher.verify(hashed_value, clearvalue)
except argon2_exceptions.VerifyMismatchError:
return False
| 8 | 456 | 49 | 505 | """
Advanced (ie. stronger) password hashers.
This module relies on `passlib` to provide more secure hashers.
"""
from passlib.hash import bcrypt, md5_crypt, sha256_crypt, sha512_crypt, ldap_salted_sha1
try:
from argon2 import PasswordHasher as argon2_hasher
from argon2 import exceptions as argon2_exceptions... | """
Advanced (ie. stronger) password hashers.
This module relies on `passlib` to provide more secure hashers.
"""
from passlib.hash import bcrypt, md5_crypt, sha256_crypt, sha512_crypt, ldap_salted_sha1
try:
from argon2 import PasswordHasher as argon2_hasher
from argon2 import exceptions as argon2_exceptions... |
38,402 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/password_hashers/advanced.py | 45,46 | 21,49 | verify | BLFCRYPTHasher | 46,49 | 46,49 | class BLFCRYPTHasher(PasswordHasher):
"""
BLF-CRYPT password hasher.
Supports rounds and provides compatibility with dovecot on
*BSD systems.
"""
@property
def scheme(self):
return "{BLF-CRYPT}" if self._target == "local" else "{CRYPT}"
def _b64encode(self, pwhash):
re... | class BLFCRYPTHasher(PasswordHasher):
"""
BLF-CRYPT password hasher.
Supports rounds and provides compatibility with dovecot on
*BSD systems.
"""
@property
def scheme(self):
return "{BLF-CRYPT}" if self._target == "local" else "{CRYPT}"
def _b64encode(self, pwhash):
re... | return bcrypt.verify(clearvalue, hashed_value)
| return bcrypt.verify(clearvalue, hashed_value)
| 3 | 259 | 22 | 281 | """
Advanced (ie. stronger) password hashers.
This module relies on `passlib` to provide more secure hashers.
"""
from passlib.hash import bcrypt, md5_crypt, sha256_crypt, sha512_crypt, ldap_salted_sha1
try:
from argon2 import PasswordHasher as argon2_hasher
from argon2 import exceptions as argon2_exceptions... | """
Advanced (ie. stronger) password hashers.
This module relies on `passlib` to provide more secure hashers.
"""
from passlib.hash import bcrypt, md5_crypt, sha256_crypt, sha512_crypt, ldap_salted_sha1
try:
from argon2 import PasswordHasher as argon2_hasher
from argon2 import exceptions as argon2_exceptions... |
38,403 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/password_hashers/advanced.py | 68,69 | 49,72 | verify | MD5CRYPTHasher | 69,72 | 69,72 | class MD5CRYPTHasher(PasswordHasher):
"""
MD5-CRYPT password hasher.
This scheme can't be considered as secure anymore.
"""
_weak = True
@property
def scheme(self):
return "{MD5-CRYPT}" if self._target == "local" else "{CRYPT}"
def _b64encode(self, pwhash):
return pwh... | class MD5CRYPTHasher(PasswordHasher):
"""
MD5-CRYPT password hasher.
This scheme can't be considered as secure anymore.
"""
_weak = True
@property
def scheme(self):
return "{MD5-CRYPT}" if self._target == "local" else "{CRYPT}"
def _b64encode(self, pwhash):
return pwh... | return md5_crypt.verify(clearvalue, hashed_value)
| return md5_crypt.verify(clearvalue, hashed_value)
| 3 | 171 | 24 | 195 | """
Advanced (ie. stronger) password hashers.
This module relies on `passlib` to provide more secure hashers.
"""
from passlib.hash import bcrypt, md5_crypt, sha256_crypt, sha512_crypt, ldap_salted_sha1
try:
from argon2 import PasswordHasher as argon2_hasher
from argon2 import exceptions as argon2_exceptions... | """
Advanced (ie. stronger) password hashers.
This module relies on `passlib` to provide more secure hashers.
"""
from passlib.hash import bcrypt, md5_crypt, sha256_crypt, sha512_crypt, ldap_salted_sha1
try:
from argon2 import PasswordHasher as argon2_hasher
from argon2 import exceptions as argon2_exceptions... |
38,404 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/password_hashers/advanced.py | 80,82 | 72,95 | scheme | SHA256CRYPTHasher | 82,84 | 82,84 | class SHA256CRYPTHasher(PasswordHasher):
"""
SHA256-CRYPT password hasher.
Supports rounds and is a good compromise between security and
performance.
"""
@property
def scheme(self):
FILL_FUNC_BODY def _b64encode(self, pwhash):
return pwhash
def _encrypt(self, clearvalue, sa... | class SHA256CRYPTHasher(PasswordHasher):
"""
SHA256-CRYPT password hasher.
Supports rounds and is a good compromise between security and
performance.
"""
@property
def scheme(self):
FILL_FUNC_BODY def _b64encode(self, pwhash):
return pwhash
def _encrypt(self, clearvalue, sa... | return "{SHA256-CRYPT}" if self._target == "local" else "{CRYPT}"
| return "{SHA256-CRYPT}" if self._target == "local" else "{CRYPT}"
| 8 | 198 | 33 | 231 | """
Advanced (ie. stronger) password hashers.
This module relies on `passlib` to provide more secure hashers.
"""
from passlib.hash import bcrypt, md5_crypt, sha256_crypt, sha512_crypt, ldap_salted_sha1
try:
from argon2 import PasswordHasher as argon2_hasher
from argon2 import exceptions as argon2_exceptions... | """
Advanced (ie. stronger) password hashers.
This module relies on `passlib` to provide more secure hashers.
"""
from passlib.hash import bcrypt, md5_crypt, sha256_crypt, sha512_crypt, ldap_salted_sha1
try:
from argon2 import PasswordHasher as argon2_hasher
from argon2 import exceptions as argon2_exceptions... |
38,405 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/password_hashers/advanced.py | 109,110 | 95,117 | _encrypt | SHA512CRYPTHasher | 110,113 | 110,113 | class SHA512CRYPTHasher(PasswordHasher):
"""
SHA512-CRYPT password hasher.
Supports rounds. Requires more resource than SHA256-CRYPT.
"""
@property
def scheme(self):
return "{SHA512-CRYPT}" if self._target == "local" else "{CRYPT}"
def _b64encode(self, pwhash):
return pwha... | class SHA512CRYPTHasher(PasswordHasher):
"""
SHA512-CRYPT password hasher.
Supports rounds. Requires more resource than SHA256-CRYPT.
"""
@property
def scheme(self):
return "{SHA512-CRYPT}" if self._target == "local" else "{CRYPT}"
def _b64encode(self, pwhash):
return pwha... | rounds = param_tools.get_global_parameter("rounds_number")
return sha512_crypt.using(rounds=rounds).hash(clearvalue)
| rounds = param_tools.get_global_parameter("rounds_number")
return sha512_crypt.using(rounds=rounds).hash(clearvalue)
| 5 | 190 | 46 | 236 | """
Advanced (ie. stronger) password hashers.
This module relies on `passlib` to provide more secure hashers.
"""
from passlib.hash import bcrypt, md5_crypt, sha256_crypt, sha512_crypt, ldap_salted_sha1
try:
from argon2 import PasswordHasher as argon2_hasher
from argon2 import exceptions as argon2_exceptions... | """
Advanced (ie. stronger) password hashers.
This module relies on `passlib` to provide more secure hashers.
"""
from passlib.hash import bcrypt, md5_crypt, sha256_crypt, sha512_crypt, ldap_salted_sha1
try:
from argon2 import PasswordHasher as argon2_hasher
from argon2 import exceptions as argon2_exceptions... |
38,406 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/password_hashers/advanced.py | 132,133 | 117,137 | verify | SSHAHasher | 133,137 | 133,137 | class SSHAHasher(PasswordHasher):
"""
Salted SHA1 password hasher.
"""
_weak = True
@property
def scheme(self):
return "{SSHA}"
def _encrypt(self, clearvalue, salt=None):
# We have to remove the {SSHA} at the beginning of the string
return ldap_salted_sha1.hash(cle... | class SSHAHasher(PasswordHasher):
"""
Salted SHA1 password hasher.
"""
_weak = True
@property
def scheme(self):
return "{SSHA}"
def _encrypt(self, clearvalue, salt=None):
# We have to remove the {SSHA} at the beginning of the string
return ldap_salted_sha1.hash(cle... | # We have to add the scheme for the hashed_value to be validated
return ldap_salted_sha1.verify(clearvalue, f"{{SSHA}}{hashed_value}")
| # We have to add the scheme for the hashed_value to be validated
return ldap_salted_sha1.verify(clearvalue, f"{{SSHA}}{hashed_value}")
| 16 | 137 | 56 | 193 | """
Advanced (ie. stronger) password hashers.
This module relies on `passlib` to provide more secure hashers.
"""
from passlib.hash import bcrypt, md5_crypt, sha256_crypt, sha512_crypt, ldap_salted_sha1
try:
from argon2 import PasswordHasher as argon2_hasher
from argon2 import exceptions as argon2_exceptions... | """
Advanced (ie. stronger) password hashers.
This module relies on `passlib` to provide more secure hashers.
"""
from passlib.hash import bcrypt, md5_crypt, sha256_crypt, sha512_crypt, ldap_salted_sha1
try:
from argon2 import PasswordHasher as argon2_hasher
from argon2 import exceptions as argon2_exceptions... |
38,407 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/password_hashers/base.py | 128,129 | 115,134 | _encrypt | CRYPTHasher | 129,134 | 129,134 | class CRYPTHasher(PasswordHasher):
"""
crypt password hasher.
Uses python `crypt` standard module.
"""
_weak = True
@property
def scheme(self):
return "{CRYPT}"
def _encrypt(self, clearvalue, salt=None):
FILL_FUNC_BODY | class CRYPTHasher(PasswordHasher):
"""
crypt password hasher.
Uses python `crypt` standard module.
"""
_weak = True
@property
def scheme(self):
return "{CRYPT}"
def _encrypt(self, clearvalue, salt=None):
FILL_FUNC_BODY | if salt is None:
salt = "".join(Random().sample(string.ascii_letters + string.digits, 2))
return crypt.crypt(clearvalue, salt)
| if salt is None:
salt = "".join(Random().sample(string.ascii_letters + string.digits, 2))
return crypt.crypt(clearvalue, salt)
| 13 | 93 | 55 | 148 | """
Base password hashers.
Contains weak hashers (the original ones) available with Modoboa.
"""
import base64
import crypt
import hashlib
import string
from random import Random
from django.utils.crypto import constant_time_compare
from django.utils.encoding import force_bytes, force_str
class MetaHasher(type):
... | """
Base password hashers.
Contains weak hashers (the original ones) available with Modoboa.
"""
import base64
import crypt
import hashlib
import string
from random import Random
from django.utils.crypto import constant_time_compare
from django.utils.encoding import force_bytes, force_str
class MetaHasher(type):
... |
38,408 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/password_hashers/base.py | 147,148 | 134,152 | _encrypt | MD5Hasher | 148,152 | 148,152 | class MD5Hasher(PasswordHasher):
"""
MD5 password hasher.
Uses python `hashlib` standard module.
"""
_weak = True
@property
def scheme(self):
return "{MD5}"
def _encrypt(self, clearvalue, salt=None):
FILL_FUNC_BODY | class MD5Hasher(PasswordHasher):
"""
MD5 password hasher.
Uses python `hashlib` standard module.
"""
_weak = True
@property
def scheme(self):
return "{MD5}"
def _encrypt(self, clearvalue, salt=None):
FILL_FUNC_BODY | obj = hashlib.md5(force_bytes(clearvalue))
return obj.hexdigest()
| obj = hashlib.md5(force_bytes(clearvalue))
return obj.hexdigest()
| 5 | 92 | 32 | 124 | """
Base password hashers.
Contains weak hashers (the original ones) available with Modoboa.
"""
import base64
import crypt
import hashlib
import string
from random import Random
from django.utils.crypto import constant_time_compare
from django.utils.encoding import force_bytes, force_str
class MetaHasher(type):
... | """
Base password hashers.
Contains weak hashers (the original ones) available with Modoboa.
"""
import base64
import crypt
import hashlib
import string
from random import Random
from django.utils.crypto import constant_time_compare
from django.utils.encoding import force_bytes, force_str
class MetaHasher(type):
... |
38,409 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/password_hashers/base.py | 28,30 | 17,34 | label | MetaHasher | 31,34 | 30,34 | class MetaHasher(type):
"""
PasswordHasher Metaclass
Allow classmethod to be properties
"""
@property
def name(cls):
"""Returns the name of the hasher"""
return cls.__name__.rstrip("Hasher").lower()
@property
def label(cls):
FILL_FUNC_BODY | class MetaHasher(type):
"""
PasswordHasher Metaclass
Allow classmethod to be properties
"""
@property
def name(cls):
"""Returns the name of the hasher"""
return cls.__name__.rstrip("Hasher").lower()
@property
def label(cls):
"""Returns the label of the hasher"""... | return cls.name if not cls._weak else "{} (weak)".format(cls.name)
| """Returns the label of the hasher"""
return cls.name if not cls._weak else "{} (weak)".format(cls.name)
| 8 | 105 | 31 | 136 | """
Base password hashers.
Contains weak hashers (the original ones) available with Modoboa.
"""
import base64
import crypt
import hashlib
import string
from random import Random
from django.utils.crypto import constant_time_compare
from django.utils.encoding import force_bytes, force_str
class MetaHasher(type):
... | """
Base password hashers.
Contains weak hashers (the original ones) available with Modoboa.
"""
import base64
import crypt
import hashlib
import string
from random import Random
from django.utils.crypto import constant_time_compare
from django.utils.encoding import force_bytes, force_str
class MetaHasher(type):
... |
38,410 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/password_hashers/base.py | 107,109 | 100,115 | scheme | PLAINHasher | 109,111 | 109,111 | class PLAINHasher(PasswordHasher):
"""
Plain (ie. clear) password hasher.
"""
_weak = True
@property
def scheme(self):
FILL_FUNC_BODY def _encrypt(self, clearvalue, salt=None):
return clearvalue
| class PLAINHasher(PasswordHasher):
"""
Plain (ie. clear) password hasher.
"""
_weak = True
@property
def scheme(self):
FILL_FUNC_BODY def _encrypt(self, clearvalue, salt=None):
return clearvalue
| return "{PLAIN}"
| return "{PLAIN}"
| 2 | 83 | 12 | 95 | """
Base password hashers.
Contains weak hashers (the original ones) available with Modoboa.
"""
import base64
import crypt
import hashlib
import string
from random import Random
from django.utils.crypto import constant_time_compare
from django.utils.encoding import force_bytes, force_str
class MetaHasher(type):
... | """
Base password hashers.
Contains weak hashers (the original ones) available with Modoboa.
"""
import base64
import crypt
import hashlib
import string
from random import Random
from django.utils.crypto import constant_time_compare
from django.utils.encoding import force_bytes, force_str
class MetaHasher(type):
... |
38,411 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/password_hashers/base.py | 47,48 | 34,100 | _b64encode | PasswordHasher | 53,57 | 48,57 | class PasswordHasher(metaclass=MetaHasher):
"""
Base class of all hashers.
"""
_weak = False
def __init__(self, target="local"):
self._target = target
def _encrypt(self, clearvalue, salt=None):
raise NotImplementedError
def _b64encode(self, pwhash):
FILL_FUNC_BODY def ... | class PasswordHasher(metaclass=MetaHasher):
"""
Base class of all hashers.
"""
_weak = False
def __init__(self, target="local"):
self._target = target
def _encrypt(self, clearvalue, salt=None):
raise NotImplementedError
def _b64encode(self, pwhash):
"""Encode :key... | if self._target == "ldap":
return base64.b64encode(pwhash)
return pwhash
| """Encode :keyword:`pwhash` using base64 if needed.
:param str pwhash: password hash
:return: base64 encoded hash or original hash
"""
if self._target == "ldap":
return base64.b64encode(pwhash)
return pwhash
| 8 | 528 | 38 | 566 | """
Base password hashers.
Contains weak hashers (the original ones) available with Modoboa.
"""
import base64
import crypt
import hashlib
import string
from random import Random
from django.utils.crypto import constant_time_compare
from django.utils.encoding import force_bytes, force_str
class MetaHasher(type):
... | """
Base password hashers.
Contains weak hashers (the original ones) available with Modoboa.
"""
import base64
import crypt
import hashlib
import string
from random import Random
from django.utils.crypto import constant_time_compare
from django.utils.encoding import force_bytes, force_str
class MetaHasher(type):
... |
38,412 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/password_hashers/base.py | 165,166 | 152,175 | _encrypt | SHA256Hasher | 166,168 | 166,168 | class SHA256Hasher(PasswordHasher):
"""
SHA256 password hasher.
Uses python `hashlib` and `base64` standard modules.
"""
_weak = True
@property
def scheme(self):
return "{SHA256}"
def _encrypt(self, clearvalue, salt=None):
FILL_FUNC_BODY def _b64encode(self, pwhash):
... | class SHA256Hasher(PasswordHasher):
"""
SHA256 password hasher.
Uses python `hashlib` and `base64` standard modules.
"""
_weak = True
@property
def scheme(self):
return "{SHA256}"
def _encrypt(self, clearvalue, salt=None):
FILL_FUNC_BODY def _b64encode(self, pwhash):
... | return hashlib.sha256(force_bytes(clearvalue)).digest()
| return hashlib.sha256(force_bytes(clearvalue)).digest()
| 2 | 181 | 24 | 205 | """
Base password hashers.
Contains weak hashers (the original ones) available with Modoboa.
"""
import base64
import crypt
import hashlib
import string
from random import Random
from django.utils.crypto import constant_time_compare
from django.utils.encoding import force_bytes, force_str
class MetaHasher(type):
... | """
Base password hashers.
Contains weak hashers (the original ones) available with Modoboa.
"""
import base64
import crypt
import hashlib
import string
from random import Random
from django.utils.crypto import constant_time_compare
from django.utils.encoding import force_bytes, force_str
class MetaHasher(type):
... |
38,413 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/password_hashers/utils.py | 17,18 | 1,74 | get_dovecot_schemes | 27,64 | 18,64 | """ Utils for password schemes caching/retrieval. """
from django.conf import settings
from django.core.cache import cache
from django.utils.encoding import smart_str
from modoboa.admin.models.alarm import Alarm
from modoboa.admin.constants import ALARM_CLOSED, ALARM_OPENED
from modoboa.core.constants import DOVEADM... | """ Utils for password schemes caching/retrieval. """
from django.conf import settings
from django.core.cache import cache
from django.utils.encoding import smart_str
from modoboa.admin.models.alarm import Alarm
from modoboa.admin.constants import ALARM_CLOSED, ALARM_OPENED
from modoboa.core.constants import DOVEADM... | schemes = getattr(settings, "DOVECOT_SUPPORTED_SCHEMES", None)
default_schemes = "MD5-CRYPT PLAIN"
status = 1
if not schemes:
try:
retcode, schemes = doveadm_cmd("pw -l")
except OSError:
schemes = default_schemes
status = 2
else:
i... | """Return schemes supported by Dovecot.
It first try to get supported schemes fron the settings, then from the
doveadm output, and fallback to {MD5-CRYPT} and {PLAIN} if the command
is not found.
:return: A tuple with [0] : a list of supported '{SCHEME}'
[1] : the status (0=actual schemes, 1=s... | 101 | 417 | 414 | 831 | """ Utils for password schemes caching/retrieval. """
from django.conf import settings
from django.core.cache import cache
from django.utils.encoding import smart_str
from modoboa.admin.models.alarm import Alarm
from modoboa.admin.constants import ALARM_CLOSED, ALARM_OPENED
from modoboa.core.constants import DOVEADM... | """ Utils for password schemes caching/retrieval. """
from django.conf import settings
from django.core.cache import cache
from django.utils.encoding import smart_str
from modoboa.admin.models.alarm import Alarm
from modoboa.admin.constants import ALARM_CLOSED, ALARM_OPENED
from modoboa.core.constants import DOVEADM... | |
38,414 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/password_validation.py | 68,69 | 7,72 | get_help_text | ComplexityValidator | 69,72 | 69,72 | class ComplexityValidator(object):
"""Check password contains at least a few things."""
def __init__(self, upper=1, lower=1, digits=1, specials=1):
self.upper = upper
self.lower = lower
self.digits = digits
self.specials = specials
def validate(self, password, user=None):
... | class ComplexityValidator(object):
"""Check password contains at least a few things."""
def __init__(self, upper=1, lower=1, digits=1, specials=1):
self.upper = upper
self.lower = lower
self.digits = digits
self.specials = specials
def validate(self, password, user=None):
... | return _(
"Your password must contain a combination of different " "character types."
)
| return _(
"Your password must contain a combination of different " "character types."
)
| 14 | 538 | 27 | 565 | """Custom password validators."""
from django.core.exceptions import ValidationError
from django.utils.translation import gettext as _, ngettext
class ComplexityValidator(object):
"""Check password contains at least a few things."""
def __init__(self, upper=1, lower=1, digits=1, specials=1):
self.up... | """Custom password validators."""
from django.core.exceptions import ValidationError
from django.utils.translation import gettext as _, ngettext
class ComplexityValidator(object):
"""Check password contains at least a few things."""
def __init__(self, upper=1, lower=1, digits=1, specials=1):
self.up... |
38,415 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/sms_backends/dummy.py | 9,10 | 6,13 | send | DUMMYBackend | 11,13 | 10,13 | class DUMMYBackend(SMSBackend):
"""Dummy backend to use with tests."""
def send(self, text, recipients):
FILL_FUNC_BODY | class DUMMYBackend(SMSBackend):
"""Dummy backend to use with tests."""
def send(self, text, recipients):
"""Print text on stdout."""
FILL_FUNC_BODY | print(text)
return True
| """Print text on stdout."""
print(text)
return True
| 3 | 56 | 12 | 68 | """Dummy SMS backend."""
from . import SMSBackend
class DUMMYBackend(SMSBackend):
"""Dummy backend to use with tests."""
def send(self, text, recipients):
FILL_FUNC_BODY | """Dummy SMS backend."""
from . import SMSBackend
class DUMMYBackend(SMSBackend):
"""Dummy backend to use with tests."""
def send(self, text, recipients):
"""Print text on stdout."""
FILL_FUNC_BODY |
38,416 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/sms_backends/ovh.py | 147,148 | 14,161 | send | OVHBackend | 149,161 | 148,161 | class OVHBackend(SMSBackend):
"""OVH SMS backend class."""
settings = {
"sms_ovh_endpoint": {
"type": forms.ChoiceField,
"attrs": {
"label": _("API endpoint"),
"initial": "ovh-eu",
"choices": (
("ovh-eu", _("OVH... | class OVHBackend(SMSBackend):
"""OVH SMS backend class."""
settings = {
"sms_ovh_endpoint": {
"type": forms.ChoiceField,
"attrs": {
"label": _("API endpoint"),
"initial": "ovh-eu",
"choices": (
("ovh-eu", _("OVH... | services = self.client.get("/sms")
result = self.client.post(
"/sms/{}/jobs".format(services[0]),
message=text,
receivers=recipients,
priority="high",
noStopClause=True,
senderForResponse=True,
)
if result["totalCred... | """Send a new SMS to given recipients."""
services = self.client.get("/sms")
result = self.client.post(
"/sms/{}/jobs".format(services[0]),
message=text,
receivers=recipients,
priority="high",
noStopClause=True,
senderForRes... | 21 | 1,321 | 122 | 1,443 | """OVH SMS backend."""
import ovh
from django import forms
from django.utils.functional import cached_property
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from . import SMSBackend
class OVHBackend(SMSBackend):
"""OVH SMS backend class."""
settings = {
... | """OVH SMS backend."""
import ovh
from django import forms
from django.utils.functional import cached_property
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from . import SMSBackend
class OVHBackend(SMSBackend):
"""OVH SMS backend class."""
settings = {
... |
38,418 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/templatetags/core_tags.py | 219,220 | 214,234 | render | ConnectedUsers | 220,234 | 220,234 | class ConnectedUsers(template.Node):
def __init__(self, varname):
self.varname = varname
def render(self, context):
FILL_FUNC_BODY | class ConnectedUsers(template.Node):
def __init__(self, varname):
self.varname = varname
def render(self, context):
FILL_FUNC_BODY | sessions = Session.objects.filter(expire_date__gte=timezone.now())
uid_list = []
# Build a list of user ids from that query
for session in sessions:
data = session.get_decoded()
uid = data.get("_auth_user_id", None)
if uid:
uid_list.app... | sessions = Session.objects.filter(expire_date__gte=timezone.now())
uid_list = []
# Build a list of user ids from that query
for session in sessions:
data = session.get_decoded()
uid = data.get("_auth_user_id", None)
if uid:
uid_list.app... | 45 | 51 | 159 | 210 | """Custom tags for Core application."""
import os
import re
from functools import reduce
import pkg_resources
from django import template
from django.conf import settings
from django.contrib.sessions.models import Session
from django.template.loader import render_to_string
from django.urls import reverse
from django... | """Custom tags for Core application."""
import os
import re
from functools import reduce
import pkg_resources
from django import template
from django.conf import settings
from django.contrib.sessions.models import Session
from django.template.loader import render_to_string
from django.urls import reverse
from django... |
38,419 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/utils.py | 12,13 | 1,52 | parse_map_file | 14,24 | 13,24 | """Utility functions."""
from pkg_resources import parse_version
from django.utils.translation import gettext as _
from modoboa.core.extensions import exts_pool
from modoboa.lib.api_client import ModoAPIClient
from . import models
def parse_map_file(path):
FILL_FUNC_BODYdef check_for_updates():
"""Check if a n... | """Utility functions."""
from pkg_resources import parse_version
from django.utils.translation import gettext as _
from modoboa.core.extensions import exts_pool
from modoboa.lib.api_client import ModoAPIClient
from . import models
def parse_map_file(path):
"""Parse a postfix map file and return values."""
FILL... | content = {}
with open(path) as fp:
for line in fp:
if not line or line.startswith("#"):
continue
name, value = line.split("=", 1)
content[name.strip()] = value.strip()
return content
| """Parse a postfix map file and return values."""
content = {}
with open(path) as fp:
for line in fp:
if not line or line.startswith("#"):
continue
name, value = line.split("=", 1)
content[name.strip()] = value.strip()
return content
| 27 | 382 | 86 | 468 | """Utility functions."""
from pkg_resources import parse_version
from django.utils.translation import gettext as _
from modoboa.core.extensions import exts_pool
from modoboa.lib.api_client import ModoAPIClient
from . import models
def parse_map_file(path):
FILL_FUNC_BODYdef check_for_updates():
"""Check if a n... | """Utility functions."""
from pkg_resources import parse_version
from django.utils.translation import gettext as _
from modoboa.core.extensions import exts_pool
from modoboa.lib.api_client import ModoAPIClient
from . import models
def parse_map_file(path):
"""Parse a postfix map file and return values."""
FILL... | |
38,420 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/views/admin.py | 24,27 | 1,133 | parameters | 28,59 | 27,59 | """Views available to super administrators only."""
from functools import reduce
from django.contrib.auth.decorators import login_required, user_passes_test
from django.shortcuts import render
from django.template.loader import render_to_string
from django.utils.translation import gettext as _
from modoboa.core.mode... | """Views available to super administrators only."""
from functools import reduce
from django.contrib.auth.decorators import login_required, user_passes_test
from django.shortcuts import render
from django.template.loader import render_to_string
from django.utils.translation import gettext as _
from modoboa.core.mode... | if request.method == "POST":
forms = param_tools.registry.get_forms(
"global", request.POST, localconfig=request.localconfig
)
for formdef in forms:
form = formdef["form"]
if form.is_valid():
form.save()
form.to_django_setti... | """View to display and save global parameters."""
if request.method == "POST":
forms = param_tools.registry.get_forms(
"global", request.POST, localconfig=request.localconfig
)
for formdef in forms:
form = formdef["form"]
if form.is_valid():
... | 54 | 982 | 274 | 1,256 | """Views available to super administrators only."""
from functools import reduce
from django.contrib.auth.decorators import login_required, user_passes_test
from django.shortcuts import render
from django.template.loader import render_to_string
from django.utils.translation import gettext as _
from modoboa.core.mode... | """Views available to super administrators only."""
from functools import reduce
from django.contrib.auth.decorators import login_required, user_passes_test
from django.shortcuts import render
from django.template.loader import render_to_string
from django.utils.translation import gettext as _
from modoboa.core.mode... | |
38,422 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/views/auth.py | 167,168 | 150,195 | form_valid | PasswordResetView | 169,195 | 168,195 | class PasswordResetView(auth_views.PasswordResetView):
"""Custom view to override form."""
form_class = forms.PasswordResetForm
def setup(self, request, *args, **kwargs):
super().setup(request, *args, **kwargs)
self.from_email = request.localconfig.parameters.get_value("sender_address")
... | class PasswordResetView(auth_views.PasswordResetView):
"""Custom view to override form."""
form_class = forms.PasswordResetForm
def setup(self, request, *args, **kwargs):
super().setup(request, *args, **kwargs)
self.from_email = request.localconfig.parameters.get_value("sender_address")
... | sms_password_recovery = self.request.localconfig.parameters.get_value(
"sms_password_recovery"
)
if not sms_password_recovery:
return super().form_valid(form)
user = models.User._default_manager.filter(
email=form.cleaned_data["email"], phone_number__i... | """Redirect to code verification page if needed."""
sms_password_recovery = self.request.localconfig.parameters.get_value(
"sms_password_recovery"
)
if not sms_password_recovery:
return super().form_valid(form)
user = models.User._default_manager.filter(
... | 65 | 201 | 322 | 523 | """Core authentication views."""
import logging
import oath
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect, Http404, JsonResponse
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils import translation
from django.utils.enc... | """Core authentication views."""
import logging
import oath
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect, Http404, JsonResponse
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils import translation
from django.utils.enc... |
38,423 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/views/auth.py | 223,224 | 220,247 | get | ResendSMSCodeView | 224,247 | 224,247 | class ResendSMSCodeView(generic.View):
"""A view to resend validation code."""
def get(self, request, *args, **kwargs):
FILL_FUNC_BODY | class ResendSMSCodeView(generic.View):
"""A view to resend validation code."""
def get(self, request, *args, **kwargs):
FILL_FUNC_BODY | sms_password_recovery = self.request.localconfig.parameters.get_value(
"sms_password_recovery"
)
if not sms_password_recovery:
raise Http404
try:
user = models.User._default_manager.get(pk=self.request.session["user_pk"])
except KeyError:
... | sms_password_recovery = self.request.localconfig.parameters.get_value(
"sms_password_recovery"
)
if not sms_password_recovery:
raise Http404
try:
user = models.User._default_manager.get(pk=self.request.session["user_pk"])
except KeyError:
... | 56 | 50 | 266 | 316 | """Core authentication views."""
import logging
import oath
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect, Http404, JsonResponse
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils import translation
from django.utils.enc... | """Core authentication views."""
import logging
import oath
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect, Http404, JsonResponse
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils import translation
from django.utils.enc... |
38,424 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/views/auth.py | 255,256 | 247,259 | form_valid | TwoFactorCodeVerifyView | 257,259 | 256,259 | class TwoFactorCodeVerifyView(
LoginRequiredMixin, UserFormKwargsMixin, generic.FormView
):
"""View to verify a 2FA code after login."""
form_class = forms.Verify2FACodeForm
template_name = "registration/twofactor_code_verify.html"
def form_valid(self, form):
FILL_FUNC_BODY | class TwoFactorCodeVerifyView(
LoginRequiredMixin, UserFormKwargsMixin, generic.FormView
):
"""View to verify a 2FA code after login."""
form_class = forms.Verify2FACodeForm
template_name = "registration/twofactor_code_verify.html"
def form_valid(self, form):
"""Login user."""
FILL_FUNC_BO... | django_otp.login(self.request, form.cleaned_data["tfa_code"])
return HttpResponseRedirect(find_nextlocation(self.request, self.request.user))
| """Login user."""
django_otp.login(self.request, form.cleaned_data["tfa_code"])
return HttpResponseRedirect(find_nextlocation(self.request, self.request.user))
| 5 | 107 | 52 | 159 | """Core authentication views."""
import logging
import oath
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect, Http404, JsonResponse
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils import translation
from django.utils.enc... | """Core authentication views."""
import logging
import oath
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect, Http404, JsonResponse
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils import translation
from django.utils.enc... |
38,425 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/views/auth.py | 201,202 | 195,220 | get_form_kwargs | VerifySMSCodeView | 203,210 | 202,210 | class VerifySMSCodeView(generic.FormView):
"""View to verify a code received by SMS."""
form_class = forms.VerifySMSCodeForm
template_name = "registration/password_reset_confirm_code.html"
def get_form_kwargs(self):
FILL_FUNC_BODY def form_valid(self, form):
"""Redirect to reset password fo... | class VerifySMSCodeView(generic.FormView):
"""View to verify a code received by SMS."""
form_class = forms.VerifySMSCodeForm
template_name = "registration/password_reset_confirm_code.html"
def get_form_kwargs(self):
"""Include totp secret in kwargs."""
FILL_FUNC_BODY def form_valid(self, fo... | kwargs = super().get_form_kwargs()
try:
kwargs.update({"totp_secret": self.request.session["totp_secret"]})
except KeyError:
raise Http404
return kwargs
| """Include totp secret in kwargs."""
kwargs = super().get_form_kwargs()
try:
kwargs.update({"totp_secret": self.request.session["totp_secret"]})
except KeyError:
raise Http404
return kwargs
| 12 | 230 | 71 | 301 | """Core authentication views."""
import logging
import oath
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect, Http404, JsonResponse
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils import translation
from django.utils.enc... | """Core authentication views."""
import logging
import oath
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect, Http404, JsonResponse
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils import translation
from django.utils.enc... |
38,426 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/views/base.py | 11,12 | 1,40 | find_nextlocation | 13,34 | 12,34 | """Base core views."""
from django.contrib.auth import mixins as auth_mixins
from django.urls import reverse
from django.utils.http import url_has_allowed_host_and_scheme
from django.views import generic
from ..extensions import exts_pool
def find_nextlocation(request, user):
FILL_FUNC_BODYclass RootDispatchView(au... | """Base core views."""
from django.contrib.auth import mixins as auth_mixins
from django.urls import reverse
from django.utils.http import url_has_allowed_host_and_scheme
from django.views import generic
from ..extensions import exts_pool
def find_nextlocation(request, user):
"""Find next location for given use... | if not user.last_login:
# Redirect to profile on first login
return reverse("core:user_index")
nextlocation = request.POST.get("next", request.GET.get("next"))
condition = nextlocation and url_has_allowed_host_and_scheme(
nextlocation, request.get_host()
)
if condition:
... | """Find next location for given user after login."""
if not user.last_login:
# Redirect to profile on first login
return reverse("core:user_index")
nextlocation = request.POST.get("next", request.GET.get("next"))
condition = nextlocation and url_has_allowed_host_and_scheme(
nextl... | 55 | 178 | 239 | 417 | """Base core views."""
from django.contrib.auth import mixins as auth_mixins
from django.urls import reverse
from django.utils.http import url_has_allowed_host_and_scheme
from django.views import generic
from ..extensions import exts_pool
def find_nextlocation(request, user):
FILL_FUNC_BODYclass RootDispatchView(au... | """Base core views."""
from django.contrib.auth import mixins as auth_mixins
from django.urls import reverse
from django.utils.http import url_has_allowed_host_and_scheme
from django.views import generic
from ..extensions import exts_pool
def find_nextlocation(request, user):
"""Find next location for given use... | |
38,427 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/views/base.py | 37,38 | 34,40 | get_redirect_url | RootDispatchView | 39,40 | 38,40 | class RootDispatchView(auth_mixins.LoginRequiredMixin, generic.RedirectView):
"""Handle root dispatching based on role."""
def get_redirect_url(self):
FILL_FUNC_BODY | class RootDispatchView(auth_mixins.LoginRequiredMixin, generic.RedirectView):
"""Handle root dispatching based on role."""
def get_redirect_url(self):
"""Find proper next hop."""
FILL_FUNC_BODY | return find_nextlocation(self.request, self.request.user)
| """Find proper next hop."""
return find_nextlocation(self.request, self.request.user)
| 3 | 65 | 19 | 84 | """Base core views."""
from django.contrib.auth import mixins as auth_mixins
from django.urls import reverse
from django.utils.http import url_has_allowed_host_and_scheme
from django.views import generic
from ..extensions import exts_pool
def find_nextlocation(request, user):
"""Find next location for given use... | """Base core views."""
from django.contrib.auth import mixins as auth_mixins
from django.urls import reverse
from django.utils.http import url_has_allowed_host_and_scheme
from django.views import generic
from ..extensions import exts_pool
def find_nextlocation(request, user):
"""Find next location for given use... |
38,428 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/views/dashboard.py | 29,30 | 18,84 | get_context_data | DashboardView | 31,84 | 30,84 | class DashboardView(auth_mixins.AccessMixin, generic.TemplateView):
"""Dashboard view."""
template_name = "core/dashboard.html"
def dispatch(self, request, *args, **kwargs):
"""Check if user can access dashboard."""
if not request.user.is_authenticated or not request.user.is_admin:
... | class DashboardView(auth_mixins.AccessMixin, generic.TemplateView):
"""Dashboard view."""
template_name = "core/dashboard.html"
def dispatch(self, request, *args, **kwargs):
"""Check if user can access dashboard."""
if not request.user.is_authenticated or not request.user.is_admin:
... | context = super().get_context_data(**kwargs)
context.update({"selection": "dashboard", "widgets": {"left": [], "right": []}})
# Fetch latest news
if self.request.user.language == "fr":
lang = "fr"
else:
lang = "en"
context.update({"selection": "das... | """Add context variables."""
context = super().get_context_data(**kwargs)
context.update({"selection": "dashboard", "widgets": {"left": [], "right": []}})
# Fetch latest news
if self.request.user.language == "fr":
lang = "fr"
else:
lang = "en"
... | 130 | 151 | 669 | 820 | """Core dashboard views."""
import feedparser
import requests
from dateutil import parser
from requests.exceptions import RequestException
from django.contrib.auth import mixins as auth_mixins
from django.views import generic
from django.conf import settings
from .. import signals
MODOBOA_WEBSITE_URL = "https://mo... | """Core dashboard views."""
import feedparser
import requests
from dateutil import parser
from requests.exceptions import RequestException
from django.contrib.auth import mixins as auth_mixins
from django.views import generic
from django.conf import settings
from .. import signals
MODOBOA_WEBSITE_URL = "https://mo... |
38,429 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/core/views/user.py | 33,35 | 1,151 | profile | 36,76 | 35,76 | """Simple user views."""
import io
import qrcode
import qrcode.image.svg
from django.conf import settings
from django.shortcuts import render
from django.template.loader import render_to_string
from django.utils import translation
from django.utils.encoding import force_str
from django.utils.translation import gette... | """Simple user views."""
import io
import qrcode
import qrcode.image.svg
from django.conf import settings
from django.shortcuts import render
from django.template.loader import render_to_string
from django.utils import translation
from django.utils.encoding import force_str
from django.utils.translation import gette... | update_password = True
results = signals.allow_password_change.send(sender="profile", user=request.user)
if True in [result[1] for result in results]:
update_password = False
password_url = request.localconfig.parameters.get_value("update_password_url")
show_password_url = False
if not r... | """Profile detail/update view."""
update_password = True
results = signals.allow_password_change.send(sender="profile", user=request.user)
if True in [result[1] for result in results]:
update_password = False
password_url = request.localconfig.parameters.get_value("update_password_url")
... | 93 | 1,086 | 451 | 1,537 | """Simple user views."""
import io
import qrcode
import qrcode.image.svg
from django.conf import settings
from django.shortcuts import render
from django.template.loader import render_to_string
from django.utils import translation
from django.utils.encoding import force_str
from django.utils.translation import gette... | """Simple user views."""
import io
import qrcode
import qrcode.image.svg
from django.conf import settings
from django.shortcuts import render
from django.template.loader import render_to_string
from django.utils import translation
from django.utils.encoding import force_str
from django.utils.translation import gette... | |
38,430 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/dmarc/api/v2/tests.py | 27,28 | 11,37 | test_no_record | DmarcViewSetTestCase | 28,32 | 28,32 | class DmarcViewSetTestCase(mixins.CallCommandMixin, ModoAPITestCase):
@classmethod
def setUpTestData(cls):
"""Create test data."""
super().setUpTestData()
cls.domain = admin_factories.DomainFactory(name="ngyn.org")
def test_alignment_stats(self):
"""Test alignment stats end... | class DmarcViewSetTestCase(mixins.CallCommandMixin, ModoAPITestCase):
@classmethod
def setUpTestData(cls):
"""Create test data."""
super().setUpTestData()
cls.domain = admin_factories.DomainFactory(name="ngyn.org")
def test_alignment_stats(self):
"""Test alignment stats end... | url = reverse("v2:dmarc-alignment-stats", args=[self.domain.pk])
response = self.client.get(f"{url}?period=2015-26")
self.assertEqual(response.status_code, 204)
| url = reverse("v2:dmarc-alignment-stats", args=[self.domain.pk])
response = self.client.get(f"{url}?period=2015-26")
self.assertEqual(response.status_code, 204)
| 9 | 307 | 74 | 381 | """API v2 tests."""
from django.urls import reverse
from modoboa.lib.tests import ModoAPITestCase
from modoboa.admin import factories as admin_factories
from modoboa.dmarc.tests import mixins
class DmarcViewSetTestCase(mixins.CallCommandMixin, ModoAPITestCase):
@classmethod
def setUpTestData(cls):
... | """API v2 tests."""
from django.urls import reverse
from modoboa.lib.tests import ModoAPITestCase
from modoboa.admin import factories as admin_factories
from modoboa.dmarc.tests import mixins
class DmarcViewSetTestCase(mixins.CallCommandMixin, ModoAPITestCase):
@classmethod
def setUpTestData(cls):
... |
38,431 | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa | /home/hieuvd/dung_repo/raw/stars_02/modoboa_modoboa/modoboa/modoboa/dmarc/api/v2/viewsets.py | 21,28 | 13,39 | alignment_stats | DMARCViewSet | 28,39 | 28,39 | class DMARCViewSet(GetThrottleViewsetMixin, viewsets.GenericViewSet):
permission_classes = (permissions.IsAuthenticated,)
def get_queryset(self):
"""Filter queryset based on current user."""
return admin_models.Domain.objects.get_for_admin(self.request.user)
@action(
methods=["get... | class DMARCViewSet(GetThrottleViewsetMixin, viewsets.GenericViewSet):
permission_classes = (permissions.IsAuthenticated,)
def get_queryset(self):
"""Filter queryset based on current user."""
return admin_models.Domain.objects.get_for_admin(self.request.user)
@action(
methods=["get... | domain = self.get_object()
if not domain.record_set.exists():
return response.Response(status=204)
try:
stats = lib.get_aligment_stats(
domain, self.request.query_params.get("period")
)
except ValueError:
return response.Res... | domain = self.get_object()
if not domain.record_set.exists():
return response.Response(status=204)
try:
stats = lib.get_aligment_stats(
domain, self.request.query_params.get("period")
)
except ValueError:
return response.Res... | 27 | 166 | 132 | 298 | """App. related viewsets."""
from rest_framework import permissions, response, viewsets
from rest_framework.decorators import action
from modoboa.admin import models as admin_models
from modoboa.lib.throttle import GetThrottleViewsetMixin
from ... import lib
from . import serializers
class DMARCViewSet(GetThrottle... | """App. related viewsets."""
from rest_framework import permissions, response, viewsets
from rest_framework.decorators import action
from modoboa.admin import models as admin_models
from modoboa.lib.throttle import GetThrottleViewsetMixin
from ... import lib
from . import serializers
class DMARCViewSet(GetThrottle... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.