id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
180,510 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint('users_stripe_card_token_key', 'users', type_='unique')
op.drop_constraint('users_stripe_customer_id_key', 'users', type_='unique')
op.drop_constraint('users_stripe_subscription_id_key', 'users', type_='unique')
op.drop_column('users', 'stripe_customer_id')
op.drop_column('users', 'stripe_card_token')
op.drop_column('users', 'stripe_subscription_id')
# ### end Alembic commands ### | null |
180,511 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('users', sa.Column('stripe_subscription_id', sa.VARCHAR(length=128), autoincrement=False, nullable=True))
op.add_column('users', sa.Column('stripe_card_token', sa.VARCHAR(length=128), autoincrement=False, nullable=True))
op.add_column('users', sa.Column('stripe_customer_id', sa.VARCHAR(length=128), autoincrement=False, nullable=True))
op.create_unique_constraint('users_stripe_subscription_id_key', 'users', ['stripe_subscription_id'])
op.create_unique_constraint('users_stripe_customer_id_key', 'users', ['stripe_customer_id'])
op.create_unique_constraint('users_stripe_card_token_key', 'users', ['stripe_card_token'])
# ### end Alembic commands ### | null |
180,512 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('directory_mailbox',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('created_at', sqlalchemy_utils.types.arrow.ArrowType(), nullable=False),
sa.Column('updated_at', sqlalchemy_utils.types.arrow.ArrowType(), nullable=True),
sa.Column('directory_id', sa.Integer(), nullable=False),
sa.Column('mailbox_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['directory_id'], ['directory.id'], ondelete='cascade'),
sa.ForeignKeyConstraint(['mailbox_id'], ['mailbox.id'], ondelete='cascade'),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('directory_id', 'mailbox_id', name='uq_directory_mailbox')
)
# ### end Alembic commands ### | null |
180,513 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('directory_mailbox')
# ### end Alembic commands ### | null |
180,514 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('email_log', sa.Column('auto_replied', sa.Boolean(), server_default='0', nullable=False))
# ### end Alembic commands ### | null |
180,515 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('email_log', 'auto_replied')
# ### end Alembic commands ### | null |
180,516 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('users', sa.Column('lifetime_coupon_id', sa.Integer(), nullable=True))
op.create_foreign_key(None, 'users', 'lifetime_coupon', ['lifetime_coupon_id'], ['id'], ondelete='SET NULL')
# ### end Alembic commands ### | null |
180,517 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(None, 'users', type_='foreignkey')
op.drop_column('users', 'lifetime_coupon_id')
# ### end Alembic commands ### | null |
180,518 | import sqlalchemy_utils
from sqlalchemy.dialects import postgresql
from alembic import op
import sqlalchemy as sa
def __create_enum() -> postgresql.ENUM:
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
block_behaviour_enum = __create_enum()
block_behaviour_enum.create(op.get_bind())
op.add_column('users', sa.Column('block_behaviour', block_behaviour_enum, nullable=False, default='return_2xx', server_default='return_2xx'))
# ### end Alembic commands ### | null |
180,519 | import sqlalchemy_utils
from sqlalchemy.dialects import postgresql
from alembic import op
import sqlalchemy as sa
def __create_enum() -> postgresql.ENUM:
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('users', 'block_behaviour')
block_behaviour_enum = __create_enum()
block_behaviour_enum.drop(op.get_bind())
# ### end Alembic commands ### | null |
180,520 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('users', 'can_use_fido')
# ### end Alembic commands ### | null |
180,521 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('users', sa.Column('can_use_fido', sa.BOOLEAN(), server_default=sa.text('false'), autoincrement=False, nullable=False))
# ### end Alembic commands ### | null |
180,522 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('api_key',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('created_at', sqlalchemy_utils.types.arrow.ArrowType(), nullable=False),
sa.Column('updated_at', sqlalchemy_utils.types.arrow.ArrowType(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('code', sa.String(length=128), nullable=False),
sa.Column('name', sa.String(length=128), nullable=False),
sa.Column('last_used', sqlalchemy_utils.types.arrow.ArrowType(), nullable=True),
sa.Column('times', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='cascade'),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('code')
)
op.create_table('alias_used_on',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('created_at', sqlalchemy_utils.types.arrow.ArrowType(), nullable=False),
sa.Column('updated_at', sqlalchemy_utils.types.arrow.ArrowType(), nullable=True),
sa.Column('gen_email_id', sa.Integer(), nullable=False),
sa.Column('hostname', sa.String(length=1024), nullable=False),
sa.ForeignKeyConstraint(['gen_email_id'], ['gen_email.id'], ondelete='cascade'),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('gen_email_id', 'hostname', name='uq_alias_used')
)
# ### end Alembic commands ### | null |
180,523 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('alias_used_on')
op.drop_table('api_key')
# ### end Alembic commands ### | null |
180,524 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('directory',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('created_at', sqlalchemy_utils.types.arrow.ArrowType(), nullable=False),
sa.Column('updated_at', sqlalchemy_utils.types.arrow.ArrowType(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=128), nullable=False),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='cascade'),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
)
op.add_column('gen_email', sa.Column('directory_id', sa.Integer(), nullable=True))
op.create_foreign_key(None, 'gen_email', 'directory', ['directory_id'], ['id'], ondelete='cascade')
# ### end Alembic commands ### | null |
180,525 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(None, 'gen_email', type_='foreignkey')
op.drop_column('gen_email', 'directory_id')
op.drop_table('directory')
# ### end Alembic commands ### | null |
180,526 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('metric',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('created_at', sqlalchemy_utils.types.arrow.ArrowType(), nullable=False),
sa.Column('updated_at', sqlalchemy_utils.types.arrow.ArrowType(), nullable=True),
sa.Column('date', sqlalchemy_utils.types.arrow.ArrowType(), nullable=False),
sa.Column('name', sa.String(length=256), nullable=False),
sa.Column('value', sa.Float(), nullable=False),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ### | null |
180,527 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('metric')
# ### end Alembic commands ### | null |
180,528 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint('client_referral_id_fkey', 'client', type_='foreignkey')
op.create_foreign_key(None, 'client', 'referral', ['referral_id'], ['id'], ondelete='SET NULL')
# ### end Alembic commands ### | null |
180,529 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(None, 'client', type_='foreignkey')
op.create_foreign_key('client_referral_id_fkey', 'client', 'referral', ['referral_id'], ['id'])
# ### end Alembic commands ### | null |
180,530 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('users', 'full_mailbox')
op.drop_column('users', 'can_use_multiple_mailbox')
# ### end Alembic commands ### | null |
180,531 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('users', sa.Column('can_use_multiple_mailbox', sa.BOOLEAN(), server_default=sa.text('false'), autoincrement=False, nullable=False))
op.add_column('users', sa.Column('full_mailbox', sa.BOOLEAN(), server_default=sa.text('false'), autoincrement=False, nullable=False))
# ### end Alembic commands ### | null |
180,532 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('users', sa.Column('default_mailbox_id', sa.Integer(), nullable=True))
op.create_foreign_key(None, 'users', 'mailbox', ['default_mailbox_id'], ['id'])
# ### end Alembic commands ### | null |
180,533 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(None, 'users', type_='foreignkey')
op.drop_column('users', 'default_mailbox_id')
# ### end Alembic commands ### | null |
180,534 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('manual_subscription',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('created_at', sqlalchemy_utils.types.arrow.ArrowType(), nullable=False),
sa.Column('updated_at', sqlalchemy_utils.types.arrow.ArrowType(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('end_at', sqlalchemy_utils.types.arrow.ArrowType(), nullable=False),
sa.Column('comment', sa.Text(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='cascade'),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('user_id')
)
# ### end Alembic commands ### | null |
180,535 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('manual_subscription')
# ### end Alembic commands ### | null |
180,536 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('contact', sa.Column('name', sa.String(length=512), server_default=sa.text('NULL'), nullable=True))
# ### end Alembic commands ### | null |
180,537 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('contact', 'name')
# ### end Alembic commands ### | null |
180,538 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_index(op.f('ix_contact_reply_email'), 'contact', ['reply_email'], unique=False)
# ### end Alembic commands ### | null |
180,539 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_contact_reply_email'), table_name='contact')
# ### end Alembic commands ### | null |
180,540 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():
op.rename_table("forward_email_log", "email_log") | null |
180,541 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def downgrade():
op.rename_table("email_log", "forward_email_log") | null |
180,542 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('alias_used_on', sa.Column('user_id', sa.Integer(), nullable=True))
op.create_foreign_key(None, 'alias_used_on', 'users', ['user_id'], ['id'], ondelete='cascade')
# ### end Alembic commands ### | null |
180,543 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(None, 'alias_used_on', type_='foreignkey')
op.drop_column('alias_used_on', 'user_id')
# ### end Alembic commands ### | null |
180,544 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('email_change',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('created_at', sqlalchemy_utils.types.arrow.ArrowType(), nullable=False),
sa.Column('updated_at', sqlalchemy_utils.types.arrow.ArrowType(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('new_email', sa.String(length=128), nullable=False),
sa.Column('code', sa.String(length=128), nullable=False),
sa.Column('expired', sqlalchemy_utils.types.arrow.ArrowType(), nullable=False),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='cascade'),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('code'),
sa.UniqueConstraint('new_email')
)
op.create_index(op.f('ix_email_change_user_id'), 'email_change', ['user_id'], unique=True)
# ### end Alembic commands ### | null |
180,545 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_email_change_user_id'), table_name='email_change')
op.drop_table('email_change')
# ### end Alembic commands ### | null |
180,546 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('sent_alert',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('created_at', sqlalchemy_utils.types.arrow.ArrowType(), nullable=False),
sa.Column('updated_at', sqlalchemy_utils.types.arrow.ArrowType(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('to_email', sa.String(length=256), nullable=False),
sa.Column('alert_type', sa.String(length=256), nullable=False),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='cascade'),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ### | null |
180,547 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('sent_alert')
# ### end Alembic commands ### | null |
180,548 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('users', sa.Column('can_use_multiple_mailbox', sa.Boolean(), server_default='0', nullable=False))
# ### end Alembic commands ### | null |
180,549 | import sqlalchemy_utils
from alembic import op
import sqlalchemy as sa
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('users', 'can_use_multiple_mailbox')
# ### end Alembic commands ### | null |
180,550 | from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('authorization_code', sa.Column('redirect_uri', sa.String(length=1024), nullable=True))
op.add_column('authorization_code', sa.Column('scope', sa.String(length=128), nullable=True))
op.add_column('oauth_token', sa.Column('redirect_uri', sa.String(length=1024), nullable=True))
op.add_column('oauth_token', sa.Column('scope', sa.String(length=128), nullable=True))
# ### end Alembic commands ### | null |
180,551 | from alembic import op
import sqlalchemy as sa
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('oauth_token', 'scope')
op.drop_column('oauth_token', 'redirect_uri')
op.drop_column('authorization_code', 'scope')
op.drop_column('authorization_code', 'redirect_uri')
# ### end Alembic commands ### | null |
180,552 | from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
config = context.config
import sys
from app.models import Base
from app.config import DB_URI
target_metadata = Base.metadata
config.set_main_option('sqlalchemy.url', DB_URI)
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
The provided code snippet includes necessary dependencies for implementing the `run_migrations_offline` function. Write a Python function `def run_migrations_offline()` to solve the following problem:
Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output.
Here is the function:
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations() | Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output. |
180,553 | from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
config = context.config
import sys
from app.models import Base
from app.config import DB_URI
target_metadata = Base.metadata
config.set_main_option('sqlalchemy.url', DB_URI)
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
The provided code snippet includes necessary dependencies for implementing the `run_migrations_online` function. Write a Python function `def run_migrations_online()` to solve the following problem:
Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context.
Here is the function:
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata
)
with context.begin_transaction():
context.run_migrations() | Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. |
180,554 | import argparse
import asyncio
import urllib.parse
from typing import List, Tuple
import arrow
import requests
from sqlalchemy import func, desc, or_, and_
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.orm import joinedload
from sqlalchemy.orm.exc import ObjectDeletedError
from sqlalchemy.sql import Insert, text
from app import s3, config
from app.alias_utils import nb_email_log_for_mailbox
from app.api.views.apple import verify_receipt
from app.db import Session
from app.dns_utils import get_mx_domains, is_mx_equivalent
from app.email_utils import (
send_email,
send_trial_end_soon_email,
render,
email_can_be_used_as_mailbox,
send_email_with_rate_control,
get_email_domain_part,
)
from app.email_validation import is_valid_email, normalize_reply_email
from app.errors import ProtonPartnerNotSetUp
from app.log import LOG
from app.mail_sender import load_unsent_mails_from_fs_and_resend
from app.models import (
Subscription,
User,
Alias,
EmailLog,
CustomDomain,
Client,
ManualSubscription,
RefusedEmail,
AppleSubscription,
Mailbox,
Monitoring,
Contact,
CoinbaseSubscription,
TransactionalEmail,
Bounce,
Metric2,
SLDomain,
DeletedAlias,
DomainDeletedAlias,
Hibp,
HibpNotifiedAlias,
Directory,
DeletedDirectory,
DeletedSubdomain,
PartnerSubscription,
PartnerUser,
ApiToCookieToken,
)
from app.pgp_utils import load_public_key_and_check, PGPException
from app.proton.utils import get_proton_partner
from app.utils import sanitize_email
from server import create_light_app
from tasks.cleanup_old_imports import cleanup_old_imports
from tasks.cleanup_old_jobs import cleanup_old_jobs
from tasks.cleanup_old_notifications import cleanup_old_notifications
def send_trial_end_soon_email(user):
LOG = _get_logger("SL")
class User(Base, ModelMixin, UserMixin, PasswordOracle):
def directory_quota(self):
def subdomain_quota(self):
def created_by_partner(self):
def subdomain_is_available():
def get_id(self):
def create(cls, email, name="", password=None, from_partner=False, **kwargs):
def get_active_subscription(
self, include_partner_subscription: bool = True
) -> Optional[
Union[
Subscription
| AppleSubscription
| ManualSubscription
| CoinbaseSubscription
| PartnerSubscription
]
]:
def get_active_subscription_end(
self, include_partner_subscription: bool = True
) -> Optional[arrow.Arrow]:
def lifetime_or_active_subscription(
self, include_partner_subscription: bool = True
) -> bool:
def is_paid(self) -> bool:
def is_active(self) -> bool:
def in_trial(self):
def should_show_upgrade_button(self):
def is_premium(self, include_partner_subscription: bool = True) -> bool:
def upgrade_channel(self) -> str:
def max_alias_for_free_account(self) -> int:
def can_create_new_alias(self) -> bool:
def can_send_or_receive(self) -> bool:
def profile_picture_url(self):
def suggested_emails(self, website_name) -> (str, [str]):
def suggested_names(self) -> (str, [str]):
def get_name_initial(self) -> str:
def get_paddle_subscription(self) -> Optional["Subscription"]:
def verified_custom_domains(self) -> List["CustomDomain"]:
def mailboxes(self) -> List["Mailbox"]:
def nb_directory(self):
def has_custom_domain(self):
def custom_domains(self):
def available_domains_for_random_alias(
self, alias_options: Optional[AliasOptions] = None
) -> List[Tuple[bool, str]]:
def default_random_alias_domain(self) -> str:
def fido_enabled(self) -> bool:
def two_factor_authentication_enabled(self) -> bool:
def get_communication_email(self) -> (Optional[str], str, bool):
def available_sl_domains(
self, alias_options: Optional[AliasOptions] = None
) -> [str]:
def get_sl_domains(
self, alias_options: Optional[AliasOptions] = None
) -> list["SLDomain"]:
def available_alias_domains(
self, alias_options: Optional[AliasOptions] = None
) -> [str]:
def should_show_app_page(self) -> bool:
def get_random_alias_suffix(self, custom_domain: Optional["CustomDomain"] = None):
def can_create_contacts(self) -> bool:
def __repr__(self):
def notify_trial_end():
for user in User.filter(
User.activated.is_(True),
User.trial_end.isnot(None),
User.trial_end >= arrow.now().shift(days=2),
User.trial_end < arrow.now().shift(days=3),
User.lifetime.is_(False),
).all():
try:
if user.in_trial():
LOG.d("Send trial end email to user %s", user)
send_trial_end_soon_email(user)
# happens if user has been deleted in the meantime
except ObjectDeletedError:
LOG.i("user has been deleted") | null |
180,555 | import argparse
import asyncio
import urllib.parse
from typing import List, Tuple
import arrow
import requests
from sqlalchemy import func, desc, or_, and_
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.orm import joinedload
from sqlalchemy.orm.exc import ObjectDeletedError
from sqlalchemy.sql import Insert, text
from app import s3, config
from app.alias_utils import nb_email_log_for_mailbox
from app.api.views.apple import verify_receipt
from app.db import Session
from app.dns_utils import get_mx_domains, is_mx_equivalent
from app.email_utils import (
send_email,
send_trial_end_soon_email,
render,
email_can_be_used_as_mailbox,
send_email_with_rate_control,
get_email_domain_part,
)
from app.email_validation import is_valid_email, normalize_reply_email
from app.errors import ProtonPartnerNotSetUp
from app.log import LOG
from app.mail_sender import load_unsent_mails_from_fs_and_resend
from app.models import (
Subscription,
User,
Alias,
EmailLog,
CustomDomain,
Client,
ManualSubscription,
RefusedEmail,
AppleSubscription,
Mailbox,
Monitoring,
Contact,
CoinbaseSubscription,
TransactionalEmail,
Bounce,
Metric2,
SLDomain,
DeletedAlias,
DomainDeletedAlias,
Hibp,
HibpNotifiedAlias,
Directory,
DeletedDirectory,
DeletedSubdomain,
PartnerSubscription,
PartnerUser,
ApiToCookieToken,
)
from app.pgp_utils import load_public_key_and_check, PGPException
from app.proton.utils import get_proton_partner
from app.utils import sanitize_email
from server import create_light_app
from tasks.cleanup_old_imports import cleanup_old_imports
from tasks.cleanup_old_jobs import cleanup_old_jobs
from tasks.cleanup_old_notifications import cleanup_old_notifications
def delete_refused_emails():
for refused_email in (
RefusedEmail.filter_by(deleted=False).order_by(RefusedEmail.id).all()
):
if arrow.now().shift(days=1) > refused_email.delete_at >= arrow.now():
LOG.d("Delete refused email %s", refused_email)
if refused_email.path:
s3.delete(refused_email.path)
s3.delete(refused_email.full_report_path)
# do not set path and full_report_path to null
# so we can check later that the files are indeed deleted
refused_email.delete_at = arrow.now()
refused_email.deleted = True
Session.commit()
LOG.d("Finish delete_refused_emails")
def delete_old_monitoring():
"""
Delete old monitoring records
"""
max_time = arrow.now().shift(days=-30)
nb_row = Monitoring.filter(Monitoring.created_at < max_time).delete()
Session.commit()
LOG.d("delete monitoring records older than %s, nb row %s", max_time, nb_row)
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
LOG = _get_logger("SL")
class EmailLog(Base, ModelMixin):
__tablename__ = "email_log"
__table_args__ = (Index("ix_email_log_created_at", "created_at"),)
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, index=True
)
contact_id = sa.Column(
sa.ForeignKey(Contact.id, ondelete="cascade"), nullable=False, index=True
)
alias_id = sa.Column(
sa.ForeignKey(Alias.id, ondelete="cascade"), nullable=True, index=True
)
# whether this is a reply
is_reply = sa.Column(sa.Boolean, nullable=False, default=False)
# for ex if alias is disabled, this forwarding is blocked
blocked = sa.Column(sa.Boolean, nullable=False, default=False)
# can happen when user mailbox refuses the forwarded email
# usually because the forwarded email is too spammy
bounced = sa.Column(sa.Boolean, nullable=False, default=False, server_default="0")
# happen when an email with auto (holiday) reply
auto_replied = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# SpamAssassin result
is_spam = sa.Column(sa.Boolean, nullable=False, default=False, server_default="0")
spam_score = sa.Column(sa.Float, nullable=True)
spam_status = sa.Column(sa.Text, nullable=True, default=None)
# do not load this column
spam_report = deferred(sa.Column(sa.JSON, nullable=True))
# Point to the email that has been refused
refused_email_id = sa.Column(
sa.ForeignKey("refused_email.id", ondelete="SET NULL"), nullable=True
)
# in forward phase, this is the mailbox that will receive the email
# in reply phase, this is the mailbox (or a mailbox's authorized address) that sends the email
mailbox_id = sa.Column(
sa.ForeignKey("mailbox.id", ondelete="cascade"), nullable=True
)
# in case of bounce, record on what mailbox the email has been bounced
# useful when an alias has several mailboxes
bounced_mailbox_id = sa.Column(
sa.ForeignKey("mailbox.id", ondelete="cascade"), nullable=True
)
# the Message ID
message_id = deferred(sa.Column(sa.String(1024), nullable=True))
# in the reply phase, the original message_id is replaced by the SL message_id
sl_message_id = deferred(sa.Column(sa.String(512), nullable=True))
refused_email = orm.relationship("RefusedEmail")
forward = orm.relationship(Contact)
contact = orm.relationship(Contact, backref="email_logs")
alias = orm.relationship(Alias)
mailbox = orm.relationship("Mailbox", lazy="joined", foreign_keys=[mailbox_id])
user = orm.relationship(User)
def bounced_mailbox(self) -> str:
if self.bounced_mailbox_id:
return Mailbox.get(self.bounced_mailbox_id).email
# retro-compatibility
return self.contact.alias.mailboxes[0].email
def get_action(self) -> str:
"""return the action name: forward|reply|block|bounced"""
if self.is_reply:
return "reply"
elif self.bounced:
return "bounced"
elif self.blocked:
return "block"
else:
return "forward"
def get_phase(self) -> str:
if self.is_reply:
return "reply"
else:
return "forward"
def get_dashboard_url(self):
return f"{config.URL}/dashboard/refused_email?highlight_id={self.id}"
def create(cls, *args, **kwargs):
commit = kwargs.pop("commit", False)
email_log = super().create(*args, **kwargs)
Session.flush()
if "alias_id" in kwargs:
sql = "UPDATE alias SET last_email_log_id = :el_id WHERE id = :alias_id"
Session.execute(
sql, {"el_id": email_log.id, "alias_id": kwargs["alias_id"]}
)
if commit:
Session.commit()
return email_log
def __repr__(self):
return f"<EmailLog {self.id}>"
class Bounce(Base, ModelMixin):
"""Record all bounces. Deleted after 7 days"""
__tablename__ = "bounce"
email = sa.Column(sa.String(256), nullable=False, index=True)
info = sa.Column(sa.Text, nullable=True)
__table_args__ = (sa.Index("ix_bounce_created_at", "created_at"),)
class TransactionalEmail(Base, ModelMixin):
"""Storing all email addresses that receive transactional emails, including account email and mailboxes.
Deleted after 7 days
"""
__tablename__ = "transactional_email"
email = sa.Column(sa.String(256), nullable=False, unique=False)
__table_args__ = (sa.Index("ix_transactional_email_created_at", "created_at"),)
def create(cls, **kw):
# whether to call Session.commit
commit = kw.pop("commit", False)
r = cls(**kw)
if not config.STORE_TRANSACTIONAL_EMAILS:
return r
Session.add(r)
if commit:
Session.commit()
return r
The provided code snippet includes necessary dependencies for implementing the `delete_logs` function. Write a Python function `def delete_logs()` to solve the following problem:
delete everything that are considered logs
Here is the function:
def delete_logs():
"""delete everything that are considered logs"""
delete_refused_emails()
delete_old_monitoring()
for t_email in TransactionalEmail.filter(
TransactionalEmail.created_at < arrow.now().shift(days=-7)
):
TransactionalEmail.delete(t_email.id)
for b in Bounce.filter(Bounce.created_at < arrow.now().shift(days=-7)):
Bounce.delete(b.id)
Session.commit()
LOG.d("Deleting EmailLog older than 2 weeks")
total_deleted = 0
batch_size = 500
Session.execute("set session statement_timeout=30000").rowcount
queries_done = 0
cutoff_time = arrow.now().shift(days=-14)
rows_to_delete = EmailLog.filter(EmailLog.created_at < cutoff_time).count()
expected_queries = int(rows_to_delete / batch_size)
sql = text(
"DELETE FROM email_log WHERE id IN (SELECT id FROM email_log WHERE created_at < :cutoff_time order by created_at limit :batch_size)"
)
str_cutoff_time = cutoff_time.isoformat()
while total_deleted < rows_to_delete:
deleted_count = Session.execute(
sql, {"cutoff_time": str_cutoff_time, "batch_size": batch_size}
).rowcount
Session.commit()
total_deleted += deleted_count
queries_done += 1
LOG.i(
f"[{queries_done}/{expected_queries}] Deleted {total_deleted} EmailLog entries"
)
if deleted_count < batch_size:
break
LOG.i("Deleted %s email logs", total_deleted) | delete everything that are considered logs |
180,556 | import argparse
import asyncio
import urllib.parse
from typing import List, Tuple
import arrow
import requests
from sqlalchemy import func, desc, or_, and_
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.orm import joinedload
from sqlalchemy.orm.exc import ObjectDeletedError
from sqlalchemy.sql import Insert, text
from app import s3, config
from app.alias_utils import nb_email_log_for_mailbox
from app.api.views.apple import verify_receipt
from app.db import Session
from app.dns_utils import get_mx_domains, is_mx_equivalent
from app.email_utils import (
send_email,
send_trial_end_soon_email,
render,
email_can_be_used_as_mailbox,
send_email_with_rate_control,
get_email_domain_part,
)
from app.email_validation import is_valid_email, normalize_reply_email
from app.errors import ProtonPartnerNotSetUp
from app.log import LOG
from app.mail_sender import load_unsent_mails_from_fs_and_resend
from app.models import (
Subscription,
User,
Alias,
EmailLog,
CustomDomain,
Client,
ManualSubscription,
RefusedEmail,
AppleSubscription,
Mailbox,
Monitoring,
Contact,
CoinbaseSubscription,
TransactionalEmail,
Bounce,
Metric2,
SLDomain,
DeletedAlias,
DomainDeletedAlias,
Hibp,
HibpNotifiedAlias,
Directory,
DeletedDirectory,
DeletedSubdomain,
PartnerSubscription,
PartnerUser,
ApiToCookieToken,
)
from app.pgp_utils import load_public_key_and_check, PGPException
from app.proton.utils import get_proton_partner
from app.utils import sanitize_email
from server import create_light_app
from tasks.cleanup_old_imports import cleanup_old_imports
from tasks.cleanup_old_jobs import cleanup_old_jobs
from tasks.cleanup_old_notifications import cleanup_old_notifications
def render(template_name, **kwargs) -> str:
templates_dir = os.path.join(config.ROOT_DIR, "templates", "emails")
env = Environment(loader=FileSystemLoader(templates_dir))
template = env.get_template(template_name)
return template.render(
MAX_NB_EMAIL_FREE_PLAN=config.MAX_NB_EMAIL_FREE_PLAN,
URL=config.URL,
LANDING_PAGE_URL=config.LANDING_PAGE_URL,
YEAR=arrow.now().year,
**kwargs,
)
def send_email(
to_email,
subject,
plaintext,
html=None,
unsubscribe_link=None,
unsubscribe_via_email=False,
retries=0, # by default no retry if sending fails
ignore_smtp_error=False,
from_name=None,
from_addr=None,
):
to_email = sanitize_email(to_email)
LOG.d("send email to %s, subject '%s'", to_email, subject)
from_name = from_name or config.NOREPLY
from_addr = from_addr or config.NOREPLY
from_domain = get_email_domain_part(from_addr)
if html:
msg = MIMEMultipart("alternative")
msg.attach(MIMEText(plaintext))
msg.attach(MIMEText(html, "html"))
else:
msg = EmailMessage()
msg.set_payload(plaintext)
msg[headers.CONTENT_TYPE] = "text/plain"
msg[headers.SUBJECT] = subject
msg[headers.FROM] = f'"{from_name}" <{from_addr}>'
msg[headers.TO] = to_email
msg_id_header = make_msgid(domain=config.EMAIL_DOMAIN)
msg[headers.MESSAGE_ID] = msg_id_header
date_header = formatdate()
msg[headers.DATE] = date_header
if headers.MIME_VERSION not in msg:
msg[headers.MIME_VERSION] = "1.0"
if unsubscribe_link:
add_or_replace_header(msg, headers.LIST_UNSUBSCRIBE, f"<{unsubscribe_link}>")
if not unsubscribe_via_email:
add_or_replace_header(
msg, headers.LIST_UNSUBSCRIBE_POST, "List-Unsubscribe=One-Click"
)
# add DKIM
email_domain = from_addr[from_addr.find("@") + 1 :]
add_dkim_signature(msg, email_domain)
transaction = TransactionalEmail.create(email=to_email, commit=True)
# use a different envelope sender for each transactional email (aka VERP)
sl_sendmail(
generate_verp_email(VerpType.transactional, transaction.id, from_domain),
to_email,
msg,
retries=retries,
ignore_smtp_error=ignore_smtp_error,
)
LOG = _get_logger("SL")
class Subscription(Base, ModelMixin):
"""Paddle subscription"""
__tablename__ = "subscription"
# Come from Paddle
cancel_url = sa.Column(sa.String(1024), nullable=False)
update_url = sa.Column(sa.String(1024), nullable=False)
subscription_id = sa.Column(sa.String(1024), nullable=False, unique=True)
event_time = sa.Column(ArrowType, nullable=False)
next_bill_date = sa.Column(sa.Date, nullable=False)
cancelled = sa.Column(sa.Boolean, nullable=False, default=False)
plan = sa.Column(sa.Enum(PlanEnum), nullable=False)
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, unique=True
)
user = orm.relationship(User)
def plan_name(self):
if self.plan == PlanEnum.monthly:
return "Monthly"
else:
return "Yearly"
def __repr__(self):
return f"<Subscription {self.plan} {self.next_bill_date}>"
The provided code snippet includes necessary dependencies for implementing the `notify_premium_end` function. Write a Python function `def notify_premium_end()` to solve the following problem:
sent to user who has canceled their subscription and who has their subscription ending soon
Here is the function:
def notify_premium_end():
"""sent to user who has canceled their subscription and who has their subscription ending soon"""
for sub in Subscription.filter_by(cancelled=True).all():
if (
arrow.now().shift(days=3).date()
> sub.next_bill_date
>= arrow.now().shift(days=2).date()
):
user = sub.user
if user.lifetime:
continue
LOG.d(f"Send subscription ending soon email to user {user}")
send_email(
user.email,
"Your subscription will end soon",
render(
"transactional/subscription-end.txt",
user=user,
next_bill_date=sub.next_bill_date.strftime("%Y-%m-%d"),
),
render(
"transactional/subscription-end.html",
user=user,
next_bill_date=sub.next_bill_date.strftime("%Y-%m-%d"),
),
retries=3,
) | sent to user who has canceled their subscription and who has their subscription ending soon |
180,557 | import argparse
import asyncio
import urllib.parse
from typing import List, Tuple
import arrow
import requests
from sqlalchemy import func, desc, or_, and_
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.orm import joinedload
from sqlalchemy.orm.exc import ObjectDeletedError
from sqlalchemy.sql import Insert, text
from app import s3, config
from app.alias_utils import nb_email_log_for_mailbox
from app.api.views.apple import verify_receipt
from app.db import Session
from app.dns_utils import get_mx_domains, is_mx_equivalent
from app.email_utils import (
send_email,
send_trial_end_soon_email,
render,
email_can_be_used_as_mailbox,
send_email_with_rate_control,
get_email_domain_part,
)
from app.email_validation import is_valid_email, normalize_reply_email
from app.errors import ProtonPartnerNotSetUp
from app.log import LOG
from app.mail_sender import load_unsent_mails_from_fs_and_resend
from app.models import (
Subscription,
User,
Alias,
EmailLog,
CustomDomain,
Client,
ManualSubscription,
RefusedEmail,
AppleSubscription,
Mailbox,
Monitoring,
Contact,
CoinbaseSubscription,
TransactionalEmail,
Bounce,
Metric2,
SLDomain,
DeletedAlias,
DomainDeletedAlias,
Hibp,
HibpNotifiedAlias,
Directory,
DeletedDirectory,
DeletedSubdomain,
PartnerSubscription,
PartnerUser,
ApiToCookieToken,
)
from app.pgp_utils import load_public_key_and_check, PGPException
from app.proton.utils import get_proton_partner
from app.utils import sanitize_email
from server import create_light_app
from tasks.cleanup_old_imports import cleanup_old_imports
from tasks.cleanup_old_jobs import cleanup_old_jobs
from tasks.cleanup_old_notifications import cleanup_old_notifications
def render(template_name, **kwargs) -> str:
def send_email(
to_email,
subject,
plaintext,
html=None,
unsubscribe_link=None,
unsubscribe_via_email=False,
retries=0, # by default no retry if sending fails
ignore_smtp_error=False,
from_name=None,
from_addr=None,
):
LOG = _get_logger("SL")
class Subscription(Base, ModelMixin):
def plan_name(self):
def __repr__(self):
class ManualSubscription(Base, ModelMixin):
def is_active(self):
class CoinbaseSubscription(Base, ModelMixin):
def is_active(self):
class AppleSubscription(Base, ModelMixin):
def is_valid(self):
def notify_manual_sub_end():
for manual_sub in ManualSubscription.all():
manual_sub: ManualSubscription
need_reminder = False
if arrow.now().shift(days=14) > manual_sub.end_at > arrow.now().shift(days=13):
need_reminder = True
elif arrow.now().shift(days=4) > manual_sub.end_at > arrow.now().shift(days=3):
need_reminder = True
user = manual_sub.user
if user.lifetime:
LOG.d("%s has a lifetime licence", user)
continue
paddle_sub: Subscription = user.get_paddle_subscription()
if paddle_sub and not paddle_sub.cancelled:
LOG.d("%s has an active Paddle subscription", user)
continue
if need_reminder:
# user can have a (free) manual subscription but has taken a paid subscription via
# Paddle, Coinbase or Apple since then
if manual_sub.is_giveaway:
if user.get_paddle_subscription():
LOG.d("%s has a active Paddle subscription", user)
continue
coinbase_subscription: CoinbaseSubscription = (
CoinbaseSubscription.get_by(user_id=user.id)
)
if coinbase_subscription and coinbase_subscription.is_active():
LOG.d("%s has a active Coinbase subscription", user)
continue
apple_sub: AppleSubscription = AppleSubscription.get_by(user_id=user.id)
if apple_sub and apple_sub.is_valid():
LOG.d("%s has a active Apple subscription", user)
continue
LOG.d("Remind user %s that their manual sub is ending soon", user)
send_email(
user.email,
"Your subscription will end soon",
render(
"transactional/manual-subscription-end.txt",
user=user,
manual_sub=manual_sub,
),
render(
"transactional/manual-subscription-end.html",
user=user,
manual_sub=manual_sub,
),
retries=3,
)
extend_subscription_url = config.URL + "/dashboard/coinbase_checkout"
for coinbase_subscription in CoinbaseSubscription.all():
need_reminder = False
if (
arrow.now().shift(days=14)
> coinbase_subscription.end_at
> arrow.now().shift(days=13)
):
need_reminder = True
elif (
arrow.now().shift(days=4)
> coinbase_subscription.end_at
> arrow.now().shift(days=3)
):
need_reminder = True
if need_reminder:
user = coinbase_subscription.user
if user.lifetime:
continue
LOG.d(
"Remind user %s that their coinbase subscription is ending soon", user
)
send_email(
user.email,
"Your SimpleLogin subscription will end soon",
render(
"transactional/coinbase/reminder-subscription.txt",
coinbase_subscription=coinbase_subscription,
extend_subscription_url=extend_subscription_url,
),
render(
"transactional/coinbase/reminder-subscription.html",
coinbase_subscription=coinbase_subscription,
extend_subscription_url=extend_subscription_url,
),
retries=3,
) | null |
180,558 | import argparse
import asyncio
import urllib.parse
from typing import List, Tuple
import arrow
import requests
from sqlalchemy import func, desc, or_, and_
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.orm import joinedload
from sqlalchemy.orm.exc import ObjectDeletedError
from sqlalchemy.sql import Insert, text
from app import s3, config
from app.alias_utils import nb_email_log_for_mailbox
from app.api.views.apple import verify_receipt
from app.db import Session
from app.dns_utils import get_mx_domains, is_mx_equivalent
from app.email_utils import (
send_email,
send_trial_end_soon_email,
render,
email_can_be_used_as_mailbox,
send_email_with_rate_control,
get_email_domain_part,
)
from app.email_validation import is_valid_email, normalize_reply_email
from app.errors import ProtonPartnerNotSetUp
from app.log import LOG
from app.mail_sender import load_unsent_mails_from_fs_and_resend
from app.models import (
Subscription,
User,
Alias,
EmailLog,
CustomDomain,
Client,
ManualSubscription,
RefusedEmail,
AppleSubscription,
Mailbox,
Monitoring,
Contact,
CoinbaseSubscription,
TransactionalEmail,
Bounce,
Metric2,
SLDomain,
DeletedAlias,
DomainDeletedAlias,
Hibp,
HibpNotifiedAlias,
Directory,
DeletedDirectory,
DeletedSubdomain,
PartnerSubscription,
PartnerUser,
ApiToCookieToken,
)
from app.pgp_utils import load_public_key_and_check, PGPException
from app.proton.utils import get_proton_partner
from app.utils import sanitize_email
from server import create_light_app
from tasks.cleanup_old_imports import cleanup_old_imports
from tasks.cleanup_old_jobs import cleanup_old_jobs
from tasks.cleanup_old_notifications import cleanup_old_notifications
def verify_receipt(receipt_data, user, password) -> Optional[AppleSubscription]:
"""
Call https://buy.itunes.apple.com/verifyReceipt and create/update AppleSubscription table
Call the production URL for verifyReceipt first,
use sandbox URL if receive a 21007 status code.
Return AppleSubscription object if success
https://developer.apple.com/documentation/appstorereceipts/verifyreceipt
"""
LOG.d("start verify_receipt")
try:
r = requests.post(
_PROD_URL, json={"receipt-data": receipt_data, "password": password}
)
except RequestException:
LOG.w("cannot call Apple server %s", _PROD_URL)
return None
if r.status_code >= 500:
LOG.w("Apple server error, response:%s %s", r, r.content)
return None
if r.json() == {"status": 21007}:
# try sandbox_url
LOG.w("Use the sandbox url instead")
r = requests.post(
_SANDBOX_URL,
json={"receipt-data": receipt_data, "password": password},
)
data = r.json()
# data has the following format
# {
# "status": 0,
# "environment": "Sandbox",
# "receipt": {
# "receipt_type": "ProductionSandbox",
# "adam_id": 0,
# "app_item_id": 0,
# "bundle_id": "io.simplelogin.ios-app",
# "application_version": "2",
# "download_id": 0,
# "version_external_identifier": 0,
# "receipt_creation_date": "2020-04-18 16:36:34 Etc/GMT",
# "receipt_creation_date_ms": "1587227794000",
# "receipt_creation_date_pst": "2020-04-18 09:36:34 America/Los_Angeles",
# "request_date": "2020-04-18 16:46:36 Etc/GMT",
# "request_date_ms": "1587228396496",
# "request_date_pst": "2020-04-18 09:46:36 America/Los_Angeles",
# "original_purchase_date": "2013-08-01 07:00:00 Etc/GMT",
# "original_purchase_date_ms": "1375340400000",
# "original_purchase_date_pst": "2013-08-01 00:00:00 America/Los_Angeles",
# "original_application_version": "1.0",
# "in_app": [
# {
# "quantity": "1",
# "product_id": "io.simplelogin.ios_app.subscription.premium.monthly",
# "transaction_id": "1000000653584474",
# "original_transaction_id": "1000000653584474",
# "purchase_date": "2020-04-18 16:27:42 Etc/GMT",
# "purchase_date_ms": "1587227262000",
# "purchase_date_pst": "2020-04-18 09:27:42 America/Los_Angeles",
# "original_purchase_date": "2020-04-18 16:27:44 Etc/GMT",
# "original_purchase_date_ms": "1587227264000",
# "original_purchase_date_pst": "2020-04-18 09:27:44 America/Los_Angeles",
# "expires_date": "2020-04-18 16:32:42 Etc/GMT",
# "expires_date_ms": "1587227562000",
# "expires_date_pst": "2020-04-18 09:32:42 America/Los_Angeles",
# "web_order_line_item_id": "1000000051847459",
# "is_trial_period": "false",
# "is_in_intro_offer_period": "false",
# },
# {
# "quantity": "1",
# "product_id": "io.simplelogin.ios_app.subscription.premium.monthly",
# "transaction_id": "1000000653584861",
# "original_transaction_id": "1000000653584474",
# "purchase_date": "2020-04-18 16:32:42 Etc/GMT",
# "purchase_date_ms": "1587227562000",
# "purchase_date_pst": "2020-04-18 09:32:42 America/Los_Angeles",
# "original_purchase_date": "2020-04-18 16:27:44 Etc/GMT",
# "original_purchase_date_ms": "1587227264000",
# "original_purchase_date_pst": "2020-04-18 09:27:44 America/Los_Angeles",
# "expires_date": "2020-04-18 16:37:42 Etc/GMT",
# "expires_date_ms": "1587227862000",
# "expires_date_pst": "2020-04-18 09:37:42 America/Los_Angeles",
# "web_order_line_item_id": "1000000051847461",
# "is_trial_period": "false",
# "is_in_intro_offer_period": "false",
# },
# ],
# },
# "latest_receipt_info": [
# {
# "quantity": "1",
# "product_id": "io.simplelogin.ios_app.subscription.premium.monthly",
# "transaction_id": "1000000653584474",
# "original_transaction_id": "1000000653584474",
# "purchase_date": "2020-04-18 16:27:42 Etc/GMT",
# "purchase_date_ms": "1587227262000",
# "purchase_date_pst": "2020-04-18 09:27:42 America/Los_Angeles",
# "original_purchase_date": "2020-04-18 16:27:44 Etc/GMT",
# "original_purchase_date_ms": "1587227264000",
# "original_purchase_date_pst": "2020-04-18 09:27:44 America/Los_Angeles",
# "expires_date": "2020-04-18 16:32:42 Etc/GMT",
# "expires_date_ms": "1587227562000",
# "expires_date_pst": "2020-04-18 09:32:42 America/Los_Angeles",
# "web_order_line_item_id": "1000000051847459",
# "is_trial_period": "false",
# "is_in_intro_offer_period": "false",
# "subscription_group_identifier": "20624274",
# },
# {
# "quantity": "1",
# "product_id": "io.simplelogin.ios_app.subscription.premium.monthly",
# "transaction_id": "1000000653584861",
# "original_transaction_id": "1000000653584474",
# "purchase_date": "2020-04-18 16:32:42 Etc/GMT",
# "purchase_date_ms": "1587227562000",
# "purchase_date_pst": "2020-04-18 09:32:42 America/Los_Angeles",
# "original_purchase_date": "2020-04-18 16:27:44 Etc/GMT",
# "original_purchase_date_ms": "1587227264000",
# "original_purchase_date_pst": "2020-04-18 09:27:44 America/Los_Angeles",
# "expires_date": "2020-04-18 16:37:42 Etc/GMT",
# "expires_date_ms": "1587227862000",
# "expires_date_pst": "2020-04-18 09:37:42 America/Los_Angeles",
# "web_order_line_item_id": "1000000051847461",
# "is_trial_period": "false",
# "is_in_intro_offer_period": "false",
# "subscription_group_identifier": "20624274",
# },
# {
# "quantity": "1",
# "product_id": "io.simplelogin.ios_app.subscription.premium.monthly",
# "transaction_id": "1000000653585235",
# "original_transaction_id": "1000000653584474",
# "purchase_date": "2020-04-18 16:38:16 Etc/GMT",
# "purchase_date_ms": "1587227896000",
# "purchase_date_pst": "2020-04-18 09:38:16 America/Los_Angeles",
# "original_purchase_date": "2020-04-18 16:27:44 Etc/GMT",
# "original_purchase_date_ms": "1587227264000",
# "original_purchase_date_pst": "2020-04-18 09:27:44 America/Los_Angeles",
# "expires_date": "2020-04-18 16:43:16 Etc/GMT",
# "expires_date_ms": "1587228196000",
# "expires_date_pst": "2020-04-18 09:43:16 America/Los_Angeles",
# "web_order_line_item_id": "1000000051847500",
# "is_trial_period": "false",
# "is_in_intro_offer_period": "false",
# "subscription_group_identifier": "20624274",
# },
# {
# "quantity": "1",
# "product_id": "io.simplelogin.ios_app.subscription.premium.monthly",
# "transaction_id": "1000000653585760",
# "original_transaction_id": "1000000653584474",
# "purchase_date": "2020-04-18 16:44:25 Etc/GMT",
# "purchase_date_ms": "1587228265000",
# "purchase_date_pst": "2020-04-18 09:44:25 America/Los_Angeles",
# "original_purchase_date": "2020-04-18 16:27:44 Etc/GMT",
# "original_purchase_date_ms": "1587227264000",
# "original_purchase_date_pst": "2020-04-18 09:27:44 America/Los_Angeles",
# "expires_date": "2020-04-18 16:49:25 Etc/GMT",
# "expires_date_ms": "1587228565000",
# "expires_date_pst": "2020-04-18 09:49:25 America/Los_Angeles",
# "web_order_line_item_id": "1000000051847566",
# "is_trial_period": "false",
# "is_in_intro_offer_period": "false",
# "subscription_group_identifier": "20624274",
# },
# ],
# "latest_receipt": "very long string",
# "pending_renewal_info": [
# {
# "auto_renew_product_id": "io.simplelogin.ios_app.subscription.premium.monthly",
# "original_transaction_id": "1000000653584474",
# "product_id": "io.simplelogin.ios_app.subscription.premium.monthly",
# "auto_renew_status": "1",
# }
# ],
# }
if data["status"] != 0:
LOG.e(
"verifyReceipt status !=0, probably invalid receipt. User %s, data %s",
user,
data,
)
return None
# use responseBody.Latest_receipt_info and not responseBody.Receipt.In_app
# as recommended on https://developer.apple.com/documentation/appstorereceipts/responsebody/receipt/in_app
# each item in data["latest_receipt_info"] has the following format
# {
# "quantity": "1",
# "product_id": "io.simplelogin.ios_app.subscription.premium.monthly",
# "transaction_id": "1000000653584474",
# "original_transaction_id": "1000000653584474",
# "purchase_date": "2020-04-18 16:27:42 Etc/GMT",
# "purchase_date_ms": "1587227262000",
# "purchase_date_pst": "2020-04-18 09:27:42 America/Los_Angeles",
# "original_purchase_date": "2020-04-18 16:27:44 Etc/GMT",
# "original_purchase_date_ms": "1587227264000",
# "original_purchase_date_pst": "2020-04-18 09:27:44 America/Los_Angeles",
# "expires_date": "2020-04-18 16:32:42 Etc/GMT",
# "expires_date_ms": "1587227562000",
# "expires_date_pst": "2020-04-18 09:32:42 America/Los_Angeles",
# "web_order_line_item_id": "1000000051847459",
# "is_trial_period": "false",
# "is_in_intro_offer_period": "false",
# }
transactions = data.get("latest_receipt_info")
if not transactions:
LOG.i("Empty transactions in data %s", data)
return None
latest_transaction = max(transactions, key=lambda t: int(t["expires_date_ms"]))
original_transaction_id = latest_transaction["original_transaction_id"]
expires_date = arrow.get(int(latest_transaction["expires_date_ms"]) / 1000)
plan = (
PlanEnum.monthly
if latest_transaction["product_id"]
in (
_MONTHLY_PRODUCT_ID,
_MACAPP_MONTHLY_PRODUCT_ID,
_MACAPP_MONTHLY_PRODUCT_ID_NEW,
)
else PlanEnum.yearly
)
apple_sub: AppleSubscription = AppleSubscription.get_by(user_id=user.id)
if apple_sub:
LOG.d(
"Update AppleSubscription for user %s, expired at %s (%s), plan %s",
user,
expires_date,
expires_date.humanize(),
plan,
)
apple_sub.receipt_data = receipt_data
apple_sub.expires_date = expires_date
apple_sub.original_transaction_id = original_transaction_id
apple_sub.product_id = latest_transaction["product_id"]
apple_sub.plan = plan
else:
# the same original_transaction_id has been used on another account
if AppleSubscription.get_by(original_transaction_id=original_transaction_id):
LOG.e("Same Apple Sub has been used before, current user %s", user)
return None
LOG.d(
"Create new AppleSubscription for user %s, expired at %s, plan %s",
user,
expires_date,
plan,
)
apple_sub = AppleSubscription.create(
user_id=user.id,
receipt_data=receipt_data,
expires_date=expires_date,
original_transaction_id=original_transaction_id,
plan=plan,
product_id=latest_transaction["product_id"],
)
execute_subscription_webhook(user)
Session.commit()
return apple_sub
LOG = _get_logger("SL")
class AppleSubscription(Base, ModelMixin):
"""
For users who have subscribed via Apple in-app payment
"""
__tablename__ = "apple_subscription"
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, unique=True
)
expires_date = sa.Column(ArrowType, nullable=False)
# to avoid using "Restore Purchase" on another account
original_transaction_id = sa.Column(sa.String(256), nullable=False, unique=True)
receipt_data = sa.Column(sa.Text(), nullable=False)
plan = sa.Column(sa.Enum(PlanEnum), nullable=False)
# to know what subscription user has bought
# e.g. io.simplelogin.ios_app.subscription.premium.monthly
product_id = sa.Column(sa.String(256), nullable=True)
user = orm.relationship(User)
def is_valid(self):
return self.expires_date > arrow.now().shift(days=-_APPLE_GRACE_PERIOD_DAYS)
The provided code snippet includes necessary dependencies for implementing the `poll_apple_subscription` function. Write a Python function `def poll_apple_subscription()` to solve the following problem:
Poll Apple API to update AppleSubscription
Here is the function:
def poll_apple_subscription():
"""Poll Apple API to update AppleSubscription"""
# todo: only near the end of the subscription
for apple_sub in AppleSubscription.all():
if not apple_sub.product_id:
LOG.d("Ignore %s", apple_sub)
continue
user = apple_sub.user
if "io.simplelogin.macapp.subscription" in apple_sub.product_id:
verify_receipt(apple_sub.receipt_data, user, config.MACAPP_APPLE_API_SECRET)
else:
verify_receipt(apple_sub.receipt_data, user, config.APPLE_API_SECRET)
LOG.d("Finish poll_apple_subscription") | Poll Apple API to update AppleSubscription |
180,559 | import argparse
import asyncio
import urllib.parse
from typing import List, Tuple
import arrow
import requests
from sqlalchemy import func, desc, or_, and_
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.orm import joinedload
from sqlalchemy.orm.exc import ObjectDeletedError
from sqlalchemy.sql import Insert, text
from app import s3, config
from app.alias_utils import nb_email_log_for_mailbox
from app.api.views.apple import verify_receipt
from app.db import Session
from app.dns_utils import get_mx_domains, is_mx_equivalent
from app.email_utils import (
send_email,
send_trial_end_soon_email,
render,
email_can_be_used_as_mailbox,
send_email_with_rate_control,
get_email_domain_part,
)
from app.email_validation import is_valid_email, normalize_reply_email
from app.errors import ProtonPartnerNotSetUp
from app.log import LOG
from app.mail_sender import load_unsent_mails_from_fs_and_resend
from app.models import (
Subscription,
User,
Alias,
EmailLog,
CustomDomain,
Client,
ManualSubscription,
RefusedEmail,
AppleSubscription,
Mailbox,
Monitoring,
Contact,
CoinbaseSubscription,
TransactionalEmail,
Bounce,
Metric2,
SLDomain,
DeletedAlias,
DomainDeletedAlias,
Hibp,
HibpNotifiedAlias,
Directory,
DeletedDirectory,
DeletedSubdomain,
PartnerSubscription,
PartnerUser,
ApiToCookieToken,
)
from app.pgp_utils import load_public_key_and_check, PGPException
from app.proton.utils import get_proton_partner
from app.utils import sanitize_email
from server import create_light_app
from tasks.cleanup_old_imports import cleanup_old_imports
from tasks.cleanup_old_jobs import cleanup_old_jobs
from tasks.cleanup_old_notifications import cleanup_old_notifications
def compute_metric2() -> Metric2:
now = arrow.now()
_24h_ago = now.shift(days=-1)
nb_referred_user_paid = 0
for user in (
User.filter(User.referral_id.isnot(None))
.yield_per(500)
.enable_eagerloads(False)
):
if user.is_paid():
nb_referred_user_paid += 1
# compute nb_proton_premium, nb_proton_user
nb_proton_premium = nb_proton_user = 0
try:
proton_partner = get_proton_partner()
nb_proton_premium = (
Session.query(PartnerSubscription, PartnerUser)
.filter(
PartnerSubscription.partner_user_id == PartnerUser.id,
PartnerUser.partner_id == proton_partner.id,
PartnerSubscription.end_at > now,
)
.count()
)
nb_proton_user = (
Session.query(PartnerUser)
.filter(
PartnerUser.partner_id == proton_partner.id,
)
.count()
)
except ProtonPartnerNotSetUp:
LOG.d("Proton partner not set up")
return Metric2.create(
date=now,
# user stats
nb_user=User.count(),
nb_activated_user=User.filter_by(activated=True).count(),
nb_proton_user=nb_proton_user,
# subscription stats
nb_premium=Subscription.filter(Subscription.cancelled.is_(False)).count(),
nb_cancelled_premium=Subscription.filter(
Subscription.cancelled.is_(True)
).count(),
# todo: filter by expires_date > now
nb_apple_premium=AppleSubscription.count(),
nb_manual_premium=ManualSubscription.filter(
ManualSubscription.end_at > now,
ManualSubscription.is_giveaway.is_(False),
).count(),
nb_coinbase_premium=CoinbaseSubscription.filter(
CoinbaseSubscription.end_at > now
).count(),
nb_proton_premium=nb_proton_premium,
# referral stats
nb_referred_user=User.filter(User.referral_id.isnot(None)).count(),
nb_referred_user_paid=nb_referred_user_paid,
nb_alias=Alias.count(),
# email log stats
nb_forward_last_24h=EmailLog.filter(EmailLog.created_at > _24h_ago)
.filter_by(bounced=False, is_spam=False, is_reply=False, blocked=False)
.count(),
nb_bounced_last_24h=EmailLog.filter(EmailLog.created_at > _24h_ago)
.filter_by(bounced=True)
.count(),
nb_total_bounced_last_24h=Bounce.filter(Bounce.created_at > _24h_ago).count(),
nb_reply_last_24h=EmailLog.filter(EmailLog.created_at > _24h_ago)
.filter_by(is_reply=True)
.count(),
nb_block_last_24h=EmailLog.filter(EmailLog.created_at > _24h_ago)
.filter_by(blocked=True)
.count(),
# other stats
nb_verified_custom_domain=CustomDomain.filter_by(verified=True).count(),
nb_subdomain=CustomDomain.filter_by(is_sl_subdomain=True).count(),
nb_directory=Directory.count(),
nb_deleted_directory=DeletedDirectory.count(),
nb_deleted_subdomain=DeletedSubdomain.count(),
nb_app=Client.count(),
commit=True,
)
def increase_percent(old, new) -> str:
if old == 0:
return "N/A"
if not old or not new:
return "N/A"
increase = (new - old) / old * 100
return f"{increase:.1f}%. Delta: {new - old}"
def bounce_report() -> List[Tuple[str, int]]:
"""return the accounts that have most bounces, e.g.
(email1, 30)
(email2, 20)
Produce this query
```
SELECT
count(*) AS c,
users.email
FROM
email_log,
users
WHERE
email_log.user_id = users.id
AND email_log.created_at > '2021-3-20'
and email_log.bounced = true
GROUP BY
users.email
ORDER BY
c DESC;
```
"""
min_dt = arrow.now().shift(days=-1)
query = (
Session.query(User.email, func.count(EmailLog.id).label("count"))
.join(EmailLog, EmailLog.user_id == User.id)
.filter(EmailLog.bounced, EmailLog.created_at > min_dt)
.group_by(User.email)
.having(func.count(EmailLog.id) > 5)
.order_by(desc("count"))
)
res = []
for email, count in query:
res.append((email, count))
return res
def all_bounce_report() -> str:
"""
Return a report for all mailboxes that have most bounces. Using this query to get mailboxes that have bounces.
For each mailbox in the list, return the first bounce info.
```
SELECT
email,
count(*) AS nb_bounce
FROM
bounce
WHERE
created_at > '2021-10-16'
GROUP BY
email
ORDER BY
nb_bounce DESC
```
"""
res = ""
min_dt = arrow.now().shift(days=-1)
query = (
Session.query(Bounce.email, func.count(Bounce.id).label("nb_bounce"))
.filter(Bounce.created_at > min_dt)
.group_by(Bounce.email)
# not return mailboxes that have too little bounces
.having(func.count(Bounce.id) > 3)
.order_by(desc("nb_bounce"))
)
for email, count in query:
res += f"{email}: {count} bounces. "
most_recent: Bounce = (
Bounce.filter(Bounce.email == email)
.order_by(Bounce.created_at.desc())
.first()
)
# most_recent.info can be very verbose
res += f"Most recent cause: \n{most_recent.info[:1000] if most_recent.info else 'N/A'}"
res += "\n----\n"
return res
def alias_creation_report() -> List[Tuple[str, int]]:
"""return the accounts that have created most aliases in the last 7 days, e.g.
(email1, 2021-3-21, 30)
(email2, 2021-3-20, 20)
Produce this query
```
SELECT
count(*) AS c,
users.email,
date(alias.created_at) AS d
FROM
alias,
users
WHERE
alias.user_id = users.id
AND alias.created_at > '2021-3-22'
GROUP BY
users.email,
d
HAVING
count(*) > 50
ORDER BY
c DESC;
```
"""
min_dt = arrow.now().shift(days=-7)
query = (
Session.query(
User.email,
func.count(Alias.id).label("count"),
func.date(Alias.created_at).label("date"),
)
.join(Alias, Alias.user_id == User.id)
.filter(Alias.created_at > min_dt)
.group_by(User.email, "date")
.having(func.count(Alias.id) > 50)
.order_by(desc("count"))
)
res = []
for email, count, date in query:
res.append((email, count, date))
return res
def send_email(
to_email,
subject,
plaintext,
html=None,
unsubscribe_link=None,
unsubscribe_via_email=False,
retries=0, # by default no retry if sending fails
ignore_smtp_error=False,
from_name=None,
from_addr=None,
):
to_email = sanitize_email(to_email)
LOG.d("send email to %s, subject '%s'", to_email, subject)
from_name = from_name or config.NOREPLY
from_addr = from_addr or config.NOREPLY
from_domain = get_email_domain_part(from_addr)
if html:
msg = MIMEMultipart("alternative")
msg.attach(MIMEText(plaintext))
msg.attach(MIMEText(html, "html"))
else:
msg = EmailMessage()
msg.set_payload(plaintext)
msg[headers.CONTENT_TYPE] = "text/plain"
msg[headers.SUBJECT] = subject
msg[headers.FROM] = f'"{from_name}" <{from_addr}>'
msg[headers.TO] = to_email
msg_id_header = make_msgid(domain=config.EMAIL_DOMAIN)
msg[headers.MESSAGE_ID] = msg_id_header
date_header = formatdate()
msg[headers.DATE] = date_header
if headers.MIME_VERSION not in msg:
msg[headers.MIME_VERSION] = "1.0"
if unsubscribe_link:
add_or_replace_header(msg, headers.LIST_UNSUBSCRIBE, f"<{unsubscribe_link}>")
if not unsubscribe_via_email:
add_or_replace_header(
msg, headers.LIST_UNSUBSCRIBE_POST, "List-Unsubscribe=One-Click"
)
# add DKIM
email_domain = from_addr[from_addr.find("@") + 1 :]
add_dkim_signature(msg, email_domain)
transaction = TransactionalEmail.create(email=to_email, commit=True)
# use a different envelope sender for each transactional email (aka VERP)
sl_sendmail(
generate_verp_email(VerpType.transactional, transaction.id, from_domain),
to_email,
msg,
retries=retries,
ignore_smtp_error=ignore_smtp_error,
)
LOG = _get_logger("SL")
class Metric2(Base, ModelMixin):
"""
For storing different metrics like number of users, etc
Store each metric as a column as opposed to having different rows as in Metric
"""
__tablename__ = "metric2"
date = sa.Column(ArrowType, default=arrow.utcnow, nullable=False)
nb_user = sa.Column(sa.Float, nullable=True)
nb_activated_user = sa.Column(sa.Float, nullable=True)
nb_proton_user = sa.Column(sa.Float, nullable=True)
nb_premium = sa.Column(sa.Float, nullable=True)
nb_apple_premium = sa.Column(sa.Float, nullable=True)
nb_cancelled_premium = sa.Column(sa.Float, nullable=True)
nb_manual_premium = sa.Column(sa.Float, nullable=True)
nb_coinbase_premium = sa.Column(sa.Float, nullable=True)
nb_proton_premium = sa.Column(sa.Float, nullable=True)
# nb users who have been referred
nb_referred_user = sa.Column(sa.Float, nullable=True)
nb_referred_user_paid = sa.Column(sa.Float, nullable=True)
nb_alias = sa.Column(sa.Float, nullable=True)
# Obsolete as only for the last 14 days
nb_forward = sa.Column(sa.Float, nullable=True)
nb_block = sa.Column(sa.Float, nullable=True)
nb_reply = sa.Column(sa.Float, nullable=True)
nb_bounced = sa.Column(sa.Float, nullable=True)
nb_spam = sa.Column(sa.Float, nullable=True)
# should be used instead
nb_forward_last_24h = sa.Column(sa.Float, nullable=True)
nb_block_last_24h = sa.Column(sa.Float, nullable=True)
nb_reply_last_24h = sa.Column(sa.Float, nullable=True)
nb_bounced_last_24h = sa.Column(sa.Float, nullable=True)
# includes bounces for both forwarding and transactional email
nb_total_bounced_last_24h = sa.Column(sa.Float, nullable=True)
nb_verified_custom_domain = sa.Column(sa.Float, nullable=True)
nb_subdomain = sa.Column(sa.Float, nullable=True)
nb_directory = sa.Column(sa.Float, nullable=True)
nb_deleted_directory = sa.Column(sa.Float, nullable=True)
nb_deleted_subdomain = sa.Column(sa.Float, nullable=True)
nb_app = sa.Column(sa.Float, nullable=True)
The provided code snippet includes necessary dependencies for implementing the `stats` function. Write a Python function `def stats()` to solve the following problem:
send admin stats everyday
Here is the function:
def stats():
"""send admin stats everyday"""
if not config.ADMIN_EMAIL:
LOG.w("ADMIN_EMAIL not set, nothing to do")
return
stats_today = compute_metric2()
stats_yesterday = (
Metric2.filter(Metric2.date < stats_today.date)
.order_by(Metric2.date.desc())
.first()
)
today = arrow.now().format()
growth_stats = f"""
Growth Stats for {today}
nb_user: {stats_today.nb_user} - {increase_percent(stats_yesterday.nb_user, stats_today.nb_user)}
nb_proton_user: {stats_today.nb_proton_user} - {increase_percent(stats_yesterday.nb_proton_user, stats_today.nb_proton_user)}
nb_premium: {stats_today.nb_premium} - {increase_percent(stats_yesterday.nb_premium, stats_today.nb_premium)}
nb_cancelled_premium: {stats_today.nb_cancelled_premium} - {increase_percent(stats_yesterday.nb_cancelled_premium, stats_today.nb_cancelled_premium)}
nb_apple_premium: {stats_today.nb_apple_premium} - {increase_percent(stats_yesterday.nb_apple_premium, stats_today.nb_apple_premium)}
nb_manual_premium: {stats_today.nb_manual_premium} - {increase_percent(stats_yesterday.nb_manual_premium, stats_today.nb_manual_premium)}
nb_coinbase_premium: {stats_today.nb_coinbase_premium} - {increase_percent(stats_yesterday.nb_coinbase_premium, stats_today.nb_coinbase_premium)}
nb_proton_premium: {stats_today.nb_proton_premium} - {increase_percent(stats_yesterday.nb_proton_premium, stats_today.nb_proton_premium)}
nb_alias: {stats_today.nb_alias} - {increase_percent(stats_yesterday.nb_alias, stats_today.nb_alias)}
nb_forward_last_24h: {stats_today.nb_forward_last_24h} - {increase_percent(stats_yesterday.nb_forward_last_24h, stats_today.nb_forward_last_24h)}
nb_reply_last_24h: {stats_today.nb_reply_last_24h} - {increase_percent(stats_yesterday.nb_reply_last_24h, stats_today.nb_reply_last_24h)}
nb_block_last_24h: {stats_today.nb_block_last_24h} - {increase_percent(stats_yesterday.nb_block_last_24h, stats_today.nb_block_last_24h)}
nb_bounced_last_24h: {stats_today.nb_bounced_last_24h} - {increase_percent(stats_yesterday.nb_bounced_last_24h, stats_today.nb_bounced_last_24h)}
nb_custom_domain: {stats_today.nb_verified_custom_domain} - {increase_percent(stats_yesterday.nb_verified_custom_domain, stats_today.nb_verified_custom_domain)}
nb_subdomain: {stats_today.nb_subdomain} - {increase_percent(stats_yesterday.nb_subdomain, stats_today.nb_subdomain)}
nb_directory: {stats_today.nb_directory} - {increase_percent(stats_yesterday.nb_directory, stats_today.nb_directory)}
nb_deleted_directory: {stats_today.nb_deleted_directory} - {increase_percent(stats_yesterday.nb_deleted_directory, stats_today.nb_deleted_directory)}
nb_deleted_subdomain: {stats_today.nb_deleted_subdomain} - {increase_percent(stats_yesterday.nb_deleted_subdomain, stats_today.nb_deleted_subdomain)}
nb_app: {stats_today.nb_app} - {increase_percent(stats_yesterday.nb_app, stats_today.nb_app)}
nb_referred_user: {stats_today.nb_referred_user} - {increase_percent(stats_yesterday.nb_referred_user, stats_today.nb_referred_user)}
nb_referred_user_upgrade: {stats_today.nb_referred_user_paid} - {increase_percent(stats_yesterday.nb_referred_user_paid, stats_today.nb_referred_user_paid)}
"""
LOG.d("growth_stats email: %s", growth_stats)
send_email(
config.ADMIN_EMAIL,
subject=f"SimpleLogin Growth Stats for {today}",
plaintext=growth_stats,
retries=3,
)
monitoring_report = f"""
Monitoring Stats for {today}
nb_alias: {stats_today.nb_alias} - {increase_percent(stats_yesterday.nb_alias, stats_today.nb_alias)}
nb_forward_last_24h: {stats_today.nb_forward_last_24h} - {increase_percent(stats_yesterday.nb_forward_last_24h, stats_today.nb_forward_last_24h)}
nb_reply_last_24h: {stats_today.nb_reply_last_24h} - {increase_percent(stats_yesterday.nb_reply_last_24h, stats_today.nb_reply_last_24h)}
nb_block_last_24h: {stats_today.nb_block_last_24h} - {increase_percent(stats_yesterday.nb_block_last_24h, stats_today.nb_block_last_24h)}
nb_bounced_last_24h: {stats_today.nb_bounced_last_24h} - {increase_percent(stats_yesterday.nb_bounced_last_24h, stats_today.nb_bounced_last_24h)}
nb_total_bounced_last_24h: {stats_today.nb_total_bounced_last_24h} - {increase_percent(stats_yesterday.nb_total_bounced_last_24h, stats_today.nb_total_bounced_last_24h)}
"""
monitoring_report += "\n====================================\n"
monitoring_report += """
# Account bounce report:
"""
for email, bounces in bounce_report():
monitoring_report += f"{email}: {bounces}\n"
monitoring_report += """\n
# Alias creation report:
"""
for email, nb_alias, date in alias_creation_report():
monitoring_report += f"{email}, {date}: {nb_alias}\n"
monitoring_report += """\n
# Full bounce detail report:
"""
monitoring_report += all_bounce_report()
LOG.d("monitoring_report email: %s", monitoring_report)
send_email(
config.MONITORING_EMAIL,
subject=f"SimpleLogin Monitoring Report for {today}",
plaintext=monitoring_report,
retries=3,
) | send admin stats everyday |
180,560 | import argparse
import asyncio
import urllib.parse
from typing import List, Tuple
import arrow
import requests
from sqlalchemy import func, desc, or_, and_
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.orm import joinedload
from sqlalchemy.orm.exc import ObjectDeletedError
from sqlalchemy.sql import Insert, text
from app import s3, config
from app.alias_utils import nb_email_log_for_mailbox
from app.api.views.apple import verify_receipt
from app.db import Session
from app.dns_utils import get_mx_domains, is_mx_equivalent
from app.email_utils import (
send_email,
send_trial_end_soon_email,
render,
email_can_be_used_as_mailbox,
send_email_with_rate_control,
get_email_domain_part,
)
from app.email_validation import is_valid_email, normalize_reply_email
from app.errors import ProtonPartnerNotSetUp
from app.log import LOG
from app.mail_sender import load_unsent_mails_from_fs_and_resend
from app.models import (
Subscription,
User,
Alias,
EmailLog,
CustomDomain,
Client,
ManualSubscription,
RefusedEmail,
AppleSubscription,
Mailbox,
Monitoring,
Contact,
CoinbaseSubscription,
TransactionalEmail,
Bounce,
Metric2,
SLDomain,
DeletedAlias,
DomainDeletedAlias,
Hibp,
HibpNotifiedAlias,
Directory,
DeletedDirectory,
DeletedSubdomain,
PartnerSubscription,
PartnerUser,
ApiToCookieToken,
)
from app.pgp_utils import load_public_key_and_check, PGPException
from app.proton.utils import get_proton_partner
from app.utils import sanitize_email
from server import create_light_app
from tasks.cleanup_old_imports import cleanup_old_imports
from tasks.cleanup_old_jobs import cleanup_old_jobs
from tasks.cleanup_old_notifications import cleanup_old_notifications
def migrate_domain_trash():
"""Move aliases from global trash to domain trash if applicable"""
# ignore duplicate when insert
# copied from https://github.com/sqlalchemy/sqlalchemy/issues/5374
def postgresql_on_conflict_do_nothing(insert, compiler, **kw):
statement = compiler.visit_insert(insert, **kw)
# IF we have a "RETURNING" clause, we must insert before it
returning_position = statement.find("RETURNING")
if returning_position >= 0:
return (
statement[:returning_position]
+ "ON CONFLICT DO NOTHING "
+ statement[returning_position:]
)
else:
return statement + " ON CONFLICT DO NOTHING"
sl_domains = [sl.domain for sl in SLDomain.all()]
count = 0
domain_deleted_aliases = []
deleted_alias_ids = []
for deleted_alias in DeletedAlias.yield_per_query():
if count % 1000 == 0:
LOG.d("process %s", count)
count += 1
alias_domain = get_email_domain_part(deleted_alias.email)
if alias_domain not in sl_domains:
custom_domain = CustomDomain.get_by(domain=alias_domain)
if custom_domain:
LOG.w("move %s to domain %s trash", deleted_alias, custom_domain)
domain_deleted_aliases.append(
DomainDeletedAlias(
user_id=custom_domain.user_id,
email=deleted_alias.email,
domain_id=custom_domain.id,
created_at=deleted_alias.created_at,
)
)
deleted_alias_ids.append(deleted_alias.id)
LOG.d("create %s DomainDeletedAlias", len(domain_deleted_aliases))
Session.bulk_save_objects(domain_deleted_aliases)
LOG.d("delete %s DeletedAlias", len(deleted_alias_ids))
DeletedAlias.filter(DeletedAlias.id.in_(deleted_alias_ids)).delete(
synchronize_session=False
)
Session.commit()
def set_custom_domain_for_alias():
"""Go through all aliases and make sure custom_domain is correctly set"""
sl_domains = [sl_domain.domain for sl_domain in SLDomain.all()]
for alias in Alias.yield_per_query().filter(Alias.custom_domain_id.is_(None)):
if (
not any(alias.email.endswith(f"@{sl_domain}") for sl_domain in sl_domains)
and not alias.custom_domain_id
):
alias_domain = get_email_domain_part(alias.email)
custom_domain = CustomDomain.get_by(domain=alias_domain)
if custom_domain:
LOG.e("set %s for %s", custom_domain, alias)
alias.custom_domain_id = custom_domain.id
else: # phantom domain
LOG.d("phantom domain %s %s %s", alias.user, alias, alias.enabled)
Session.commit()
def sanitize_alias_address_name():
count = 0
# using Alias.all() will take all the memory
for alias in Alias.yield_per_query():
if count % 1000 == 0:
LOG.d("process %s", count)
count += 1
if sanitize_email(alias.email) != alias.email:
LOG.e("Alias %s email not sanitized", alias)
if alias.name and "\n" in alias.name:
alias.name = alias.name.replace("\n", "")
Session.commit()
LOG.e("Alias %s name contains linebreak %s", alias, alias.name)
def check_mailbox_valid_domain():
"""detect if there's mailbox that's using an invalid domain"""
mailbox_ids = (
Session.query(Mailbox.id)
.filter(Mailbox.verified.is_(True), Mailbox.disabled.is_(False))
.all()
)
mailbox_ids = [e[0] for e in mailbox_ids]
# iterate over id instead of mailbox directly
# as a mailbox can be deleted in the meantime
for mailbox_id in mailbox_ids:
mailbox = Mailbox.get(mailbox_id)
# a mailbox has been deleted
if not mailbox:
continue
if email_can_be_used_as_mailbox(mailbox.email):
LOG.d("Mailbox %s valid", mailbox)
mailbox.nb_failed_checks = 0
else:
mailbox.nb_failed_checks += 1
nb_email_log = nb_email_log_for_mailbox(mailbox)
LOG.w(
"issue with mailbox %s domain. #alias %s, nb email log %s",
mailbox,
mailbox.nb_alias(),
nb_email_log,
)
# send a warning
if mailbox.nb_failed_checks == 5:
if mailbox.user.email != mailbox.email:
send_email(
mailbox.user.email,
f"Mailbox {mailbox.email} is disabled",
render(
"transactional/disable-mailbox-warning.txt.jinja2",
mailbox=mailbox,
),
render(
"transactional/disable-mailbox-warning.html",
mailbox=mailbox,
),
retries=3,
)
# alert if too much fail and nb_email_log > 100
if mailbox.nb_failed_checks > 10 and nb_email_log > 100:
mailbox.disabled = True
if mailbox.user.email != mailbox.email:
send_email(
mailbox.user.email,
f"Mailbox {mailbox.email} is disabled",
render(
"transactional/disable-mailbox.txt.jinja2", mailbox=mailbox
),
render("transactional/disable-mailbox.html", mailbox=mailbox),
retries=3,
)
Session.commit()
def check_mailbox_valid_pgp_keys():
mailbox_ids = (
Session.query(Mailbox.id)
.filter(
Mailbox.verified.is_(True),
Mailbox.pgp_public_key.isnot(None),
Mailbox.disable_pgp.is_(False),
)
.all()
)
mailbox_ids = [e[0] for e in mailbox_ids]
# iterate over id instead of mailbox directly
# as a mailbox can be deleted in the meantime
for mailbox_id in mailbox_ids:
mailbox = Mailbox.get(mailbox_id)
# a mailbox has been deleted
if not mailbox:
LOG.d(f"Mailbox {mailbox_id} not found")
continue
LOG.d(f"Checking PGP key for {mailbox}")
try:
load_public_key_and_check(mailbox.pgp_public_key)
except PGPException:
LOG.i(f"{mailbox} PGP key invalid")
send_email(
mailbox.user.email,
f"Mailbox {mailbox.email}'s PGP Key is invalid",
render(
"transactional/invalid-mailbox-pgp-key.txt.jinja2",
mailbox=mailbox,
),
retries=3,
)
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
def is_valid_email(email_address: str) -> bool:
"""
Used to check whether an email address is valid
NOT run MX check.
NOT allow unicode.
"""
try:
validate_email(email_address, check_deliverability=False, allow_smtputf8=False)
return True
except EmailNotValidError:
return False
def normalize_reply_email(reply_email: str) -> str:
"""Handle the case where reply email contains *strange* char that was wrongly generated in the past"""
if not reply_email.isascii():
reply_email = convert_to_id(reply_email)
ret = []
# drop all control characters like shift, separator, etc
for c in reply_email:
if c not in _ALLOWED_CHARS:
ret.append("_")
else:
ret.append(c)
return "".join(ret)
LOG = _get_logger("SL")
class User(Base, ModelMixin, UserMixin, PasswordOracle):
__tablename__ = "users"
FLAG_FREE_DISABLE_CREATE_ALIAS = 1 << 0
FLAG_CREATED_FROM_PARTNER = 1 << 1
FLAG_FREE_OLD_ALIAS_LIMIT = 1 << 2
email = sa.Column(sa.String(256), unique=True, nullable=False)
name = sa.Column(sa.String(128), nullable=True)
is_admin = sa.Column(sa.Boolean, nullable=False, default=False)
alias_generator = sa.Column(
sa.Integer,
nullable=False,
default=AliasGeneratorEnum.word.value,
server_default=str(AliasGeneratorEnum.word.value),
)
notification = sa.Column(
sa.Boolean, default=True, nullable=False, server_default="1"
)
activated = sa.Column(sa.Boolean, default=False, nullable=False, index=True)
# an account can be disabled if having harmful behavior
disabled = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0")
profile_picture_id = sa.Column(sa.ForeignKey(File.id), nullable=True)
otp_secret = sa.Column(sa.String(16), nullable=True)
enable_otp = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
last_otp = sa.Column(sa.String(12), nullable=True, default=False)
# Fields for WebAuthn
fido_uuid = sa.Column(sa.String(), nullable=True, unique=True)
# the default domain that's used when user creates a new random alias
# default_alias_custom_domain_id XOR default_alias_public_domain_id
default_alias_custom_domain_id = sa.Column(
sa.ForeignKey("custom_domain.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
default_alias_public_domain_id = sa.Column(
sa.ForeignKey("public_domain.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
# some users could have lifetime premium
lifetime = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0")
paid_lifetime = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
lifetime_coupon_id = sa.Column(
sa.ForeignKey("lifetime_coupon.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
# user can use all premium features until this date
trial_end = sa.Column(
ArrowType, default=lambda: arrow.now().shift(days=7, hours=1), nullable=True
)
# the mailbox used when create random alias
# this field is nullable but in practice, it's always set
# it cannot be set to non-nullable though
# as this will create foreign key cycle between User and Mailbox
default_mailbox_id = sa.Column(
sa.ForeignKey("mailbox.id"), nullable=True, default=None
)
profile_picture = orm.relationship(File, foreign_keys=[profile_picture_id])
# Specify the format for sender address
# for the full list, see SenderFormatEnum
sender_format = sa.Column(
sa.Integer, default="0", nullable=False, server_default="0"
)
# to know whether user has explicitly chosen a sender format as opposed to those who use the default ones.
# users who haven't chosen a sender format and are using 1 or 3 format, their sender format will be set to 0
sender_format_updated_at = sa.Column(ArrowType, default=None)
replace_reverse_alias = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
referral_id = sa.Column(
sa.ForeignKey("referral.id", ondelete="SET NULL"),
nullable=True,
default=None,
index=True,
)
referral = orm.relationship("Referral", foreign_keys=[referral_id])
# whether intro has been shown to user
intro_shown = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
default_mailbox = orm.relationship("Mailbox", foreign_keys=[default_mailbox_id])
# user can set a more strict max_spam score to block spams more aggressively
max_spam_score = sa.Column(sa.Integer, nullable=True)
# newsletter is sent to this address
newsletter_alias_id = sa.Column(
sa.ForeignKey("alias.id", ondelete="SET NULL"),
nullable=True,
default=None,
index=True,
)
# whether to include the sender address in reverse-alias
include_sender_in_reverse_alias = sa.Column(
sa.Boolean, default=True, nullable=False, server_default="0"
)
# whether to use random string or random word as suffix
# Random word from dictionary file -> 0
# Completely random string -> 1
random_alias_suffix = sa.Column(
sa.Integer,
nullable=False,
default=AliasSuffixEnum.word.value,
server_default=str(AliasSuffixEnum.random_string.value),
)
# always expand the alias info, i.e. without needing to press "More"
expand_alias_info = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# ignore emails send from a mailbox to its alias. This can happen when replying all to a forwarded email
# can automatically re-includes the alias
ignore_loop_email = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# used for flask-login as an "alternative token"
# cf https://flask-login.readthedocs.io/en/latest/#alternative-tokens
alternative_id = sa.Column(sa.String(128), unique=True, nullable=True)
# by default, when an alias is automatically created, a note like "Created with ...." is created
# If this field is True, the note won't be created.
disable_automatic_alias_note = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# By default, the one-click unsubscribe disable the alias
# If set to true, it will block the sender instead
one_click_unsubscribe_block_sender = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# automatically include the website name when user creates an alias via the SimpleLogin icon in the email field
include_website_in_one_click_alias = sa.Column(
sa.Boolean,
# new user will have this option turned on automatically
default=True,
nullable=False,
# old user will have this option turned off
server_default="0",
)
_directory_quota = sa.Column(
"directory_quota", sa.Integer, default=50, nullable=False, server_default="50"
)
_subdomain_quota = sa.Column(
"subdomain_quota", sa.Integer, default=5, nullable=False, server_default="5"
)
# user can use import to import too many aliases
disable_import = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# user can use the phone feature
can_use_phone = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# in minutes
phone_quota = sa.Column(sa.Integer, nullable=True)
# Status code to return if is blocked
block_behaviour = sa.Column(
sa.Enum(BlockBehaviourEnum),
nullable=False,
server_default=BlockBehaviourEnum.return_2xx.name,
)
include_header_email_header = sa.Column(
sa.Boolean, default=True, nullable=False, server_default="1"
)
# bitwise flags. Allow for future expansion
flags = sa.Column(
sa.BigInteger,
default=FLAG_FREE_DISABLE_CREATE_ALIAS,
server_default="0",
nullable=False,
)
# Keep original unsub behaviour
unsub_behaviour = sa.Column(
IntEnumType(UnsubscribeBehaviourEnum),
default=UnsubscribeBehaviourEnum.PreserveOriginal,
server_default=str(UnsubscribeBehaviourEnum.DisableAlias.value),
nullable=False,
)
# Trigger hard deletion of the account at this time
delete_on = sa.Column(ArrowType, default=None)
__table_args__ = (
sa.Index(
"ix_users_activated_trial_end_lifetime", activated, trial_end, lifetime
),
sa.Index("ix_users_delete_on", delete_on),
)
def directory_quota(self):
return min(
self._directory_quota,
config.MAX_NB_DIRECTORY - Directory.filter_by(user_id=self.id).count(),
)
def subdomain_quota(self):
return min(
self._subdomain_quota,
config.MAX_NB_SUBDOMAIN
- CustomDomain.filter_by(user_id=self.id, is_sl_subdomain=True).count(),
)
def created_by_partner(self):
return User.FLAG_CREATED_FROM_PARTNER == (
self.flags & User.FLAG_CREATED_FROM_PARTNER
)
def subdomain_is_available():
return SLDomain.filter_by(can_use_subdomain=True).count() > 0
# implement flask-login "alternative token"
def get_id(self):
if self.alternative_id:
return self.alternative_id
else:
return str(self.id)
def create(cls, email, name="", password=None, from_partner=False, **kwargs):
email = sanitize_email(email)
user: User = super(User, cls).create(email=email, name=name[:100], **kwargs)
if password:
user.set_password(password)
Session.flush()
mb = Mailbox.create(user_id=user.id, email=user.email, verified=True)
Session.flush()
user.default_mailbox_id = mb.id
# generate an alternative_id if needed
if "alternative_id" not in kwargs:
user.alternative_id = str(uuid.uuid4())
# If the user is created from partner, do not notify
# nor give a trial
if from_partner:
user.flags = User.FLAG_CREATED_FROM_PARTNER
user.notification = False
user.trial_end = None
Job.create(
name=config.JOB_SEND_PROTON_WELCOME_1,
payload={"user_id": user.id},
run_at=arrow.now(),
)
Session.flush()
return user
# create a first alias mail to show user how to use when they login
alias = Alias.create_new(
user,
prefix="simplelogin-newsletter",
mailbox_id=mb.id,
note="This is your first alias. It's used to receive SimpleLogin communications "
"like new features announcements, newsletters.",
)
Session.flush()
user.newsletter_alias_id = alias.id
Session.flush()
if config.DISABLE_ONBOARDING:
LOG.d("Disable onboarding emails")
return user
# Schedule onboarding emails
Job.create(
name=config.JOB_ONBOARDING_1,
payload={"user_id": user.id},
run_at=arrow.now().shift(days=1),
)
Job.create(
name=config.JOB_ONBOARDING_2,
payload={"user_id": user.id},
run_at=arrow.now().shift(days=2),
)
Job.create(
name=config.JOB_ONBOARDING_4,
payload={"user_id": user.id},
run_at=arrow.now().shift(days=3),
)
Session.flush()
return user
def get_active_subscription(
self, include_partner_subscription: bool = True
) -> Optional[
Union[
Subscription
| AppleSubscription
| ManualSubscription
| CoinbaseSubscription
| PartnerSubscription
]
]:
sub: Subscription = self.get_paddle_subscription()
if sub:
return sub
apple_sub: AppleSubscription = AppleSubscription.get_by(user_id=self.id)
if apple_sub and apple_sub.is_valid():
return apple_sub
manual_sub: ManualSubscription = ManualSubscription.get_by(user_id=self.id)
if manual_sub and manual_sub.is_active():
return manual_sub
coinbase_subscription: CoinbaseSubscription = CoinbaseSubscription.get_by(
user_id=self.id
)
if coinbase_subscription and coinbase_subscription.is_active():
return coinbase_subscription
if include_partner_subscription:
partner_sub: PartnerSubscription = PartnerSubscription.find_by_user_id(
self.id
)
if partner_sub and partner_sub.is_active():
return partner_sub
return None
def get_active_subscription_end(
self, include_partner_subscription: bool = True
) -> Optional[arrow.Arrow]:
sub = self.get_active_subscription(
include_partner_subscription=include_partner_subscription
)
if isinstance(sub, Subscription):
return arrow.get(sub.next_bill_date)
if isinstance(sub, AppleSubscription):
return sub.expires_date
if isinstance(sub, ManualSubscription):
return sub.end_at
if isinstance(sub, CoinbaseSubscription):
return sub.end_at
return None
# region Billing
def lifetime_or_active_subscription(
self, include_partner_subscription: bool = True
) -> bool:
"""True if user has lifetime licence or active subscription"""
if self.lifetime:
return True
return self.get_active_subscription(include_partner_subscription) is not None
def is_paid(self) -> bool:
"""same as _lifetime_or_active_subscription but not include free manual subscription"""
sub = self.get_active_subscription()
if sub is None:
return False
if isinstance(sub, ManualSubscription) and sub.is_giveaway:
return False
return True
def is_active(self) -> bool:
if self.delete_on is None:
return True
return self.delete_on < arrow.now()
def in_trial(self):
"""return True if user does not have lifetime licence or an active subscription AND is in trial period"""
if self.lifetime_or_active_subscription():
return False
if self.trial_end and arrow.now() < self.trial_end:
return True
return False
def should_show_upgrade_button(self):
if self.lifetime_or_active_subscription():
return False
return True
def is_premium(self, include_partner_subscription: bool = True) -> bool:
"""
user is premium if they:
- have a lifetime deal or
- in trial period or
- active subscription
"""
if self.lifetime_or_active_subscription(include_partner_subscription):
return True
if self.trial_end and arrow.now() < self.trial_end:
return True
return False
def upgrade_channel(self) -> str:
"""Used on admin dashboard"""
# user can have multiple subscription channel
channels = []
if self.lifetime:
channels.append("Lifetime")
sub: Subscription = self.get_paddle_subscription()
if sub:
if sub.cancelled:
channels.append(
f"""Cancelled Paddle Subscription <a href="https://vendors.paddle.com/subscriptions/customers/manage/{sub.subscription_id}">{sub.subscription_id}</a> {sub.plan_name()} ends at {sub.next_bill_date}"""
)
else:
channels.append(
f"""Active Paddle Subscription <a href="https://vendors.paddle.com/subscriptions/customers/manage/{sub.subscription_id}">{sub.subscription_id}</a> {sub.plan_name()}, renews at {sub.next_bill_date}"""
)
apple_sub: AppleSubscription = AppleSubscription.get_by(user_id=self.id)
if apple_sub and apple_sub.is_valid():
channels.append(f"Apple Subscription {apple_sub.expires_date.humanize()}")
manual_sub: ManualSubscription = ManualSubscription.get_by(user_id=self.id)
if manual_sub and manual_sub.is_active():
mode = "Giveaway" if manual_sub.is_giveaway else "Paid"
channels.append(
f"Manual Subscription {manual_sub.comment} {mode} {manual_sub.end_at.humanize()}"
)
coinbase_subscription: CoinbaseSubscription = CoinbaseSubscription.get_by(
user_id=self.id
)
if coinbase_subscription and coinbase_subscription.is_active():
channels.append(
f"Coinbase Subscription ends {coinbase_subscription.end_at.humanize()}"
)
r = (
Session.query(PartnerSubscription, PartnerUser, Partner)
.filter(
PartnerSubscription.partner_user_id == PartnerUser.id,
PartnerUser.user_id == self.id,
Partner.id == PartnerUser.partner_id,
)
.first()
)
if r and r[0].is_active():
channels.append(
f"Subscription via {r[2].name} partner , ends {r[0].end_at.humanize()}"
)
return ".\n".join(channels)
# endregion
def max_alias_for_free_account(self) -> int:
if (
self.FLAG_FREE_OLD_ALIAS_LIMIT
== self.flags & self.FLAG_FREE_OLD_ALIAS_LIMIT
):
return config.MAX_NB_EMAIL_OLD_FREE_PLAN
else:
return config.MAX_NB_EMAIL_FREE_PLAN
def can_create_new_alias(self) -> bool:
"""
Whether user can create a new alias. User can't create a new alias if
- has more than 15 aliases in the free plan, *even in the free trial*
"""
if not self.is_active():
return False
if self.disabled:
return False
if self.lifetime_or_active_subscription():
return True
else:
return (
Alias.filter_by(user_id=self.id).count()
< self.max_alias_for_free_account()
)
def can_send_or_receive(self) -> bool:
if self.disabled:
LOG.i(f"User {self} is disabled. Cannot receive or send emails")
return False
if self.delete_on is not None:
LOG.i(
f"User {self} is scheduled to be deleted. Cannot receive or send emails"
)
return False
return True
def profile_picture_url(self):
if self.profile_picture_id:
return self.profile_picture.get_url()
else:
return url_for("static", filename="default-avatar.png")
def suggested_emails(self, website_name) -> (str, [str]):
"""return suggested email and other email choices"""
website_name = convert_to_id(website_name)
all_aliases = [
ge.email for ge in Alias.filter_by(user_id=self.id, enabled=True)
]
if self.can_create_new_alias():
suggested_alias = Alias.create_new(self, prefix=website_name).email
else:
# pick an email from the list of gen emails
suggested_alias = random.choice(all_aliases)
return (
suggested_alias,
list(set(all_aliases).difference({suggested_alias})),
)
def suggested_names(self) -> (str, [str]):
"""return suggested name and other name choices"""
other_name = convert_to_id(self.name)
return self.name, [other_name, "Anonymous", "whoami"]
def get_name_initial(self) -> str:
if not self.name:
return ""
names = self.name.split(" ")
return "".join([n[0].upper() for n in names if n])
def get_paddle_subscription(self) -> Optional["Subscription"]:
"""return *active* Paddle subscription
Return None if the subscription is already expired
TODO: support user unsubscribe and re-subscribe
"""
sub = Subscription.get_by(user_id=self.id)
if sub:
# grace period is 14 days
# sub is active until the next billing_date + PADDLE_SUBSCRIPTION_GRACE_DAYS
if (
sub.next_bill_date
>= arrow.now().shift(days=-PADDLE_SUBSCRIPTION_GRACE_DAYS).date()
):
return sub
# past subscription, user is considered not having a subscription = free plan
else:
return None
else:
return sub
def verified_custom_domains(self) -> List["CustomDomain"]:
return (
CustomDomain.filter_by(user_id=self.id, ownership_verified=True)
.order_by(CustomDomain.domain.asc())
.all()
)
def mailboxes(self) -> List["Mailbox"]:
"""list of mailbox that user own"""
mailboxes = []
for mailbox in Mailbox.filter_by(user_id=self.id, verified=True):
mailboxes.append(mailbox)
return mailboxes
def nb_directory(self):
return Directory.filter_by(user_id=self.id).count()
def has_custom_domain(self):
return CustomDomain.filter_by(user_id=self.id, verified=True).count() > 0
def custom_domains(self):
return CustomDomain.filter_by(user_id=self.id, verified=True).all()
def available_domains_for_random_alias(
self, alias_options: Optional[AliasOptions] = None
) -> List[Tuple[bool, str]]:
"""Return available domains for user to create random aliases
Each result record contains:
- whether the domain belongs to SimpleLogin
- the domain
"""
res = []
for domain in self.available_sl_domains(alias_options=alias_options):
res.append((True, domain))
for custom_domain in self.verified_custom_domains():
res.append((False, custom_domain.domain))
return res
def default_random_alias_domain(self) -> str:
"""return the domain used for the random alias"""
if self.default_alias_custom_domain_id:
custom_domain = CustomDomain.get(self.default_alias_custom_domain_id)
# sanity check
if (
not custom_domain
or not custom_domain.verified
or custom_domain.user_id != self.id
):
LOG.w("Problem with %s default random alias domain", self)
return config.FIRST_ALIAS_DOMAIN
return custom_domain.domain
if self.default_alias_public_domain_id:
sl_domain = SLDomain.get(self.default_alias_public_domain_id)
# sanity check
if not sl_domain:
LOG.e("Problem with %s public random alias domain", self)
return config.FIRST_ALIAS_DOMAIN
if sl_domain.premium_only and not self.is_premium():
LOG.w(
"%s is not premium and cannot use %s. Reset default random alias domain setting",
self,
sl_domain,
)
self.default_alias_custom_domain_id = None
self.default_alias_public_domain_id = None
Session.commit()
return config.FIRST_ALIAS_DOMAIN
return sl_domain.domain
return config.FIRST_ALIAS_DOMAIN
def fido_enabled(self) -> bool:
if self.fido_uuid is not None:
return True
return False
def two_factor_authentication_enabled(self) -> bool:
return self.enable_otp or self.fido_enabled()
def get_communication_email(self) -> (Optional[str], str, bool):
"""
Return
- the email that user uses to receive email communication. None if user unsubscribes from newsletter
- the unsubscribe URL
- whether the unsubscribe method is via sending email (mailto:) or Http POST
"""
if self.notification and self.activated and not self.disabled:
if self.newsletter_alias_id:
alias = Alias.get(self.newsletter_alias_id)
if alias.enabled:
unsub = UnsubscribeEncoder.encode(
UnsubscribeAction.DisableAlias, alias.id
)
return alias.email, unsub.link, unsub.via_email
# alias disabled -> user doesn't want to receive newsletter
else:
return None, "", False
else:
# do not handle http POST unsubscribe
if config.UNSUBSCRIBER:
# use * as suffix instead of = as for alias unsubscribe
return (
self.email,
UnsubscribeEncoder.encode_mailto(
UnsubscribeAction.UnsubscribeNewsletter, self.id
),
True,
)
return None, "", False
def available_sl_domains(
self, alias_options: Optional[AliasOptions] = None
) -> [str]:
"""
Return all SimpleLogin domains that user can use when creating a new alias, including:
- SimpleLogin public domains, available for all users (ALIAS_DOMAIN)
- SimpleLogin premium domains, only available for Premium accounts (PREMIUM_ALIAS_DOMAIN)
"""
return [
sl_domain.domain
for sl_domain in self.get_sl_domains(alias_options=alias_options)
]
def get_sl_domains(
self, alias_options: Optional[AliasOptions] = None
) -> list["SLDomain"]:
if alias_options is None:
alias_options = AliasOptions()
top_conds = [SLDomain.hidden == False] # noqa: E712
or_conds = [] # noqa:E711
if self.default_alias_public_domain_id is not None:
default_domain_conds = [SLDomain.id == self.default_alias_public_domain_id]
if not self.is_premium():
default_domain_conds.append(
SLDomain.premium_only == False # noqa: E712
)
or_conds.append(and_(*default_domain_conds).self_group())
if alias_options.show_partner_domains is not None:
partner_user = PartnerUser.filter_by(
user_id=self.id, partner_id=alias_options.show_partner_domains.id
).first()
if partner_user is not None:
partner_domain_cond = [SLDomain.partner_id == partner_user.partner_id]
if alias_options.show_partner_premium is None:
alias_options.show_partner_premium = self.is_premium()
if not alias_options.show_partner_premium:
partner_domain_cond.append(
SLDomain.premium_only == False # noqa: E712
)
or_conds.append(and_(*partner_domain_cond).self_group())
if alias_options.show_sl_domains:
sl_conds = [SLDomain.partner_id == None] # noqa: E711
if not self.is_premium():
sl_conds.append(SLDomain.premium_only == False) # noqa: E712
or_conds.append(and_(*sl_conds).self_group())
top_conds.append(or_(*or_conds))
query = Session.query(SLDomain).filter(*top_conds).order_by(SLDomain.order)
return query.all()
def available_alias_domains(
self, alias_options: Optional[AliasOptions] = None
) -> [str]:
"""return all domains that user can use when creating a new alias, including:
- SimpleLogin public domains, available for all users (ALIAS_DOMAIN)
- SimpleLogin premium domains, only available for Premium accounts (PREMIUM_ALIAS_DOMAIN)
- Verified custom domains
"""
domains = self.available_sl_domains(alias_options=alias_options)
for custom_domain in self.verified_custom_domains():
domains.append(custom_domain.domain)
# can have duplicate where a "root" user has a domain that's also listed in SL domains
return list(set(domains))
def should_show_app_page(self) -> bool:
"""whether to show the app page"""
return (
# when user has used the "Sign in with SL" button before
ClientUser.filter(ClientUser.user_id == self.id).count()
# or when user has created an app
+ Client.filter(Client.user_id == self.id).count()
> 0
)
def get_random_alias_suffix(self, custom_domain: Optional["CustomDomain"] = None):
"""Get random suffix for an alias based on user's preference.
Use a shorter suffix in case of custom domain
Returns:
str: the random suffix generated
"""
if self.random_alias_suffix == AliasSuffixEnum.random_string.value:
return random_string(config.ALIAS_RANDOM_SUFFIX_LENGTH, include_digits=True)
if custom_domain is None:
return random_words(1, 3)
return random_words(1)
def can_create_contacts(self) -> bool:
if self.is_premium():
return True
if self.flags & User.FLAG_FREE_DISABLE_CREATE_ALIAS == 0:
return True
return not config.DISABLE_CREATE_CONTACTS_FOR_FREE_USERS
def __repr__(self):
return f"<User {self.id} {self.name} {self.email}>"
class Contact(Base, ModelMixin):
"""
Store configuration of sender (website-email) and alias.
"""
MAX_NAME_LENGTH = 512
__tablename__ = "contact"
__table_args__ = (
sa.UniqueConstraint("alias_id", "website_email", name="uq_contact"),
)
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, index=True
)
alias_id = sa.Column(
sa.ForeignKey(Alias.id, ondelete="cascade"), nullable=False, index=True
)
name = sa.Column(
sa.String(512), nullable=True, default=None, server_default=text("NULL")
)
website_email = sa.Column(sa.String(512), nullable=False)
# the email from header, e.g. AB CD <ab@cd.com>
# nullable as this field is added after website_email
website_from = sa.Column(sa.String(1024), nullable=True)
# when user clicks on "reply", they will reply to this address.
# This address allows to hide user personal email
# this reply email is created every time a website sends an email to user
# it used to have the prefix "reply+" or "ra+"
reply_email = sa.Column(sa.String(512), nullable=False, index=True)
# whether a contact is created via CC
is_cc = sa.Column(sa.Boolean, nullable=False, default=False, server_default="0")
pgp_public_key = sa.Column(sa.Text, nullable=True)
pgp_finger_print = sa.Column(sa.String(512), nullable=True, index=True)
alias = orm.relationship(Alias, backref="contacts")
user = orm.relationship(User)
# the latest reply sent to this contact
latest_reply: Optional[Arrow] = None
# to investigate why the website_email is sometimes not correctly parsed
# the envelope mail_from
mail_from = sa.Column(sa.Text, nullable=True, default=None)
# a contact can have an empty email address, in this case it can't receive emails
invalid_email = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# emails sent from this contact will be blocked
block_forward = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# whether contact is created automatically during the forward phase
automatic_created = sa.Column(sa.Boolean, nullable=True, default=False)
def email(self):
return self.website_email
def create(cls, **kw):
commit = kw.pop("commit", False)
flush = kw.pop("flush", False)
new_contact = cls(**kw)
website_email = kw["website_email"]
# make sure email is lowercase and doesn't have any whitespace
website_email = sanitize_email(website_email)
# make sure contact.website_email isn't a reverse alias
if website_email != config.NOREPLY:
orig_contact = Contact.get_by(reply_email=website_email)
if orig_contact:
raise CannotCreateContactForReverseAlias(str(orig_contact))
Session.add(new_contact)
if commit:
Session.commit()
if flush:
Session.flush()
return new_contact
def website_send_to(self):
"""return the email address with name.
to use when user wants to send an email from the alias
Return
"First Last | email at example.com" <reverse-alias@SL>
"""
# Prefer using contact name if possible
user = self.user
name = self.name
email = self.website_email
if (
not user
or not SenderFormatEnum.has_value(user.sender_format)
or user.sender_format == SenderFormatEnum.AT.value
):
email = email.replace("@", " at ")
elif user.sender_format == SenderFormatEnum.A.value:
email = email.replace("@", "(a)")
# if no name, try to parse it from website_from
if not name and self.website_from:
try:
name = address.parse(self.website_from).display_name
except Exception:
# Skip if website_from is wrongly formatted
LOG.e(
"Cannot parse contact %s website_from %s", self, self.website_from
)
name = ""
# remove all double quote
if name:
name = name.replace('"', "")
if name:
name = name + " | " + email
else:
name = email
# cannot use formataddr here as this field is for email client, not for MTA
return f'"{name}" <{self.reply_email}>'
def new_addr(self):
"""
Replace original email by reply_email. Possible formats:
- First Last - first at example.com <reply_email> OR
- First Last - first(a)example.com <reply_email> OR
- First Last <reply_email>
- first at example.com <reply_email>
- reply_email
And return new address with RFC 2047 format
"""
user = self.user
sender_format = user.sender_format if user else SenderFormatEnum.AT.value
if sender_format == SenderFormatEnum.NO_NAME.value:
return self.reply_email
if sender_format == SenderFormatEnum.NAME_ONLY.value:
new_name = self.name
elif sender_format == SenderFormatEnum.AT_ONLY.value:
new_name = self.website_email.replace("@", " at ").strip()
elif sender_format == SenderFormatEnum.AT.value:
formatted_email = self.website_email.replace("@", " at ").strip()
new_name = (
(self.name + " - " + formatted_email)
if self.name and self.name != self.website_email.strip()
else formatted_email
)
else: # SenderFormatEnum.A.value
formatted_email = self.website_email.replace("@", "(a)").strip()
new_name = (
(self.name + " - " + formatted_email)
if self.name and self.name != self.website_email.strip()
else formatted_email
)
from app.email_utils import sl_formataddr
new_addr = sl_formataddr((new_name, self.reply_email)).strip()
return new_addr.strip()
def last_reply(self) -> "EmailLog":
"""return the most recent reply"""
return (
EmailLog.filter_by(contact_id=self.id, is_reply=True)
.order_by(desc(EmailLog.created_at))
.first()
)
def __repr__(self):
return f"<Contact {self.id} {self.website_email} {self.alias_id}>"
class CustomDomain(Base, ModelMixin):
__tablename__ = "custom_domain"
user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False)
domain = sa.Column(sa.String(128), unique=True, nullable=False)
# default name to use when user replies/sends from alias
name = sa.Column(sa.String(128), nullable=True, default=None)
# mx verified
verified = sa.Column(sa.Boolean, nullable=False, default=False)
dkim_verified = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
spf_verified = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
dmarc_verified = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
_mailboxes = orm.relationship("Mailbox", secondary="domain_mailbox", lazy="joined")
# an alias is created automatically the first time it receives an email
catch_all = sa.Column(sa.Boolean, nullable=False, default=False, server_default="0")
# option to generate random prefix version automatically
random_prefix_generation = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# incremented when a check is failed on the domain
# alert when the number exceeds a threshold
# used in check_custom_domain()
nb_failed_checks = sa.Column(
sa.Integer, default=0, server_default="0", nullable=False
)
# only domain has the ownership verified can go the next DNS step
# MX verified domains before this change don't have to do the TXT check
# and therefore have ownership_verified=True
ownership_verified = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# randomly generated TXT value for verifying domain ownership
# the TXT record should be sl-verification=txt_token
ownership_txt_token = sa.Column(sa.String(128), nullable=True)
# if the domain is SimpleLogin subdomain, no need for the ownership, SPF, DKIM, DMARC check
is_sl_subdomain = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
__table_args__ = (
Index(
"ix_unique_domain", # Index name
"domain", # Columns which are part of the index
unique=True,
postgresql_where=Column("ownership_verified"),
), # The condition
)
user = orm.relationship(User, foreign_keys=[user_id], backref="custom_domains")
def mailboxes(self):
if self._mailboxes:
return self._mailboxes
else:
return [self.user.default_mailbox]
def nb_alias(self):
return Alias.filter_by(custom_domain_id=self.id).count()
def get_trash_url(self):
return config.URL + f"/dashboard/domains/{self.id}/trash"
def get_ownership_dns_txt_value(self):
return f"sl-verification={self.ownership_txt_token}"
def create(cls, **kwargs):
domain = kwargs.get("domain")
kwargs["domain"] = domain.replace("\n", "")
if DeletedSubdomain.get_by(domain=domain):
raise SubdomainInTrashError
domain: CustomDomain = super(CustomDomain, cls).create(**kwargs)
# generate a domain ownership txt token
if not domain.ownership_txt_token:
domain.ownership_txt_token = random_string(30)
Session.commit()
if domain.is_sl_subdomain:
user = domain.user
user._subdomain_quota -= 1
Session.flush()
return domain
def delete(cls, obj_id):
obj: CustomDomain = cls.get(obj_id)
if obj.is_sl_subdomain:
DeletedSubdomain.create(domain=obj.domain)
return super(CustomDomain, cls).delete(obj_id)
def auto_create_rules(self):
return sorted(self._auto_create_rules, key=lambda rule: rule.order)
def __repr__(self):
return f"<Custom Domain {self.domain}>"
class Mailbox(Base, ModelMixin):
__tablename__ = "mailbox"
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, index=True
)
email = sa.Column(sa.String(256), nullable=False, index=True)
verified = sa.Column(sa.Boolean, default=False, nullable=False)
force_spf = sa.Column(sa.Boolean, default=True, server_default="1", nullable=False)
# used when user wants to update mailbox email
new_email = sa.Column(sa.String(256), unique=True)
pgp_public_key = sa.Column(sa.Text, nullable=True)
pgp_finger_print = sa.Column(sa.String(512), nullable=True)
disable_pgp = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# incremented when a check is failed on the mailbox
# alert when the number exceeds a threshold
# used in sanity_check()
nb_failed_checks = sa.Column(
sa.Integer, default=0, server_default="0", nullable=False
)
# a mailbox can be disabled if it can't be reached
disabled = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0")
generic_subject = sa.Column(sa.String(78), nullable=True)
__table_args__ = (sa.UniqueConstraint("user_id", "email", name="uq_mailbox_user"),)
user = orm.relationship(User, foreign_keys=[user_id])
def pgp_enabled(self) -> bool:
if self.pgp_finger_print and not self.disable_pgp:
return True
return False
def nb_alias(self):
return (
AliasMailbox.filter_by(mailbox_id=self.id).count()
+ Alias.filter_by(mailbox_id=self.id).count()
)
def is_proton(self) -> bool:
if (
self.email.endswith("@proton.me")
or self.email.endswith("@protonmail.com")
or self.email.endswith("@protonmail.ch")
or self.email.endswith("@proton.ch")
or self.email.endswith("@pm.me")
):
return True
from app.email_utils import get_email_local_part
mx_domains: [(int, str)] = get_mx_domains(get_email_local_part(self.email))
# Proton is the first domain
if mx_domains and mx_domains[0][1] in (
"mail.protonmail.ch.",
"mailsec.protonmail.ch.",
):
return True
return False
def delete(cls, obj_id):
mailbox: Mailbox = cls.get(obj_id)
user = mailbox.user
# Put all aliases belonging to this mailbox to global or domain trash
for alias in Alias.filter_by(mailbox_id=obj_id):
# special handling for alias that has several mailboxes and has mailbox_id=obj_id
if len(alias.mailboxes) > 1:
# use the first mailbox found in alias._mailboxes
first_mb = alias._mailboxes[0]
alias.mailbox_id = first_mb.id
alias._mailboxes.remove(first_mb)
else:
from app import alias_utils
# only put aliases that have mailbox as a single mailbox into trash
alias_utils.delete_alias(alias, user)
Session.commit()
cls.filter(cls.id == obj_id).delete()
Session.commit()
def aliases(self) -> [Alias]:
ret = Alias.filter_by(mailbox_id=self.id).all()
for am in AliasMailbox.filter_by(mailbox_id=self.id):
ret.append(am.alias)
return ret
def create(cls, **kw):
if "email" in kw:
kw["email"] = sanitize_email(kw["email"])
return super().create(**kw)
def __repr__(self):
return f"<Mailbox {self.id} {self.email}>"
def sanitize_email(email_address: str, not_lower=False) -> str:
if email_address:
email_address = email_address.strip().replace(" ", "").replace("\n", " ")
if not not_lower:
email_address = email_address.lower()
return email_address.replace("\u200f", "")
def sanity_check():
LOG.d("sanitize user email")
for user in User.filter_by(activated=True).all():
if sanitize_email(user.email) != user.email:
LOG.e("%s does not have sanitized email", user)
LOG.d("sanitize alias address & name")
sanitize_alias_address_name()
LOG.d("sanity contact address")
contact_email_sanity_date = arrow.get("2021-01-12")
for contact in Contact.yield_per_query():
if sanitize_email(contact.reply_email) != contact.reply_email:
LOG.e("Contact %s reply-email not sanitized", contact)
if (
sanitize_email(contact.website_email, not_lower=True)
!= contact.website_email
and contact.created_at > contact_email_sanity_date
):
LOG.e("Contact %s website-email not sanitized", contact)
if not contact.invalid_email and not is_valid_email(contact.website_email):
LOG.e("%s invalid email", contact)
contact.invalid_email = True
Session.commit()
LOG.d("sanitize mailbox address")
for mailbox in Mailbox.yield_per_query():
if sanitize_email(mailbox.email) != mailbox.email:
LOG.e("Mailbox %s address not sanitized", mailbox)
LOG.d("normalize reverse alias")
for contact in Contact.yield_per_query():
if normalize_reply_email(contact.reply_email) != contact.reply_email:
LOG.e(
"Contact %s reply email is not normalized %s",
contact,
contact.reply_email,
)
LOG.d("clean domain name")
for domain in CustomDomain.yield_per_query():
if domain.name and "\n" in domain.name:
LOG.e("Domain %s name contain linebreak %s", domain, domain.name)
LOG.d("migrate domain trash if needed")
migrate_domain_trash()
LOG.d("fix custom domain for alias")
set_custom_domain_for_alias()
LOG.d("check mailbox valid domain")
check_mailbox_valid_domain()
LOG.d("check mailbox valid PGP keys")
check_mailbox_valid_pgp_keys()
LOG.d(
"""check if there's an email that starts with "\u200f" (right-to-left mark (RLM))"""
)
for contact in (
Contact.yield_per_query()
.filter(Contact.website_email.startswith("\u200f"))
.all()
):
contact.website_email = contact.website_email.replace("\u200f", "")
LOG.e("remove right-to-left mark (RLM) from %s", contact)
Session.commit()
LOG.d("Finish sanity check") | null |
180,561 | import argparse
import asyncio
import urllib.parse
from typing import List, Tuple
import arrow
import requests
from sqlalchemy import func, desc, or_, and_
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.orm import joinedload
from sqlalchemy.orm.exc import ObjectDeletedError
from sqlalchemy.sql import Insert, text
from app import s3, config
from app.alias_utils import nb_email_log_for_mailbox
from app.api.views.apple import verify_receipt
from app.db import Session
from app.dns_utils import get_mx_domains, is_mx_equivalent
from app.email_utils import (
send_email,
send_trial_end_soon_email,
render,
email_can_be_used_as_mailbox,
send_email_with_rate_control,
get_email_domain_part,
)
from app.email_validation import is_valid_email, normalize_reply_email
from app.errors import ProtonPartnerNotSetUp
from app.log import LOG
from app.mail_sender import load_unsent_mails_from_fs_and_resend
from app.models import (
Subscription,
User,
Alias,
EmailLog,
CustomDomain,
Client,
ManualSubscription,
RefusedEmail,
AppleSubscription,
Mailbox,
Monitoring,
Contact,
CoinbaseSubscription,
TransactionalEmail,
Bounce,
Metric2,
SLDomain,
DeletedAlias,
DomainDeletedAlias,
Hibp,
HibpNotifiedAlias,
Directory,
DeletedDirectory,
DeletedSubdomain,
PartnerSubscription,
PartnerUser,
ApiToCookieToken,
)
from app.pgp_utils import load_public_key_and_check, PGPException
from app.proton.utils import get_proton_partner
from app.utils import sanitize_email
from server import create_light_app
from tasks.cleanup_old_imports import cleanup_old_imports
from tasks.cleanup_old_jobs import cleanup_old_jobs
from tasks.cleanup_old_notifications import cleanup_old_notifications
def check_single_custom_domain(custom_domain):
mx_domains = get_mx_domains(custom_domain.domain)
if not is_mx_equivalent(mx_domains, config.EMAIL_SERVERS_WITH_PRIORITY):
user = custom_domain.user
LOG.w(
"The MX record is not correctly set for %s %s %s",
custom_domain,
user,
mx_domains,
)
custom_domain.nb_failed_checks += 1
# send alert if fail for 5 consecutive days
if custom_domain.nb_failed_checks > 5:
domain_dns_url = f"{config.URL}/dashboard/domains/{custom_domain.id}/dns"
LOG.w("Alert domain MX check fails %s about %s", user, custom_domain)
send_email_with_rate_control(
user,
config.AlERT_WRONG_MX_RECORD_CUSTOM_DOMAIN,
user.email,
f"Please update {custom_domain.domain} DNS on SimpleLogin",
render(
"transactional/custom-domain-dns-issue.txt.jinja2",
custom_domain=custom_domain,
domain_dns_url=domain_dns_url,
),
max_nb_alert=1,
nb_day=30,
retries=3,
)
# reset checks
custom_domain.nb_failed_checks = 0
else:
# reset checks
custom_domain.nb_failed_checks = 0
Session.commit()
LOG = _get_logger("SL")
class CustomDomain(Base, ModelMixin):
__tablename__ = "custom_domain"
user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False)
domain = sa.Column(sa.String(128), unique=True, nullable=False)
# default name to use when user replies/sends from alias
name = sa.Column(sa.String(128), nullable=True, default=None)
# mx verified
verified = sa.Column(sa.Boolean, nullable=False, default=False)
dkim_verified = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
spf_verified = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
dmarc_verified = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
_mailboxes = orm.relationship("Mailbox", secondary="domain_mailbox", lazy="joined")
# an alias is created automatically the first time it receives an email
catch_all = sa.Column(sa.Boolean, nullable=False, default=False, server_default="0")
# option to generate random prefix version automatically
random_prefix_generation = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# incremented when a check is failed on the domain
# alert when the number exceeds a threshold
# used in check_custom_domain()
nb_failed_checks = sa.Column(
sa.Integer, default=0, server_default="0", nullable=False
)
# only domain has the ownership verified can go the next DNS step
# MX verified domains before this change don't have to do the TXT check
# and therefore have ownership_verified=True
ownership_verified = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# randomly generated TXT value for verifying domain ownership
# the TXT record should be sl-verification=txt_token
ownership_txt_token = sa.Column(sa.String(128), nullable=True)
# if the domain is SimpleLogin subdomain, no need for the ownership, SPF, DKIM, DMARC check
is_sl_subdomain = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
__table_args__ = (
Index(
"ix_unique_domain", # Index name
"domain", # Columns which are part of the index
unique=True,
postgresql_where=Column("ownership_verified"),
), # The condition
)
user = orm.relationship(User, foreign_keys=[user_id], backref="custom_domains")
def mailboxes(self):
if self._mailboxes:
return self._mailboxes
else:
return [self.user.default_mailbox]
def nb_alias(self):
return Alias.filter_by(custom_domain_id=self.id).count()
def get_trash_url(self):
return config.URL + f"/dashboard/domains/{self.id}/trash"
def get_ownership_dns_txt_value(self):
return f"sl-verification={self.ownership_txt_token}"
def create(cls, **kwargs):
domain = kwargs.get("domain")
kwargs["domain"] = domain.replace("\n", "")
if DeletedSubdomain.get_by(domain=domain):
raise SubdomainInTrashError
domain: CustomDomain = super(CustomDomain, cls).create(**kwargs)
# generate a domain ownership txt token
if not domain.ownership_txt_token:
domain.ownership_txt_token = random_string(30)
Session.commit()
if domain.is_sl_subdomain:
user = domain.user
user._subdomain_quota -= 1
Session.flush()
return domain
def delete(cls, obj_id):
obj: CustomDomain = cls.get(obj_id)
if obj.is_sl_subdomain:
DeletedSubdomain.create(domain=obj.domain)
return super(CustomDomain, cls).delete(obj_id)
def auto_create_rules(self):
return sorted(self._auto_create_rules, key=lambda rule: rule.order)
def __repr__(self):
return f"<Custom Domain {self.domain}>"
def check_custom_domain():
LOG.d("Check verified domain for DNS issues")
for custom_domain in CustomDomain.filter_by(verified=True): # type: CustomDomain
try:
check_single_custom_domain(custom_domain)
except ObjectDeletedError:
LOG.i("custom domain has been deleted") | null |
180,562 | import argparse
import asyncio
import urllib.parse
from typing import List, Tuple
import arrow
import requests
from sqlalchemy import func, desc, or_, and_
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.orm import joinedload
from sqlalchemy.orm.exc import ObjectDeletedError
from sqlalchemy.sql import Insert, text
from app import s3, config
from app.alias_utils import nb_email_log_for_mailbox
from app.api.views.apple import verify_receipt
from app.db import Session
from app.dns_utils import get_mx_domains, is_mx_equivalent
from app.email_utils import (
send_email,
send_trial_end_soon_email,
render,
email_can_be_used_as_mailbox,
send_email_with_rate_control,
get_email_domain_part,
)
from app.email_validation import is_valid_email, normalize_reply_email
from app.errors import ProtonPartnerNotSetUp
from app.log import LOG
from app.mail_sender import load_unsent_mails_from_fs_and_resend
from app.models import (
Subscription,
User,
Alias,
EmailLog,
CustomDomain,
Client,
ManualSubscription,
RefusedEmail,
AppleSubscription,
Mailbox,
Monitoring,
Contact,
CoinbaseSubscription,
TransactionalEmail,
Bounce,
Metric2,
SLDomain,
DeletedAlias,
DomainDeletedAlias,
Hibp,
HibpNotifiedAlias,
Directory,
DeletedDirectory,
DeletedSubdomain,
PartnerSubscription,
PartnerUser,
ApiToCookieToken,
)
from app.pgp_utils import load_public_key_and_check, PGPException
from app.proton.utils import get_proton_partner
from app.utils import sanitize_email
from server import create_light_app
from tasks.cleanup_old_imports import cleanup_old_imports
from tasks.cleanup_old_jobs import cleanup_old_jobs
from tasks.cleanup_old_notifications import cleanup_old_notifications
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
LOG = _get_logger("SL")
class ApiToCookieToken(Base, ModelMixin):
__tablename__ = "api_cookie_token"
code = sa.Column(sa.String(128), unique=True, nullable=False)
user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False)
api_key_id = sa.Column(sa.ForeignKey(ApiKey.id, ondelete="cascade"), nullable=False)
user = orm.relationship(User)
api_key = orm.relationship(ApiKey)
def create(cls, **kwargs):
code = secrets.token_urlsafe(32)
return super().create(code=code, **kwargs)
The provided code snippet includes necessary dependencies for implementing the `delete_expired_tokens` function. Write a Python function `def delete_expired_tokens()` to solve the following problem:
Delete old tokens
Here is the function:
def delete_expired_tokens():
"""
Delete old tokens
"""
max_time = arrow.now().shift(hours=-1)
nb_row = ApiToCookieToken.filter(ApiToCookieToken.created_at < max_time).delete()
Session.commit()
LOG.d("Delete api to cookie tokens older than %s, nb row %s", max_time, nb_row) | Delete old tokens |
180,563 | import argparse
import asyncio
import urllib.parse
from typing import List, Tuple
import arrow
import requests
from sqlalchemy import func, desc, or_, and_
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.orm import joinedload
from sqlalchemy.orm.exc import ObjectDeletedError
from sqlalchemy.sql import Insert, text
from app import s3, config
from app.alias_utils import nb_email_log_for_mailbox
from app.api.views.apple import verify_receipt
from app.db import Session
from app.dns_utils import get_mx_domains, is_mx_equivalent
from app.email_utils import (
send_email,
send_trial_end_soon_email,
render,
email_can_be_used_as_mailbox,
send_email_with_rate_control,
get_email_domain_part,
)
from app.email_validation import is_valid_email, normalize_reply_email
from app.errors import ProtonPartnerNotSetUp
from app.log import LOG
from app.mail_sender import load_unsent_mails_from_fs_and_resend
from app.models import (
Subscription,
User,
Alias,
EmailLog,
CustomDomain,
Client,
ManualSubscription,
RefusedEmail,
AppleSubscription,
Mailbox,
Monitoring,
Contact,
CoinbaseSubscription,
TransactionalEmail,
Bounce,
Metric2,
SLDomain,
DeletedAlias,
DomainDeletedAlias,
Hibp,
HibpNotifiedAlias,
Directory,
DeletedDirectory,
DeletedSubdomain,
PartnerSubscription,
PartnerUser,
ApiToCookieToken,
)
from app.pgp_utils import load_public_key_and_check, PGPException
from app.proton.utils import get_proton_partner
from app.utils import sanitize_email
from server import create_light_app
from tasks.cleanup_old_imports import cleanup_old_imports
from tasks.cleanup_old_jobs import cleanup_old_jobs
from tasks.cleanup_old_notifications import cleanup_old_notifications
async def _hibp_check(api_key, queue):
"""
Uses a single API key to check the queue as fast as possible.
This function to be ran simultaneously (multiple _hibp_check functions with different keys on the same queue) to make maximum use of multiple API keys.
"""
default_rate_sleep = (60.0 / config.HIBP_RPM) + 0.1
rate_sleep = default_rate_sleep
rate_hit_counter = 0
while True:
try:
alias_id = queue.get_nowait()
except asyncio.QueueEmpty:
return
alias = Alias.get(alias_id)
if not alias:
continue
user = alias.user
if user.disabled or not user.is_paid():
# Mark it as hibp done to skip it as if it had been checked
alias.hibp_last_check = arrow.utcnow()
Session.commit()
continue
LOG.d("Checking HIBP for %s", alias)
request_headers = {
"user-agent": "SimpleLogin",
"hibp-api-key": api_key,
}
r = requests.get(
f"https://haveibeenpwned.com/api/v3/breachedaccount/{urllib.parse.quote(alias.email)}",
headers=request_headers,
)
if r.status_code == 200:
# Breaches found
alias.hibp_breaches = [
Hibp.get_by(name=entry["Name"]) for entry in r.json()
]
if len(alias.hibp_breaches) > 0:
LOG.w("%s appears in HIBP breaches %s", alias, alias.hibp_breaches)
if rate_hit_counter > 0:
rate_hit_counter -= 1
elif r.status_code == 404:
# No breaches found
alias.hibp_breaches = []
elif r.status_code == 429:
# rate limited
LOG.w("HIBP rate limited, check alias %s in the next run", alias)
rate_hit_counter += 1
rate_sleep = default_rate_sleep + (0.2 * rate_hit_counter)
if rate_hit_counter > 10:
LOG.w(f"HIBP rate limited too many times stopping with alias {alias}")
return
# Just sleep for a while
asyncio.sleep(5)
elif r.status_code > 500:
LOG.w("HIBP server 5** error %s", r.status_code)
return
else:
LOG.error(
"An error occurred while checking alias %s: %s - %s",
alias,
r.status_code,
r.text,
)
return
alias.hibp_last_check = arrow.utcnow()
Session.add(alias)
Session.commit()
LOG.d("Updated breach info for %s", alias)
await asyncio.sleep(rate_sleep)
def get_alias_to_check_hibp(
oldest_hibp_allowed: arrow.Arrow,
user_ids_to_skip: list[int],
min_alias_id: int,
max_alias_id: int,
):
now = arrow.now()
alias_query = (
Session.query(Alias)
.join(User, User.id == Alias.user_id)
.join(Subscription, User.id == Subscription.user_id, isouter=True)
.join(ManualSubscription, User.id == ManualSubscription.user_id, isouter=True)
.join(AppleSubscription, User.id == AppleSubscription.user_id, isouter=True)
.join(
CoinbaseSubscription,
User.id == CoinbaseSubscription.user_id,
isouter=True,
)
.join(PartnerUser, User.id == PartnerUser.user_id, isouter=True)
.join(
PartnerSubscription,
PartnerSubscription.partner_user_id == PartnerUser.id,
isouter=True,
)
.filter(
or_(
Alias.hibp_last_check.is_(None),
Alias.hibp_last_check < oldest_hibp_allowed,
),
Alias.user_id.notin_(user_ids_to_skip),
Alias.enabled,
Alias.id >= min_alias_id,
Alias.id < max_alias_id,
User.disabled == False, # noqa: E712
or_(
User.lifetime,
ManualSubscription.end_at > now,
Subscription.next_bill_date > now.date(),
AppleSubscription.expires_date > now,
CoinbaseSubscription.end_at > now,
PartnerSubscription.end_at > now,
),
)
)
if config.HIBP_SKIP_PARTNER_ALIAS:
alias_query = alias_query.filter(
Alias.flags.op("&")(Alias.FLAG_PARTNER_CREATED) == 0
)
for alias in (
alias_query.order_by(Alias.id.asc()).enable_eagerloads(False).yield_per(500)
):
yield alias
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
LOG = _get_logger("SL")
class Hibp(Base, ModelMixin):
__tablename__ = "hibp"
name = sa.Column(sa.String(), nullable=False, unique=True, index=True)
breached_aliases = orm.relationship("Alias", secondary="alias_hibp")
description = sa.Column(sa.Text)
date = sa.Column(ArrowType, nullable=True)
def __repr__(self):
return f"<HIBP Breach {self.id} {self.name}>"
class Alias(Base, ModelMixin):
__tablename__ = "alias"
FLAG_PARTNER_CREATED = 1 << 0
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, index=True
)
email = sa.Column(sa.String(128), unique=True, nullable=False)
# the name to use when user replies/sends from alias
name = sa.Column(sa.String(128), nullable=True, default=None)
enabled = sa.Column(sa.Boolean(), default=True, nullable=False)
flags = sa.Column(
sa.BigInteger(), default=0, server_default="0", nullable=False, index=True
)
custom_domain_id = sa.Column(
sa.ForeignKey("custom_domain.id", ondelete="cascade"), nullable=True, index=True
)
custom_domain = orm.relationship("CustomDomain", foreign_keys=[custom_domain_id])
# To know whether an alias is created "on the fly", i.e. via the custom domain catch-all feature
automatic_creation = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# to know whether an alias belongs to a directory
directory_id = sa.Column(
sa.ForeignKey("directory.id", ondelete="cascade"), nullable=True, index=True
)
note = sa.Column(sa.Text, default=None, nullable=True)
# an alias can be owned by another mailbox
mailbox_id = sa.Column(
sa.ForeignKey("mailbox.id", ondelete="cascade"), nullable=False, index=True
)
# prefix _ to avoid this object being used accidentally.
# To have the list of all mailboxes, should use AliasInfo instead
_mailboxes = orm.relationship("Mailbox", secondary="alias_mailbox", lazy="joined")
# If the mailbox has PGP-enabled, user can choose disable the PGP on the alias
# this is useful when some senders already support PGP
disable_pgp = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# a way to bypass the bounce automatic disable mechanism
cannot_be_disabled = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# when a mailbox wants to send an email on behalf of the alias via the reverse-alias
# several checks are performed to avoid email spoofing
# this option allow disabling these checks
disable_email_spoofing_check = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# to know whether an alias is added using a batch import
batch_import_id = sa.Column(
sa.ForeignKey("batch_import.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
# set in case of alias transfer.
original_owner_id = sa.Column(
sa.ForeignKey(User.id, ondelete="SET NULL"), nullable=True
)
# alias is pinned on top
pinned = sa.Column(sa.Boolean, nullable=False, default=False, server_default="0")
# used to transfer an alias to another user
transfer_token = sa.Column(sa.String(64), default=None, unique=True, nullable=True)
transfer_token_expiration = sa.Column(
ArrowType, default=arrow.utcnow, nullable=True
)
# have I been pwned
hibp_last_check = sa.Column(ArrowType, default=None, index=True)
hibp_breaches = orm.relationship("Hibp", secondary="alias_hibp")
# to use Postgres full text search. Only applied on "note" column for now
# this is a generated Postgres column
ts_vector = sa.Column(
TSVector(), sa.Computed("to_tsvector('english', note)", persisted=True)
)
last_email_log_id = sa.Column(sa.Integer, default=None, nullable=True)
__table_args__ = (
Index("ix_video___ts_vector__", ts_vector, postgresql_using="gin"),
# index on note column using pg_trgm
Index(
"note_pg_trgm_index",
"note",
postgresql_ops={"note": "gin_trgm_ops"},
postgresql_using="gin",
),
)
user = orm.relationship(User, foreign_keys=[user_id])
mailbox = orm.relationship("Mailbox", lazy="joined")
def mailboxes(self):
ret = [self.mailbox]
for m in self._mailboxes:
if m.id is not self.mailbox.id:
ret.append(m)
ret = [mb for mb in ret if mb.verified]
ret = sorted(ret, key=lambda mb: mb.email)
return ret
def authorized_addresses(self) -> [str]:
"""return addresses that can send on behalf of this alias, i.e. can send emails to this alias's reverse-aliases
Including its mailboxes and their authorized addresses
"""
mailboxes = self.mailboxes
ret = [mb.email for mb in mailboxes]
for mailbox in mailboxes:
for aa in mailbox.authorized_addresses:
ret.append(aa.email)
return ret
def mailbox_support_pgp(self) -> bool:
"""return True of one of the mailboxes support PGP"""
for mb in self.mailboxes:
if mb.pgp_enabled():
return True
return False
def pgp_enabled(self) -> bool:
if self.mailbox_support_pgp() and not self.disable_pgp:
return True
return False
def get_custom_domain(alias_address) -> Optional["CustomDomain"]:
alias_domain = validate_email(
alias_address, check_deliverability=False, allow_smtputf8=False
).domain
# handle the case a SLDomain is also a CustomDomain
if SLDomain.get_by(domain=alias_domain) is None:
custom_domain = CustomDomain.get_by(domain=alias_domain)
if custom_domain:
return custom_domain
def create(cls, **kw):
commit = kw.pop("commit", False)
flush = kw.pop("flush", False)
new_alias = cls(**kw)
user = User.get(new_alias.user_id)
if user.is_premium():
limits = config.ALIAS_CREATE_RATE_LIMIT_PAID
else:
limits = config.ALIAS_CREATE_RATE_LIMIT_FREE
# limits is array of (hits,days)
for limit in limits:
key = f"alias_create_{limit[1]}d:{user.id}"
rate_limiter.check_bucket_limit(key, limit[0], limit[1])
email = kw["email"]
# make sure email is lowercase and doesn't have any whitespace
email = sanitize_email(email)
# make sure alias is not in global trash, i.e. DeletedAlias table
if DeletedAlias.get_by(email=email):
raise AliasInTrashError
if DomainDeletedAlias.get_by(email=email):
raise AliasInTrashError
# detect whether alias should belong to a custom domain
if "custom_domain_id" not in kw:
custom_domain = Alias.get_custom_domain(email)
if custom_domain:
new_alias.custom_domain_id = custom_domain.id
Session.add(new_alias)
DailyMetric.get_or_create_today_metric().nb_alias += 1
if commit:
Session.commit()
if flush:
Session.flush()
return new_alias
def create_new(cls, user, prefix, note=None, mailbox_id=None):
prefix = prefix.lower().strip().replace(" ", "")
if not prefix:
raise Exception("alias prefix cannot be empty")
# find the right suffix - avoid infinite loop by running this at max 1000 times
for _ in range(1000):
suffix = user.get_random_alias_suffix()
email = f"{prefix}.{suffix}@{config.FIRST_ALIAS_DOMAIN}"
if available_sl_email(email):
break
return Alias.create(
user_id=user.id,
email=email,
note=note,
mailbox_id=mailbox_id or user.default_mailbox_id,
)
def delete(cls, obj_id):
raise Exception("should use delete_alias(alias,user) instead")
def create_new_random(
cls,
user,
scheme: int = AliasGeneratorEnum.word.value,
in_hex: bool = False,
note: str = None,
):
"""create a new random alias"""
custom_domain = None
random_email = None
if user.default_alias_custom_domain_id:
custom_domain = CustomDomain.get(user.default_alias_custom_domain_id)
random_email = generate_random_alias_email(
scheme=scheme, in_hex=in_hex, alias_domain=custom_domain.domain
)
elif user.default_alias_public_domain_id:
sl_domain: SLDomain = SLDomain.get(user.default_alias_public_domain_id)
if sl_domain.premium_only and not user.is_premium():
LOG.w("%s not premium, cannot use %s", user, sl_domain)
else:
random_email = generate_random_alias_email(
scheme=scheme, in_hex=in_hex, alias_domain=sl_domain.domain
)
if not random_email:
random_email = generate_random_alias_email(scheme=scheme, in_hex=in_hex)
alias = Alias.create(
user_id=user.id,
email=random_email,
mailbox_id=user.default_mailbox_id,
note=note,
)
if custom_domain:
alias.custom_domain_id = custom_domain.id
return alias
def mailbox_email(self):
if self.mailbox_id:
return self.mailbox.email
else:
return self.user.email
def __repr__(self):
return f"<Alias {self.id} {self.email}>"
The provided code snippet includes necessary dependencies for implementing the `check_hibp` function. Write a Python function `async def check_hibp()` to solve the following problem:
Check all aliases on the HIBP (Have I Been Pwned) API
Here is the function:
async def check_hibp():
"""
Check all aliases on the HIBP (Have I Been Pwned) API
"""
LOG.d("Checking HIBP API for aliases in breaches")
if len(config.HIBP_API_KEYS) == 0:
LOG.e("No HIBP API keys")
return
LOG.d("Updating list of known breaches")
r = requests.get("https://haveibeenpwned.com/api/v3/breaches")
for entry in r.json():
hibp_entry = Hibp.get_or_create(name=entry["Name"])
hibp_entry.date = arrow.get(entry["BreachDate"])
hibp_entry.description = entry["Description"]
Session.commit()
LOG.d("Updated list of known breaches")
LOG.d("Getting the list of users to skip")
query = "select u.id, count(a.id) from users u, alias a where a.user_id=u.id group by u.id having count(a.id) > :max_alias"
rows = Session.execute(query, {"max_alias": config.HIBP_MAX_ALIAS_CHECK})
user_ids = [row[0] for row in rows]
LOG.d("Got %d users to skip" % len(user_ids))
LOG.d("Checking aliases")
queue = asyncio.Queue()
min_alias_id = 0
max_alias_id = Session.query(func.max(Alias.id)).scalar()
step = 10000
now = arrow.now()
oldest_hibp_allowed = now.shift(days=-config.HIBP_SCAN_INTERVAL_DAYS)
alias_checked = 0
for alias_batch_id in range(min_alias_id, max_alias_id, step):
for alias in get_alias_to_check_hibp(
oldest_hibp_allowed, user_ids, alias_batch_id, alias_batch_id + step
):
await queue.put(alias.id)
alias_checked += queue.qsize()
LOG.d(
f"Need to check about {queue.qsize()} aliases in this loop {alias_batch_id}/{max_alias_id}"
)
# Start one checking process per API key
# Each checking process will take one alias from the queue, get the info
# and then sleep for 1.5 seconds (due to HIBP API request limits)
checkers = []
for i in range(len(config.HIBP_API_KEYS)):
checker = asyncio.create_task(
_hibp_check(
config.HIBP_API_KEYS[i],
queue,
)
)
checkers.append(checker)
# Wait until all checking processes are done
for checker in checkers:
await checker
LOG.d(f"Done checking {alias_checked} HIBP API for aliases in breaches") | Check all aliases on the HIBP (Have I Been Pwned) API |
180,564 | import argparse
import asyncio
import urllib.parse
from typing import List, Tuple
import arrow
import requests
from sqlalchemy import func, desc, or_, and_
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.orm import joinedload
from sqlalchemy.orm.exc import ObjectDeletedError
from sqlalchemy.sql import Insert, text
from app import s3, config
from app.alias_utils import nb_email_log_for_mailbox
from app.api.views.apple import verify_receipt
from app.db import Session
from app.dns_utils import get_mx_domains, is_mx_equivalent
from app.email_utils import (
send_email,
send_trial_end_soon_email,
render,
email_can_be_used_as_mailbox,
send_email_with_rate_control,
get_email_domain_part,
)
from app.email_validation import is_valid_email, normalize_reply_email
from app.errors import ProtonPartnerNotSetUp
from app.log import LOG
from app.mail_sender import load_unsent_mails_from_fs_and_resend
from app.models import (
Subscription,
User,
Alias,
EmailLog,
CustomDomain,
Client,
ManualSubscription,
RefusedEmail,
AppleSubscription,
Mailbox,
Monitoring,
Contact,
CoinbaseSubscription,
TransactionalEmail,
Bounce,
Metric2,
SLDomain,
DeletedAlias,
DomainDeletedAlias,
Hibp,
HibpNotifiedAlias,
Directory,
DeletedDirectory,
DeletedSubdomain,
PartnerSubscription,
PartnerUser,
ApiToCookieToken,
)
from app.pgp_utils import load_public_key_and_check, PGPException
from app.proton.utils import get_proton_partner
from app.utils import sanitize_email
from server import create_light_app
from tasks.cleanup_old_imports import cleanup_old_imports
from tasks.cleanup_old_jobs import cleanup_old_jobs
from tasks.cleanup_old_notifications import cleanup_old_notifications
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
def render(template_name, **kwargs) -> str:
templates_dir = os.path.join(config.ROOT_DIR, "templates", "emails")
env = Environment(loader=FileSystemLoader(templates_dir))
template = env.get_template(template_name)
return template.render(
MAX_NB_EMAIL_FREE_PLAN=config.MAX_NB_EMAIL_FREE_PLAN,
URL=config.URL,
LANDING_PAGE_URL=config.LANDING_PAGE_URL,
YEAR=arrow.now().year,
**kwargs,
)
def send_email(
to_email,
subject,
plaintext,
html=None,
unsubscribe_link=None,
unsubscribe_via_email=False,
retries=0, # by default no retry if sending fails
ignore_smtp_error=False,
from_name=None,
from_addr=None,
):
to_email = sanitize_email(to_email)
LOG.d("send email to %s, subject '%s'", to_email, subject)
from_name = from_name or config.NOREPLY
from_addr = from_addr or config.NOREPLY
from_domain = get_email_domain_part(from_addr)
if html:
msg = MIMEMultipart("alternative")
msg.attach(MIMEText(plaintext))
msg.attach(MIMEText(html, "html"))
else:
msg = EmailMessage()
msg.set_payload(plaintext)
msg[headers.CONTENT_TYPE] = "text/plain"
msg[headers.SUBJECT] = subject
msg[headers.FROM] = f'"{from_name}" <{from_addr}>'
msg[headers.TO] = to_email
msg_id_header = make_msgid(domain=config.EMAIL_DOMAIN)
msg[headers.MESSAGE_ID] = msg_id_header
date_header = formatdate()
msg[headers.DATE] = date_header
if headers.MIME_VERSION not in msg:
msg[headers.MIME_VERSION] = "1.0"
if unsubscribe_link:
add_or_replace_header(msg, headers.LIST_UNSUBSCRIBE, f"<{unsubscribe_link}>")
if not unsubscribe_via_email:
add_or_replace_header(
msg, headers.LIST_UNSUBSCRIBE_POST, "List-Unsubscribe=One-Click"
)
# add DKIM
email_domain = from_addr[from_addr.find("@") + 1 :]
add_dkim_signature(msg, email_domain)
transaction = TransactionalEmail.create(email=to_email, commit=True)
# use a different envelope sender for each transactional email (aka VERP)
sl_sendmail(
generate_verp_email(VerpType.transactional, transaction.id, from_domain),
to_email,
msg,
retries=retries,
ignore_smtp_error=ignore_smtp_error,
)
LOG = _get_logger("SL")
class HibpNotifiedAlias(Base, ModelMixin):
"""Contain list of aliases that have been notified to users
So that we can only notify users of new aliases.
"""
__tablename__ = "hibp_notified_alias"
alias_id = sa.Column(
sa.ForeignKey("alias.id", ondelete="cascade"), nullable=False, index=True
)
user_id = sa.Column(sa.ForeignKey("users.id", ondelete="cascade"), nullable=False)
notified_at = sa.Column(ArrowType, default=arrow.utcnow, nullable=False)
class User(Base, ModelMixin, UserMixin, PasswordOracle):
__tablename__ = "users"
FLAG_FREE_DISABLE_CREATE_ALIAS = 1 << 0
FLAG_CREATED_FROM_PARTNER = 1 << 1
FLAG_FREE_OLD_ALIAS_LIMIT = 1 << 2
email = sa.Column(sa.String(256), unique=True, nullable=False)
name = sa.Column(sa.String(128), nullable=True)
is_admin = sa.Column(sa.Boolean, nullable=False, default=False)
alias_generator = sa.Column(
sa.Integer,
nullable=False,
default=AliasGeneratorEnum.word.value,
server_default=str(AliasGeneratorEnum.word.value),
)
notification = sa.Column(
sa.Boolean, default=True, nullable=False, server_default="1"
)
activated = sa.Column(sa.Boolean, default=False, nullable=False, index=True)
# an account can be disabled if having harmful behavior
disabled = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0")
profile_picture_id = sa.Column(sa.ForeignKey(File.id), nullable=True)
otp_secret = sa.Column(sa.String(16), nullable=True)
enable_otp = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
last_otp = sa.Column(sa.String(12), nullable=True, default=False)
# Fields for WebAuthn
fido_uuid = sa.Column(sa.String(), nullable=True, unique=True)
# the default domain that's used when user creates a new random alias
# default_alias_custom_domain_id XOR default_alias_public_domain_id
default_alias_custom_domain_id = sa.Column(
sa.ForeignKey("custom_domain.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
default_alias_public_domain_id = sa.Column(
sa.ForeignKey("public_domain.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
# some users could have lifetime premium
lifetime = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0")
paid_lifetime = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
lifetime_coupon_id = sa.Column(
sa.ForeignKey("lifetime_coupon.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
# user can use all premium features until this date
trial_end = sa.Column(
ArrowType, default=lambda: arrow.now().shift(days=7, hours=1), nullable=True
)
# the mailbox used when create random alias
# this field is nullable but in practice, it's always set
# it cannot be set to non-nullable though
# as this will create foreign key cycle between User and Mailbox
default_mailbox_id = sa.Column(
sa.ForeignKey("mailbox.id"), nullable=True, default=None
)
profile_picture = orm.relationship(File, foreign_keys=[profile_picture_id])
# Specify the format for sender address
# for the full list, see SenderFormatEnum
sender_format = sa.Column(
sa.Integer, default="0", nullable=False, server_default="0"
)
# to know whether user has explicitly chosen a sender format as opposed to those who use the default ones.
# users who haven't chosen a sender format and are using 1 or 3 format, their sender format will be set to 0
sender_format_updated_at = sa.Column(ArrowType, default=None)
replace_reverse_alias = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
referral_id = sa.Column(
sa.ForeignKey("referral.id", ondelete="SET NULL"),
nullable=True,
default=None,
index=True,
)
referral = orm.relationship("Referral", foreign_keys=[referral_id])
# whether intro has been shown to user
intro_shown = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
default_mailbox = orm.relationship("Mailbox", foreign_keys=[default_mailbox_id])
# user can set a more strict max_spam score to block spams more aggressively
max_spam_score = sa.Column(sa.Integer, nullable=True)
# newsletter is sent to this address
newsletter_alias_id = sa.Column(
sa.ForeignKey("alias.id", ondelete="SET NULL"),
nullable=True,
default=None,
index=True,
)
# whether to include the sender address in reverse-alias
include_sender_in_reverse_alias = sa.Column(
sa.Boolean, default=True, nullable=False, server_default="0"
)
# whether to use random string or random word as suffix
# Random word from dictionary file -> 0
# Completely random string -> 1
random_alias_suffix = sa.Column(
sa.Integer,
nullable=False,
default=AliasSuffixEnum.word.value,
server_default=str(AliasSuffixEnum.random_string.value),
)
# always expand the alias info, i.e. without needing to press "More"
expand_alias_info = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# ignore emails send from a mailbox to its alias. This can happen when replying all to a forwarded email
# can automatically re-includes the alias
ignore_loop_email = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# used for flask-login as an "alternative token"
# cf https://flask-login.readthedocs.io/en/latest/#alternative-tokens
alternative_id = sa.Column(sa.String(128), unique=True, nullable=True)
# by default, when an alias is automatically created, a note like "Created with ...." is created
# If this field is True, the note won't be created.
disable_automatic_alias_note = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# By default, the one-click unsubscribe disable the alias
# If set to true, it will block the sender instead
one_click_unsubscribe_block_sender = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# automatically include the website name when user creates an alias via the SimpleLogin icon in the email field
include_website_in_one_click_alias = sa.Column(
sa.Boolean,
# new user will have this option turned on automatically
default=True,
nullable=False,
# old user will have this option turned off
server_default="0",
)
_directory_quota = sa.Column(
"directory_quota", sa.Integer, default=50, nullable=False, server_default="50"
)
_subdomain_quota = sa.Column(
"subdomain_quota", sa.Integer, default=5, nullable=False, server_default="5"
)
# user can use import to import too many aliases
disable_import = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# user can use the phone feature
can_use_phone = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# in minutes
phone_quota = sa.Column(sa.Integer, nullable=True)
# Status code to return if is blocked
block_behaviour = sa.Column(
sa.Enum(BlockBehaviourEnum),
nullable=False,
server_default=BlockBehaviourEnum.return_2xx.name,
)
include_header_email_header = sa.Column(
sa.Boolean, default=True, nullable=False, server_default="1"
)
# bitwise flags. Allow for future expansion
flags = sa.Column(
sa.BigInteger,
default=FLAG_FREE_DISABLE_CREATE_ALIAS,
server_default="0",
nullable=False,
)
# Keep original unsub behaviour
unsub_behaviour = sa.Column(
IntEnumType(UnsubscribeBehaviourEnum),
default=UnsubscribeBehaviourEnum.PreserveOriginal,
server_default=str(UnsubscribeBehaviourEnum.DisableAlias.value),
nullable=False,
)
# Trigger hard deletion of the account at this time
delete_on = sa.Column(ArrowType, default=None)
__table_args__ = (
sa.Index(
"ix_users_activated_trial_end_lifetime", activated, trial_end, lifetime
),
sa.Index("ix_users_delete_on", delete_on),
)
def directory_quota(self):
return min(
self._directory_quota,
config.MAX_NB_DIRECTORY - Directory.filter_by(user_id=self.id).count(),
)
def subdomain_quota(self):
return min(
self._subdomain_quota,
config.MAX_NB_SUBDOMAIN
- CustomDomain.filter_by(user_id=self.id, is_sl_subdomain=True).count(),
)
def created_by_partner(self):
return User.FLAG_CREATED_FROM_PARTNER == (
self.flags & User.FLAG_CREATED_FROM_PARTNER
)
def subdomain_is_available():
return SLDomain.filter_by(can_use_subdomain=True).count() > 0
# implement flask-login "alternative token"
def get_id(self):
if self.alternative_id:
return self.alternative_id
else:
return str(self.id)
def create(cls, email, name="", password=None, from_partner=False, **kwargs):
email = sanitize_email(email)
user: User = super(User, cls).create(email=email, name=name[:100], **kwargs)
if password:
user.set_password(password)
Session.flush()
mb = Mailbox.create(user_id=user.id, email=user.email, verified=True)
Session.flush()
user.default_mailbox_id = mb.id
# generate an alternative_id if needed
if "alternative_id" not in kwargs:
user.alternative_id = str(uuid.uuid4())
# If the user is created from partner, do not notify
# nor give a trial
if from_partner:
user.flags = User.FLAG_CREATED_FROM_PARTNER
user.notification = False
user.trial_end = None
Job.create(
name=config.JOB_SEND_PROTON_WELCOME_1,
payload={"user_id": user.id},
run_at=arrow.now(),
)
Session.flush()
return user
# create a first alias mail to show user how to use when they login
alias = Alias.create_new(
user,
prefix="simplelogin-newsletter",
mailbox_id=mb.id,
note="This is your first alias. It's used to receive SimpleLogin communications "
"like new features announcements, newsletters.",
)
Session.flush()
user.newsletter_alias_id = alias.id
Session.flush()
if config.DISABLE_ONBOARDING:
LOG.d("Disable onboarding emails")
return user
# Schedule onboarding emails
Job.create(
name=config.JOB_ONBOARDING_1,
payload={"user_id": user.id},
run_at=arrow.now().shift(days=1),
)
Job.create(
name=config.JOB_ONBOARDING_2,
payload={"user_id": user.id},
run_at=arrow.now().shift(days=2),
)
Job.create(
name=config.JOB_ONBOARDING_4,
payload={"user_id": user.id},
run_at=arrow.now().shift(days=3),
)
Session.flush()
return user
def get_active_subscription(
self, include_partner_subscription: bool = True
) -> Optional[
Union[
Subscription
| AppleSubscription
| ManualSubscription
| CoinbaseSubscription
| PartnerSubscription
]
]:
sub: Subscription = self.get_paddle_subscription()
if sub:
return sub
apple_sub: AppleSubscription = AppleSubscription.get_by(user_id=self.id)
if apple_sub and apple_sub.is_valid():
return apple_sub
manual_sub: ManualSubscription = ManualSubscription.get_by(user_id=self.id)
if manual_sub and manual_sub.is_active():
return manual_sub
coinbase_subscription: CoinbaseSubscription = CoinbaseSubscription.get_by(
user_id=self.id
)
if coinbase_subscription and coinbase_subscription.is_active():
return coinbase_subscription
if include_partner_subscription:
partner_sub: PartnerSubscription = PartnerSubscription.find_by_user_id(
self.id
)
if partner_sub and partner_sub.is_active():
return partner_sub
return None
def get_active_subscription_end(
self, include_partner_subscription: bool = True
) -> Optional[arrow.Arrow]:
sub = self.get_active_subscription(
include_partner_subscription=include_partner_subscription
)
if isinstance(sub, Subscription):
return arrow.get(sub.next_bill_date)
if isinstance(sub, AppleSubscription):
return sub.expires_date
if isinstance(sub, ManualSubscription):
return sub.end_at
if isinstance(sub, CoinbaseSubscription):
return sub.end_at
return None
# region Billing
def lifetime_or_active_subscription(
self, include_partner_subscription: bool = True
) -> bool:
"""True if user has lifetime licence or active subscription"""
if self.lifetime:
return True
return self.get_active_subscription(include_partner_subscription) is not None
def is_paid(self) -> bool:
"""same as _lifetime_or_active_subscription but not include free manual subscription"""
sub = self.get_active_subscription()
if sub is None:
return False
if isinstance(sub, ManualSubscription) and sub.is_giveaway:
return False
return True
def is_active(self) -> bool:
if self.delete_on is None:
return True
return self.delete_on < arrow.now()
def in_trial(self):
"""return True if user does not have lifetime licence or an active subscription AND is in trial period"""
if self.lifetime_or_active_subscription():
return False
if self.trial_end and arrow.now() < self.trial_end:
return True
return False
def should_show_upgrade_button(self):
if self.lifetime_or_active_subscription():
return False
return True
def is_premium(self, include_partner_subscription: bool = True) -> bool:
"""
user is premium if they:
- have a lifetime deal or
- in trial period or
- active subscription
"""
if self.lifetime_or_active_subscription(include_partner_subscription):
return True
if self.trial_end and arrow.now() < self.trial_end:
return True
return False
def upgrade_channel(self) -> str:
"""Used on admin dashboard"""
# user can have multiple subscription channel
channels = []
if self.lifetime:
channels.append("Lifetime")
sub: Subscription = self.get_paddle_subscription()
if sub:
if sub.cancelled:
channels.append(
f"""Cancelled Paddle Subscription <a href="https://vendors.paddle.com/subscriptions/customers/manage/{sub.subscription_id}">{sub.subscription_id}</a> {sub.plan_name()} ends at {sub.next_bill_date}"""
)
else:
channels.append(
f"""Active Paddle Subscription <a href="https://vendors.paddle.com/subscriptions/customers/manage/{sub.subscription_id}">{sub.subscription_id}</a> {sub.plan_name()}, renews at {sub.next_bill_date}"""
)
apple_sub: AppleSubscription = AppleSubscription.get_by(user_id=self.id)
if apple_sub and apple_sub.is_valid():
channels.append(f"Apple Subscription {apple_sub.expires_date.humanize()}")
manual_sub: ManualSubscription = ManualSubscription.get_by(user_id=self.id)
if manual_sub and manual_sub.is_active():
mode = "Giveaway" if manual_sub.is_giveaway else "Paid"
channels.append(
f"Manual Subscription {manual_sub.comment} {mode} {manual_sub.end_at.humanize()}"
)
coinbase_subscription: CoinbaseSubscription = CoinbaseSubscription.get_by(
user_id=self.id
)
if coinbase_subscription and coinbase_subscription.is_active():
channels.append(
f"Coinbase Subscription ends {coinbase_subscription.end_at.humanize()}"
)
r = (
Session.query(PartnerSubscription, PartnerUser, Partner)
.filter(
PartnerSubscription.partner_user_id == PartnerUser.id,
PartnerUser.user_id == self.id,
Partner.id == PartnerUser.partner_id,
)
.first()
)
if r and r[0].is_active():
channels.append(
f"Subscription via {r[2].name} partner , ends {r[0].end_at.humanize()}"
)
return ".\n".join(channels)
# endregion
def max_alias_for_free_account(self) -> int:
if (
self.FLAG_FREE_OLD_ALIAS_LIMIT
== self.flags & self.FLAG_FREE_OLD_ALIAS_LIMIT
):
return config.MAX_NB_EMAIL_OLD_FREE_PLAN
else:
return config.MAX_NB_EMAIL_FREE_PLAN
def can_create_new_alias(self) -> bool:
"""
Whether user can create a new alias. User can't create a new alias if
- has more than 15 aliases in the free plan, *even in the free trial*
"""
if not self.is_active():
return False
if self.disabled:
return False
if self.lifetime_or_active_subscription():
return True
else:
return (
Alias.filter_by(user_id=self.id).count()
< self.max_alias_for_free_account()
)
def can_send_or_receive(self) -> bool:
if self.disabled:
LOG.i(f"User {self} is disabled. Cannot receive or send emails")
return False
if self.delete_on is not None:
LOG.i(
f"User {self} is scheduled to be deleted. Cannot receive or send emails"
)
return False
return True
def profile_picture_url(self):
if self.profile_picture_id:
return self.profile_picture.get_url()
else:
return url_for("static", filename="default-avatar.png")
def suggested_emails(self, website_name) -> (str, [str]):
"""return suggested email and other email choices"""
website_name = convert_to_id(website_name)
all_aliases = [
ge.email for ge in Alias.filter_by(user_id=self.id, enabled=True)
]
if self.can_create_new_alias():
suggested_alias = Alias.create_new(self, prefix=website_name).email
else:
# pick an email from the list of gen emails
suggested_alias = random.choice(all_aliases)
return (
suggested_alias,
list(set(all_aliases).difference({suggested_alias})),
)
def suggested_names(self) -> (str, [str]):
"""return suggested name and other name choices"""
other_name = convert_to_id(self.name)
return self.name, [other_name, "Anonymous", "whoami"]
def get_name_initial(self) -> str:
if not self.name:
return ""
names = self.name.split(" ")
return "".join([n[0].upper() for n in names if n])
def get_paddle_subscription(self) -> Optional["Subscription"]:
"""return *active* Paddle subscription
Return None if the subscription is already expired
TODO: support user unsubscribe and re-subscribe
"""
sub = Subscription.get_by(user_id=self.id)
if sub:
# grace period is 14 days
# sub is active until the next billing_date + PADDLE_SUBSCRIPTION_GRACE_DAYS
if (
sub.next_bill_date
>= arrow.now().shift(days=-PADDLE_SUBSCRIPTION_GRACE_DAYS).date()
):
return sub
# past subscription, user is considered not having a subscription = free plan
else:
return None
else:
return sub
def verified_custom_domains(self) -> List["CustomDomain"]:
return (
CustomDomain.filter_by(user_id=self.id, ownership_verified=True)
.order_by(CustomDomain.domain.asc())
.all()
)
def mailboxes(self) -> List["Mailbox"]:
"""list of mailbox that user own"""
mailboxes = []
for mailbox in Mailbox.filter_by(user_id=self.id, verified=True):
mailboxes.append(mailbox)
return mailboxes
def nb_directory(self):
return Directory.filter_by(user_id=self.id).count()
def has_custom_domain(self):
return CustomDomain.filter_by(user_id=self.id, verified=True).count() > 0
def custom_domains(self):
return CustomDomain.filter_by(user_id=self.id, verified=True).all()
def available_domains_for_random_alias(
self, alias_options: Optional[AliasOptions] = None
) -> List[Tuple[bool, str]]:
"""Return available domains for user to create random aliases
Each result record contains:
- whether the domain belongs to SimpleLogin
- the domain
"""
res = []
for domain in self.available_sl_domains(alias_options=alias_options):
res.append((True, domain))
for custom_domain in self.verified_custom_domains():
res.append((False, custom_domain.domain))
return res
def default_random_alias_domain(self) -> str:
"""return the domain used for the random alias"""
if self.default_alias_custom_domain_id:
custom_domain = CustomDomain.get(self.default_alias_custom_domain_id)
# sanity check
if (
not custom_domain
or not custom_domain.verified
or custom_domain.user_id != self.id
):
LOG.w("Problem with %s default random alias domain", self)
return config.FIRST_ALIAS_DOMAIN
return custom_domain.domain
if self.default_alias_public_domain_id:
sl_domain = SLDomain.get(self.default_alias_public_domain_id)
# sanity check
if not sl_domain:
LOG.e("Problem with %s public random alias domain", self)
return config.FIRST_ALIAS_DOMAIN
if sl_domain.premium_only and not self.is_premium():
LOG.w(
"%s is not premium and cannot use %s. Reset default random alias domain setting",
self,
sl_domain,
)
self.default_alias_custom_domain_id = None
self.default_alias_public_domain_id = None
Session.commit()
return config.FIRST_ALIAS_DOMAIN
return sl_domain.domain
return config.FIRST_ALIAS_DOMAIN
def fido_enabled(self) -> bool:
if self.fido_uuid is not None:
return True
return False
def two_factor_authentication_enabled(self) -> bool:
return self.enable_otp or self.fido_enabled()
def get_communication_email(self) -> (Optional[str], str, bool):
"""
Return
- the email that user uses to receive email communication. None if user unsubscribes from newsletter
- the unsubscribe URL
- whether the unsubscribe method is via sending email (mailto:) or Http POST
"""
if self.notification and self.activated and not self.disabled:
if self.newsletter_alias_id:
alias = Alias.get(self.newsletter_alias_id)
if alias.enabled:
unsub = UnsubscribeEncoder.encode(
UnsubscribeAction.DisableAlias, alias.id
)
return alias.email, unsub.link, unsub.via_email
# alias disabled -> user doesn't want to receive newsletter
else:
return None, "", False
else:
# do not handle http POST unsubscribe
if config.UNSUBSCRIBER:
# use * as suffix instead of = as for alias unsubscribe
return (
self.email,
UnsubscribeEncoder.encode_mailto(
UnsubscribeAction.UnsubscribeNewsletter, self.id
),
True,
)
return None, "", False
def available_sl_domains(
self, alias_options: Optional[AliasOptions] = None
) -> [str]:
"""
Return all SimpleLogin domains that user can use when creating a new alias, including:
- SimpleLogin public domains, available for all users (ALIAS_DOMAIN)
- SimpleLogin premium domains, only available for Premium accounts (PREMIUM_ALIAS_DOMAIN)
"""
return [
sl_domain.domain
for sl_domain in self.get_sl_domains(alias_options=alias_options)
]
def get_sl_domains(
self, alias_options: Optional[AliasOptions] = None
) -> list["SLDomain"]:
if alias_options is None:
alias_options = AliasOptions()
top_conds = [SLDomain.hidden == False] # noqa: E712
or_conds = [] # noqa:E711
if self.default_alias_public_domain_id is not None:
default_domain_conds = [SLDomain.id == self.default_alias_public_domain_id]
if not self.is_premium():
default_domain_conds.append(
SLDomain.premium_only == False # noqa: E712
)
or_conds.append(and_(*default_domain_conds).self_group())
if alias_options.show_partner_domains is not None:
partner_user = PartnerUser.filter_by(
user_id=self.id, partner_id=alias_options.show_partner_domains.id
).first()
if partner_user is not None:
partner_domain_cond = [SLDomain.partner_id == partner_user.partner_id]
if alias_options.show_partner_premium is None:
alias_options.show_partner_premium = self.is_premium()
if not alias_options.show_partner_premium:
partner_domain_cond.append(
SLDomain.premium_only == False # noqa: E712
)
or_conds.append(and_(*partner_domain_cond).self_group())
if alias_options.show_sl_domains:
sl_conds = [SLDomain.partner_id == None] # noqa: E711
if not self.is_premium():
sl_conds.append(SLDomain.premium_only == False) # noqa: E712
or_conds.append(and_(*sl_conds).self_group())
top_conds.append(or_(*or_conds))
query = Session.query(SLDomain).filter(*top_conds).order_by(SLDomain.order)
return query.all()
def available_alias_domains(
self, alias_options: Optional[AliasOptions] = None
) -> [str]:
"""return all domains that user can use when creating a new alias, including:
- SimpleLogin public domains, available for all users (ALIAS_DOMAIN)
- SimpleLogin premium domains, only available for Premium accounts (PREMIUM_ALIAS_DOMAIN)
- Verified custom domains
"""
domains = self.available_sl_domains(alias_options=alias_options)
for custom_domain in self.verified_custom_domains():
domains.append(custom_domain.domain)
# can have duplicate where a "root" user has a domain that's also listed in SL domains
return list(set(domains))
def should_show_app_page(self) -> bool:
"""whether to show the app page"""
return (
# when user has used the "Sign in with SL" button before
ClientUser.filter(ClientUser.user_id == self.id).count()
# or when user has created an app
+ Client.filter(Client.user_id == self.id).count()
> 0
)
def get_random_alias_suffix(self, custom_domain: Optional["CustomDomain"] = None):
"""Get random suffix for an alias based on user's preference.
Use a shorter suffix in case of custom domain
Returns:
str: the random suffix generated
"""
if self.random_alias_suffix == AliasSuffixEnum.random_string.value:
return random_string(config.ALIAS_RANDOM_SUFFIX_LENGTH, include_digits=True)
if custom_domain is None:
return random_words(1, 3)
return random_words(1)
def can_create_contacts(self) -> bool:
if self.is_premium():
return True
if self.flags & User.FLAG_FREE_DISABLE_CREATE_ALIAS == 0:
return True
return not config.DISABLE_CREATE_CONTACTS_FOR_FREE_USERS
def __repr__(self):
return f"<User {self.id} {self.name} {self.email}>"
class Alias(Base, ModelMixin):
__tablename__ = "alias"
FLAG_PARTNER_CREATED = 1 << 0
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, index=True
)
email = sa.Column(sa.String(128), unique=True, nullable=False)
# the name to use when user replies/sends from alias
name = sa.Column(sa.String(128), nullable=True, default=None)
enabled = sa.Column(sa.Boolean(), default=True, nullable=False)
flags = sa.Column(
sa.BigInteger(), default=0, server_default="0", nullable=False, index=True
)
custom_domain_id = sa.Column(
sa.ForeignKey("custom_domain.id", ondelete="cascade"), nullable=True, index=True
)
custom_domain = orm.relationship("CustomDomain", foreign_keys=[custom_domain_id])
# To know whether an alias is created "on the fly", i.e. via the custom domain catch-all feature
automatic_creation = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# to know whether an alias belongs to a directory
directory_id = sa.Column(
sa.ForeignKey("directory.id", ondelete="cascade"), nullable=True, index=True
)
note = sa.Column(sa.Text, default=None, nullable=True)
# an alias can be owned by another mailbox
mailbox_id = sa.Column(
sa.ForeignKey("mailbox.id", ondelete="cascade"), nullable=False, index=True
)
# prefix _ to avoid this object being used accidentally.
# To have the list of all mailboxes, should use AliasInfo instead
_mailboxes = orm.relationship("Mailbox", secondary="alias_mailbox", lazy="joined")
# If the mailbox has PGP-enabled, user can choose disable the PGP on the alias
# this is useful when some senders already support PGP
disable_pgp = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# a way to bypass the bounce automatic disable mechanism
cannot_be_disabled = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# when a mailbox wants to send an email on behalf of the alias via the reverse-alias
# several checks are performed to avoid email spoofing
# this option allow disabling these checks
disable_email_spoofing_check = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# to know whether an alias is added using a batch import
batch_import_id = sa.Column(
sa.ForeignKey("batch_import.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
# set in case of alias transfer.
original_owner_id = sa.Column(
sa.ForeignKey(User.id, ondelete="SET NULL"), nullable=True
)
# alias is pinned on top
pinned = sa.Column(sa.Boolean, nullable=False, default=False, server_default="0")
# used to transfer an alias to another user
transfer_token = sa.Column(sa.String(64), default=None, unique=True, nullable=True)
transfer_token_expiration = sa.Column(
ArrowType, default=arrow.utcnow, nullable=True
)
# have I been pwned
hibp_last_check = sa.Column(ArrowType, default=None, index=True)
hibp_breaches = orm.relationship("Hibp", secondary="alias_hibp")
# to use Postgres full text search. Only applied on "note" column for now
# this is a generated Postgres column
ts_vector = sa.Column(
TSVector(), sa.Computed("to_tsvector('english', note)", persisted=True)
)
last_email_log_id = sa.Column(sa.Integer, default=None, nullable=True)
__table_args__ = (
Index("ix_video___ts_vector__", ts_vector, postgresql_using="gin"),
# index on note column using pg_trgm
Index(
"note_pg_trgm_index",
"note",
postgresql_ops={"note": "gin_trgm_ops"},
postgresql_using="gin",
),
)
user = orm.relationship(User, foreign_keys=[user_id])
mailbox = orm.relationship("Mailbox", lazy="joined")
def mailboxes(self):
ret = [self.mailbox]
for m in self._mailboxes:
if m.id is not self.mailbox.id:
ret.append(m)
ret = [mb for mb in ret if mb.verified]
ret = sorted(ret, key=lambda mb: mb.email)
return ret
def authorized_addresses(self) -> [str]:
"""return addresses that can send on behalf of this alias, i.e. can send emails to this alias's reverse-aliases
Including its mailboxes and their authorized addresses
"""
mailboxes = self.mailboxes
ret = [mb.email for mb in mailboxes]
for mailbox in mailboxes:
for aa in mailbox.authorized_addresses:
ret.append(aa.email)
return ret
def mailbox_support_pgp(self) -> bool:
"""return True of one of the mailboxes support PGP"""
for mb in self.mailboxes:
if mb.pgp_enabled():
return True
return False
def pgp_enabled(self) -> bool:
if self.mailbox_support_pgp() and not self.disable_pgp:
return True
return False
def get_custom_domain(alias_address) -> Optional["CustomDomain"]:
alias_domain = validate_email(
alias_address, check_deliverability=False, allow_smtputf8=False
).domain
# handle the case a SLDomain is also a CustomDomain
if SLDomain.get_by(domain=alias_domain) is None:
custom_domain = CustomDomain.get_by(domain=alias_domain)
if custom_domain:
return custom_domain
def create(cls, **kw):
commit = kw.pop("commit", False)
flush = kw.pop("flush", False)
new_alias = cls(**kw)
user = User.get(new_alias.user_id)
if user.is_premium():
limits = config.ALIAS_CREATE_RATE_LIMIT_PAID
else:
limits = config.ALIAS_CREATE_RATE_LIMIT_FREE
# limits is array of (hits,days)
for limit in limits:
key = f"alias_create_{limit[1]}d:{user.id}"
rate_limiter.check_bucket_limit(key, limit[0], limit[1])
email = kw["email"]
# make sure email is lowercase and doesn't have any whitespace
email = sanitize_email(email)
# make sure alias is not in global trash, i.e. DeletedAlias table
if DeletedAlias.get_by(email=email):
raise AliasInTrashError
if DomainDeletedAlias.get_by(email=email):
raise AliasInTrashError
# detect whether alias should belong to a custom domain
if "custom_domain_id" not in kw:
custom_domain = Alias.get_custom_domain(email)
if custom_domain:
new_alias.custom_domain_id = custom_domain.id
Session.add(new_alias)
DailyMetric.get_or_create_today_metric().nb_alias += 1
if commit:
Session.commit()
if flush:
Session.flush()
return new_alias
def create_new(cls, user, prefix, note=None, mailbox_id=None):
prefix = prefix.lower().strip().replace(" ", "")
if not prefix:
raise Exception("alias prefix cannot be empty")
# find the right suffix - avoid infinite loop by running this at max 1000 times
for _ in range(1000):
suffix = user.get_random_alias_suffix()
email = f"{prefix}.{suffix}@{config.FIRST_ALIAS_DOMAIN}"
if available_sl_email(email):
break
return Alias.create(
user_id=user.id,
email=email,
note=note,
mailbox_id=mailbox_id or user.default_mailbox_id,
)
def delete(cls, obj_id):
raise Exception("should use delete_alias(alias,user) instead")
def create_new_random(
cls,
user,
scheme: int = AliasGeneratorEnum.word.value,
in_hex: bool = False,
note: str = None,
):
"""create a new random alias"""
custom_domain = None
random_email = None
if user.default_alias_custom_domain_id:
custom_domain = CustomDomain.get(user.default_alias_custom_domain_id)
random_email = generate_random_alias_email(
scheme=scheme, in_hex=in_hex, alias_domain=custom_domain.domain
)
elif user.default_alias_public_domain_id:
sl_domain: SLDomain = SLDomain.get(user.default_alias_public_domain_id)
if sl_domain.premium_only and not user.is_premium():
LOG.w("%s not premium, cannot use %s", user, sl_domain)
else:
random_email = generate_random_alias_email(
scheme=scheme, in_hex=in_hex, alias_domain=sl_domain.domain
)
if not random_email:
random_email = generate_random_alias_email(scheme=scheme, in_hex=in_hex)
alias = Alias.create(
user_id=user.id,
email=random_email,
mailbox_id=user.default_mailbox_id,
note=note,
)
if custom_domain:
alias.custom_domain_id = custom_domain.id
return alias
def mailbox_email(self):
if self.mailbox_id:
return self.mailbox.email
else:
return self.user.email
def __repr__(self):
return f"<Alias {self.id} {self.email}>"
The provided code snippet includes necessary dependencies for implementing the `notify_hibp` function. Write a Python function `def notify_hibp()` to solve the following problem:
Send aggregated email reports for HIBP breaches
Here is the function:
def notify_hibp():
"""
Send aggregated email reports for HIBP breaches
"""
# to get a list of users that have at least a breached alias
alias_query = (
Session.query(Alias)
.options(joinedload(Alias.hibp_breaches))
.filter(Alias.hibp_breaches.any())
.filter(Alias.id.notin_(Session.query(HibpNotifiedAlias.alias_id)))
.distinct(Alias.user_id)
.all()
)
user_ids = [alias.user_id for alias in alias_query]
for user in User.filter(User.id.in_(user_ids)):
breached_aliases = (
Session.query(Alias)
.options(joinedload(Alias.hibp_breaches))
.filter(Alias.hibp_breaches.any(), Alias.user_id == user.id)
.all()
)
LOG.d(
"Send new breaches found email to %s for %s breaches aliases",
user,
len(breached_aliases),
)
send_email(
user.email,
"You were in a data breach",
render(
"transactional/hibp-new-breaches.txt.jinja2",
user=user,
breached_aliases=breached_aliases,
),
render(
"transactional/hibp-new-breaches.html",
user=user,
breached_aliases=breached_aliases,
),
retries=3,
)
# add the breached aliases to HibpNotifiedAlias to avoid sending another email
for alias in breached_aliases:
HibpNotifiedAlias.create(user_id=user.id, alias_id=alias.id)
Session.commit() | Send aggregated email reports for HIBP breaches |
180,565 | import argparse
import asyncio
import urllib.parse
from typing import List, Tuple
import arrow
import requests
from sqlalchemy import func, desc, or_, and_
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.orm import joinedload
from sqlalchemy.orm.exc import ObjectDeletedError
from sqlalchemy.sql import Insert, text
from app import s3, config
from app.alias_utils import nb_email_log_for_mailbox
from app.api.views.apple import verify_receipt
from app.db import Session
from app.dns_utils import get_mx_domains, is_mx_equivalent
from app.email_utils import (
send_email,
send_trial_end_soon_email,
render,
email_can_be_used_as_mailbox,
send_email_with_rate_control,
get_email_domain_part,
)
from app.email_validation import is_valid_email, normalize_reply_email
from app.errors import ProtonPartnerNotSetUp
from app.log import LOG
from app.mail_sender import load_unsent_mails_from_fs_and_resend
from app.models import (
Subscription,
User,
Alias,
EmailLog,
CustomDomain,
Client,
ManualSubscription,
RefusedEmail,
AppleSubscription,
Mailbox,
Monitoring,
Contact,
CoinbaseSubscription,
TransactionalEmail,
Bounce,
Metric2,
SLDomain,
DeletedAlias,
DomainDeletedAlias,
Hibp,
HibpNotifiedAlias,
Directory,
DeletedDirectory,
DeletedSubdomain,
PartnerSubscription,
PartnerUser,
ApiToCookieToken,
)
from app.pgp_utils import load_public_key_and_check, PGPException
from app.proton.utils import get_proton_partner
from app.utils import sanitize_email
from server import create_light_app
from tasks.cleanup_old_imports import cleanup_old_imports
from tasks.cleanup_old_jobs import cleanup_old_jobs
from tasks.cleanup_old_notifications import cleanup_old_notifications
DELETE_GRACE_DAYS = 30
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
LOG = _get_logger("SL")
class User(Base, ModelMixin, UserMixin, PasswordOracle):
def directory_quota(self):
def subdomain_quota(self):
def created_by_partner(self):
def subdomain_is_available():
def get_id(self):
def create(cls, email, name="", password=None, from_partner=False, **kwargs):
def get_active_subscription(
self, include_partner_subscription: bool = True
) -> Optional[
Union[
Subscription
| AppleSubscription
| ManualSubscription
| CoinbaseSubscription
| PartnerSubscription
]
]:
def get_active_subscription_end(
self, include_partner_subscription: bool = True
) -> Optional[arrow.Arrow]:
def lifetime_or_active_subscription(
self, include_partner_subscription: bool = True
) -> bool:
def is_paid(self) -> bool:
def is_active(self) -> bool:
def in_trial(self):
def should_show_upgrade_button(self):
def is_premium(self, include_partner_subscription: bool = True) -> bool:
def upgrade_channel(self) -> str:
def max_alias_for_free_account(self) -> int:
def can_create_new_alias(self) -> bool:
def can_send_or_receive(self) -> bool:
def profile_picture_url(self):
def suggested_emails(self, website_name) -> (str, [str]):
def suggested_names(self) -> (str, [str]):
def get_name_initial(self) -> str:
def get_paddle_subscription(self) -> Optional["Subscription"]:
def verified_custom_domains(self) -> List["CustomDomain"]:
def mailboxes(self) -> List["Mailbox"]:
def nb_directory(self):
def has_custom_domain(self):
def custom_domains(self):
def available_domains_for_random_alias(
self, alias_options: Optional[AliasOptions] = None
) -> List[Tuple[bool, str]]:
def default_random_alias_domain(self) -> str:
def fido_enabled(self) -> bool:
def two_factor_authentication_enabled(self) -> bool:
def get_communication_email(self) -> (Optional[str], str, bool):
def available_sl_domains(
self, alias_options: Optional[AliasOptions] = None
) -> [str]:
def get_sl_domains(
self, alias_options: Optional[AliasOptions] = None
) -> list["SLDomain"]:
def available_alias_domains(
self, alias_options: Optional[AliasOptions] = None
) -> [str]:
def should_show_app_page(self) -> bool:
def get_random_alias_suffix(self, custom_domain: Optional["CustomDomain"] = None):
def can_create_contacts(self) -> bool:
def __repr__(self):
def clear_users_scheduled_to_be_deleted(dry_run=False):
users = User.filter(
and_(
User.delete_on.isnot(None),
User.delete_on <= arrow.now().shift(days=-DELETE_GRACE_DAYS),
)
).all()
for user in users:
LOG.i(
f"Scheduled deletion of user {user} with scheduled delete on {user.delete_on}"
)
if dry_run:
continue
User.delete(user.id)
Session.commit() | null |
180,566 | import argparse
import asyncio
import urllib.parse
from typing import List, Tuple
import arrow
import requests
from sqlalchemy import func, desc, or_, and_
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.orm import joinedload
from sqlalchemy.orm.exc import ObjectDeletedError
from sqlalchemy.sql import Insert, text
from app import s3, config
from app.alias_utils import nb_email_log_for_mailbox
from app.api.views.apple import verify_receipt
from app.db import Session
from app.dns_utils import get_mx_domains, is_mx_equivalent
from app.email_utils import (
send_email,
send_trial_end_soon_email,
render,
email_can_be_used_as_mailbox,
send_email_with_rate_control,
get_email_domain_part,
)
from app.email_validation import is_valid_email, normalize_reply_email
from app.errors import ProtonPartnerNotSetUp
from app.log import LOG
from app.mail_sender import load_unsent_mails_from_fs_and_resend
from app.models import (
Subscription,
User,
Alias,
EmailLog,
CustomDomain,
Client,
ManualSubscription,
RefusedEmail,
AppleSubscription,
Mailbox,
Monitoring,
Contact,
CoinbaseSubscription,
TransactionalEmail,
Bounce,
Metric2,
SLDomain,
DeletedAlias,
DomainDeletedAlias,
Hibp,
HibpNotifiedAlias,
Directory,
DeletedDirectory,
DeletedSubdomain,
PartnerSubscription,
PartnerUser,
ApiToCookieToken,
)
from app.pgp_utils import load_public_key_and_check, PGPException
from app.proton.utils import get_proton_partner
from app.utils import sanitize_email
from server import create_light_app
from tasks.cleanup_old_imports import cleanup_old_imports
from tasks.cleanup_old_jobs import cleanup_old_jobs
from tasks.cleanup_old_notifications import cleanup_old_notifications
def cleanup_old_imports(oldest_allowed: arrow.Arrow):
def cleanup_old_jobs(oldest_allowed: arrow.Arrow):
def cleanup_old_notifications(oldest_allowed: arrow.Arrow):
def delete_old_data():
oldest_valid = arrow.now().shift(days=-config.KEEP_OLD_DATA_DAYS)
cleanup_old_imports(oldest_valid)
cleanup_old_jobs(oldest_valid)
cleanup_old_notifications(oldest_valid) | null |
180,567 | import json
import os
import time
from datetime import timedelta
import arrow
import click
import flask_limiter
import flask_profiler
import sentry_sdk
from coinbase_commerce.error import WebhookInvalidPayload, SignatureVerificationError
from coinbase_commerce.webhook import Webhook
from dateutil.relativedelta import relativedelta
from flask import (
Flask,
redirect,
url_for,
render_template,
request,
jsonify,
flash,
session,
g,
)
from flask_admin import Admin
from flask_cors import cross_origin, CORS
from flask_login import current_user
from sentry_sdk.integrations.flask import FlaskIntegration
from sentry_sdk.integrations.sqlalchemy import SqlalchemyIntegration
from werkzeug.middleware.proxy_fix import ProxyFix
from app import paddle_utils, config, paddle_callback
from app.admin_model import (
SLAdminIndexView,
UserAdmin,
AliasAdmin,
MailboxAdmin,
ManualSubscriptionAdmin,
CouponAdmin,
CustomDomainAdmin,
AdminAuditLogAdmin,
ProviderComplaintAdmin,
NewsletterAdmin,
NewsletterUserAdmin,
DailyMetricAdmin,
MetricAdmin,
InvalidMailboxDomainAdmin,
)
from app.api.base import api_bp
from app.auth.base import auth_bp
from app.build_info import SHA1
from app.config import (
DB_URI,
FLASK_SECRET,
SENTRY_DSN,
URL,
PADDLE_MONTHLY_PRODUCT_ID,
FLASK_PROFILER_PATH,
FLASK_PROFILER_PASSWORD,
SENTRY_FRONT_END_DSN,
FIRST_ALIAS_DOMAIN,
SESSION_COOKIE_NAME,
PLAUSIBLE_HOST,
PLAUSIBLE_DOMAIN,
GITHUB_CLIENT_ID,
GOOGLE_CLIENT_ID,
FACEBOOK_CLIENT_ID,
LANDING_PAGE_URL,
STATUS_PAGE_URL,
SUPPORT_EMAIL,
PADDLE_MONTHLY_PRODUCT_IDS,
PADDLE_YEARLY_PRODUCT_IDS,
PGP_SIGNER,
COINBASE_WEBHOOK_SECRET,
PAGE_LIMIT,
PADDLE_COUPON_ID,
ZENDESK_ENABLED,
MAX_NB_EMAIL_FREE_PLAN,
MEM_STORE_URI,
)
from app.dashboard.base import dashboard_bp
from app.subscription_webhook import execute_subscription_webhook
from app.db import Session
from app.developer.base import developer_bp
from app.discover.base import discover_bp
from app.email_utils import send_email, render
from app.extensions import login_manager, limiter
from app.fake_data import fake_data
from app.internal.base import internal_bp
from app.jose_utils import get_jwk_key
from app.log import LOG
from app.models import (
User,
Alias,
Subscription,
PlanEnum,
CustomDomain,
Mailbox,
CoinbaseSubscription,
EmailLog,
Contact,
ManualSubscription,
Coupon,
AdminAuditLog,
ProviderComplaint,
Newsletter,
NewsletterUser,
DailyMetric,
Metric2,
InvalidMailboxDomain,
)
from app.monitor.base import monitor_bp
from app.newsletter_utils import send_newsletter_to_user
from app.oauth.base import oauth_bp
from app.onboarding.base import onboarding_bp
from app.phone.base import phone_bp
from app.redis_services import initialize_redis_services
from app.utils import random_string
DB_URI = os.environ["DB_URI"]
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
def create_light_app() -> Flask:
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = DB_URI
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
@app.teardown_appcontext
def shutdown_session(response_or_exc):
Session.remove()
return app | null |
180,568 | import json
import os
import time
from datetime import timedelta
import arrow
import click
import flask_limiter
import flask_profiler
import sentry_sdk
from coinbase_commerce.error import WebhookInvalidPayload, SignatureVerificationError
from coinbase_commerce.webhook import Webhook
from dateutil.relativedelta import relativedelta
from flask import (
Flask,
redirect,
url_for,
render_template,
request,
jsonify,
flash,
session,
g,
)
from flask_admin import Admin
from flask_cors import cross_origin, CORS
from flask_login import current_user
from sentry_sdk.integrations.flask import FlaskIntegration
from sentry_sdk.integrations.sqlalchemy import SqlalchemyIntegration
from werkzeug.middleware.proxy_fix import ProxyFix
from app import paddle_utils, config, paddle_callback
from app.admin_model import (
SLAdminIndexView,
UserAdmin,
AliasAdmin,
MailboxAdmin,
ManualSubscriptionAdmin,
CouponAdmin,
CustomDomainAdmin,
AdminAuditLogAdmin,
ProviderComplaintAdmin,
NewsletterAdmin,
NewsletterUserAdmin,
DailyMetricAdmin,
MetricAdmin,
InvalidMailboxDomainAdmin,
)
from app.api.base import api_bp
from app.auth.base import auth_bp
from app.build_info import SHA1
from app.config import (
DB_URI,
FLASK_SECRET,
SENTRY_DSN,
URL,
PADDLE_MONTHLY_PRODUCT_ID,
FLASK_PROFILER_PATH,
FLASK_PROFILER_PASSWORD,
SENTRY_FRONT_END_DSN,
FIRST_ALIAS_DOMAIN,
SESSION_COOKIE_NAME,
PLAUSIBLE_HOST,
PLAUSIBLE_DOMAIN,
GITHUB_CLIENT_ID,
GOOGLE_CLIENT_ID,
FACEBOOK_CLIENT_ID,
LANDING_PAGE_URL,
STATUS_PAGE_URL,
SUPPORT_EMAIL,
PADDLE_MONTHLY_PRODUCT_IDS,
PADDLE_YEARLY_PRODUCT_IDS,
PGP_SIGNER,
COINBASE_WEBHOOK_SECRET,
PAGE_LIMIT,
PADDLE_COUPON_ID,
ZENDESK_ENABLED,
MAX_NB_EMAIL_FREE_PLAN,
MEM_STORE_URI,
)
from app.dashboard.base import dashboard_bp
from app.subscription_webhook import execute_subscription_webhook
from app.db import Session
from app.developer.base import developer_bp
from app.discover.base import discover_bp
from app.email_utils import send_email, render
from app.extensions import login_manager, limiter
from app.fake_data import fake_data
from app.internal.base import internal_bp
from app.jose_utils import get_jwk_key
from app.log import LOG
from app.models import (
User,
Alias,
Subscription,
PlanEnum,
CustomDomain,
Mailbox,
CoinbaseSubscription,
EmailLog,
Contact,
ManualSubscription,
Coupon,
AdminAuditLog,
ProviderComplaint,
Newsletter,
NewsletterUser,
DailyMetric,
Metric2,
InvalidMailboxDomain,
)
from app.monitor.base import monitor_bp
from app.newsletter_utils import send_newsletter_to_user
from app.oauth.base import oauth_bp
from app.onboarding.base import onboarding_bp
from app.phone.base import phone_bp
from app.redis_services import initialize_redis_services
from app.utils import random_string
class User(Base, ModelMixin, UserMixin, PasswordOracle):
def directory_quota(self):
def subdomain_quota(self):
def created_by_partner(self):
def subdomain_is_available():
def get_id(self):
def create(cls, email, name="", password=None, from_partner=False, **kwargs):
def get_active_subscription(
self, include_partner_subscription: bool = True
) -> Optional[
Union[
Subscription
| AppleSubscription
| ManualSubscription
| CoinbaseSubscription
| PartnerSubscription
]
]:
def get_active_subscription_end(
self, include_partner_subscription: bool = True
) -> Optional[arrow.Arrow]:
def lifetime_or_active_subscription(
self, include_partner_subscription: bool = True
) -> bool:
def is_paid(self) -> bool:
def is_active(self) -> bool:
def in_trial(self):
def should_show_upgrade_button(self):
def is_premium(self, include_partner_subscription: bool = True) -> bool:
def upgrade_channel(self) -> str:
def max_alias_for_free_account(self) -> int:
def can_create_new_alias(self) -> bool:
def can_send_or_receive(self) -> bool:
def profile_picture_url(self):
def suggested_emails(self, website_name) -> (str, [str]):
def suggested_names(self) -> (str, [str]):
def get_name_initial(self) -> str:
def get_paddle_subscription(self) -> Optional["Subscription"]:
def verified_custom_domains(self) -> List["CustomDomain"]:
def mailboxes(self) -> List["Mailbox"]:
def nb_directory(self):
def has_custom_domain(self):
def custom_domains(self):
def available_domains_for_random_alias(
self, alias_options: Optional[AliasOptions] = None
) -> List[Tuple[bool, str]]:
def default_random_alias_domain(self) -> str:
def fido_enabled(self) -> bool:
def two_factor_authentication_enabled(self) -> bool:
def get_communication_email(self) -> (Optional[str], str, bool):
def available_sl_domains(
self, alias_options: Optional[AliasOptions] = None
) -> [str]:
def get_sl_domains(
self, alias_options: Optional[AliasOptions] = None
) -> list["SLDomain"]:
def available_alias_domains(
self, alias_options: Optional[AliasOptions] = None
) -> [str]:
def should_show_app_page(self) -> bool:
def get_random_alias_suffix(self, custom_domain: Optional["CustomDomain"] = None):
def can_create_contacts(self) -> bool:
def __repr__(self):
def load_user(alternative_id):
user = User.get_by(alternative_id=alternative_id)
if user:
sentry_sdk.set_user({"email": user.email, "id": user.id})
if user.disabled:
return None
if not user.is_active():
return None
return user | null |
180,569 | import json
import os
import time
from datetime import timedelta
import arrow
import click
import flask_limiter
import flask_profiler
import sentry_sdk
from coinbase_commerce.error import WebhookInvalidPayload, SignatureVerificationError
from coinbase_commerce.webhook import Webhook
from dateutil.relativedelta import relativedelta
from flask import (
Flask,
redirect,
url_for,
render_template,
request,
jsonify,
flash,
session,
g,
)
from flask_admin import Admin
from flask_cors import cross_origin, CORS
from flask_login import current_user
from sentry_sdk.integrations.flask import FlaskIntegration
from sentry_sdk.integrations.sqlalchemy import SqlalchemyIntegration
from werkzeug.middleware.proxy_fix import ProxyFix
from app import paddle_utils, config, paddle_callback
from app.admin_model import (
SLAdminIndexView,
UserAdmin,
AliasAdmin,
MailboxAdmin,
ManualSubscriptionAdmin,
CouponAdmin,
CustomDomainAdmin,
AdminAuditLogAdmin,
ProviderComplaintAdmin,
NewsletterAdmin,
NewsletterUserAdmin,
DailyMetricAdmin,
MetricAdmin,
InvalidMailboxDomainAdmin,
)
from app.api.base import api_bp
from app.auth.base import auth_bp
from app.build_info import SHA1
from app.config import (
DB_URI,
FLASK_SECRET,
SENTRY_DSN,
URL,
PADDLE_MONTHLY_PRODUCT_ID,
FLASK_PROFILER_PATH,
FLASK_PROFILER_PASSWORD,
SENTRY_FRONT_END_DSN,
FIRST_ALIAS_DOMAIN,
SESSION_COOKIE_NAME,
PLAUSIBLE_HOST,
PLAUSIBLE_DOMAIN,
GITHUB_CLIENT_ID,
GOOGLE_CLIENT_ID,
FACEBOOK_CLIENT_ID,
LANDING_PAGE_URL,
STATUS_PAGE_URL,
SUPPORT_EMAIL,
PADDLE_MONTHLY_PRODUCT_IDS,
PADDLE_YEARLY_PRODUCT_IDS,
PGP_SIGNER,
COINBASE_WEBHOOK_SECRET,
PAGE_LIMIT,
PADDLE_COUPON_ID,
ZENDESK_ENABLED,
MAX_NB_EMAIL_FREE_PLAN,
MEM_STORE_URI,
)
from app.dashboard.base import dashboard_bp
from app.subscription_webhook import execute_subscription_webhook
from app.db import Session
from app.developer.base import developer_bp
from app.discover.base import discover_bp
from app.email_utils import send_email, render
from app.extensions import login_manager, limiter
from app.fake_data import fake_data
from app.internal.base import internal_bp
from app.jose_utils import get_jwk_key
from app.log import LOG
from app.models import (
User,
Alias,
Subscription,
PlanEnum,
CustomDomain,
Mailbox,
CoinbaseSubscription,
EmailLog,
Contact,
ManualSubscription,
Coupon,
AdminAuditLog,
ProviderComplaint,
Newsletter,
NewsletterUser,
DailyMetric,
Metric2,
InvalidMailboxDomain,
)
from app.monitor.base import monitor_bp
from app.newsletter_utils import send_newsletter_to_user
from app.oauth.base import oauth_bp
from app.onboarding.base import onboarding_bp
from app.phone.base import phone_bp
from app.redis_services import initialize_redis_services
from app.utils import random_string
def create_app() -> Flask:
app = Flask(__name__)
# SimpleLogin is deployed behind NGINX
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_host=1)
app.url_map.strict_slashes = False
app.config["SQLALCHEMY_DATABASE_URI"] = DB_URI
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
# enable to print all queries generated by sqlalchemy
# app.config["SQLALCHEMY_ECHO"] = True
app.secret_key = FLASK_SECRET
app.config["TEMPLATES_AUTO_RELOAD"] = True
# to have a "fluid" layout for admin
app.config["FLASK_ADMIN_FLUID_LAYOUT"] = True
# to avoid conflict with other cookie
app.config["SESSION_COOKIE_NAME"] = SESSION_COOKIE_NAME
if URL.startswith("https"):
app.config["SESSION_COOKIE_SECURE"] = True
app.config["SESSION_COOKIE_SAMESITE"] = "Lax"
if MEM_STORE_URI:
app.config[flask_limiter.extension.C.STORAGE_URL] = MEM_STORE_URI
initialize_redis_services(app, MEM_STORE_URI)
limiter.init_app(app)
setup_error_page(app)
init_extensions(app)
register_blueprints(app)
set_index_page(app)
jinja2_filter(app)
setup_favicon_route(app)
setup_openid_metadata(app)
init_admin(app)
setup_paddle_callback(app)
setup_coinbase_commerce(app)
setup_do_not_track(app)
register_custom_commands(app)
if FLASK_PROFILER_PATH:
LOG.d("Enable flask-profiler")
app.config["flask_profiler"] = {
"enabled": True,
"storage": {"engine": "sqlite", "FILE": FLASK_PROFILER_PATH},
"basicAuth": {
"enabled": True,
"username": "admin",
"password": FLASK_PROFILER_PASSWORD,
},
"ignore": ["^/static/.*", "/git", "/exception"],
}
flask_profiler.init_app(app)
# enable CORS on /api endpoints
CORS(app, resources={r"/api/*": {"origins": "*"}})
# set session to permanent so user stays signed in after quitting the browser
# the cookie is valid for 7 days
def make_session_permanent():
session.permanent = True
app.permanent_session_lifetime = timedelta(days=7)
def cleanup(resp_or_exc):
Session.remove()
return app
def local_main():
config.COLOR_LOG = True
app = create_app()
# enable flask toolbar
from flask_debugtoolbar import DebugToolbarExtension
app.config["DEBUG_TB_PROFILER_ENABLED"] = True
app.config["DEBUG_TB_INTERCEPT_REDIRECTS"] = False
app.debug = True
DebugToolbarExtension(app)
# disable the sqlalchemy debug panels because of "IndexError: pop from empty list" from:
# duration = time.time() - conn.info['query_start_time'].pop(-1)
# app.config["DEBUG_TB_PANELS"] += ("flask_debugtoolbar_sqlalchemy.SQLAlchemyPanel",)
app.run(debug=True, port=7777)
# uncomment to run https locally
# LOG.d("enable https")
# import ssl
# context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
# context.load_cert_chain("local_data/cert.pem", "local_data/key.pem")
# app.run(debug=True, port=7777, ssl_context=context) | null |
180,570 | from app.log import LOG
from monitor.metric import UpcloudMetric, UpcloudMetrics, UpcloudRecord
import base64
import requests
from typing import Any
def get_metric(json: Any, metric: str) -> UpcloudMetric:
records = []
if metric in json:
metric_data = json[metric]
data = metric_data["data"]
cols = list(map(lambda x: x["label"], data["cols"][1:]))
latest = data["rows"][-1]
time = latest[0]
for column_idx in range(len(cols)):
value = latest[1 + column_idx]
# If the latest value is None, try to fetch the second to last
if value is None:
value = data["rows"][-2][1 + column_idx]
if value is not None:
label = cols[column_idx]
if "(master)" in label:
db_role = "master"
else:
db_role = "standby"
records.append(
UpcloudRecord(time=time, db_role=db_role, label=label, value=value)
)
else:
LOG.warn(f"Could not get value for metric {metric}")
return UpcloudMetric(metric_name=metric, records=records)
class UpcloudMetrics:
metrics: List[UpcloudMetric]
def get_metrics(json: Any) -> UpcloudMetrics:
return UpcloudMetrics(
metrics=[
get_metric(json, "cpu_usage"),
get_metric(json, "disk_usage"),
get_metric(json, "diskio_reads"),
get_metric(json, "diskio_writes"),
get_metric(json, "load_average"),
get_metric(json, "mem_usage"),
get_metric(json, "net_receive"),
get_metric(json, "net_send"),
]
) | null |
180,571 | import base64
import binascii
import enum
import hmac
import json
import os
import quopri
import random
import time
import uuid
from copy import deepcopy
from email import policy, message_from_bytes, message_from_string
from email.header import decode_header, Header
from email.message import Message, EmailMessage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import make_msgid, formatdate, formataddr
from smtplib import SMTP, SMTPException
from typing import Tuple, List, Optional, Union
import arrow
import dkim
import re2 as re
import spf
from aiosmtpd.smtp import Envelope
from cachetools import cached, TTLCache
from email_validator import (
validate_email,
EmailNotValidError,
ValidatedEmail,
)
from flanker.addresslib import address
from flanker.addresslib.address import EmailAddress
from jinja2 import Environment, FileSystemLoader
from sqlalchemy import func
from app import config
from app.db import Session
from app.dns_utils import get_mx_domains
from app.email import headers
from app.log import LOG
from app.mail_sender import sl_sendmail
from app.message_utils import message_to_bytes
from app.models import (
Mailbox,
User,
SentAlert,
CustomDomain,
SLDomain,
Contact,
Alias,
EmailLog,
TransactionalEmail,
IgnoreBounceSender,
InvalidMailboxDomain,
VerpType,
available_sl_email,
)
from app.utils import (
random_string,
convert_to_id,
convert_to_alphanumeric,
sanitize_email,
)
The provided code snippet includes necessary dependencies for implementing the `get_header_from_bounce` function. Write a Python function `def get_header_from_bounce(msg: Message, header: str) -> str` to solve the following problem:
using regex to get header value from bounce message get_orig_message_from_bounce is better. This should be the last option
Here is the function:
def get_header_from_bounce(msg: Message, header: str) -> str:
"""using regex to get header value from bounce message
get_orig_message_from_bounce is better. This should be the last option
"""
msg_str = str(msg)
exp = re.compile(f"{header}.*\n")
r = re.search(exp, msg_str)
if r:
# substr should be something like 'HEADER: 1234'
substr = msg_str[r.start() : r.end()].strip()
parts = substr.split(":")
return parts[1].strip()
return None | using regex to get header value from bounce message get_orig_message_from_bounce is better. This should be the last option |
180,572 | import base64
import binascii
import enum
import hmac
import json
import os
import quopri
import random
import time
import uuid
from copy import deepcopy
from email import policy, message_from_bytes, message_from_string
from email.header import decode_header, Header
from email.message import Message, EmailMessage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import make_msgid, formatdate, formataddr
from smtplib import SMTP, SMTPException
from typing import Tuple, List, Optional, Union
import arrow
import dkim
import re2 as re
import spf
from aiosmtpd.smtp import Envelope
from cachetools import cached, TTLCache
from email_validator import (
validate_email,
EmailNotValidError,
ValidatedEmail,
)
from flanker.addresslib import address
from flanker.addresslib.address import EmailAddress
from jinja2 import Environment, FileSystemLoader
from sqlalchemy import func
from app import config
from app.db import Session
from app.dns_utils import get_mx_domains
from app.email import headers
from app.log import LOG
from app.mail_sender import sl_sendmail
from app.message_utils import message_to_bytes
from app.models import (
Mailbox,
User,
SentAlert,
CustomDomain,
SLDomain,
Contact,
Alias,
EmailLog,
TransactionalEmail,
IgnoreBounceSender,
InvalidMailboxDomain,
VerpType,
available_sl_email,
)
from app.utils import (
random_string,
convert_to_id,
convert_to_alphanumeric,
sanitize_email,
)
LOG = _get_logger("SL")
def get_smtp_server():
LOG.d("get a smtp server")
if config.POSTFIX_SUBMISSION_TLS:
smtp = SMTP(config.POSTFIX_SERVER, 587)
smtp.starttls()
else:
smtp = SMTP(config.POSTFIX_SERVER, config.POSTFIX_PORT)
return smtp | null |
180,573 | import base64
import binascii
import enum
import hmac
import json
import os
import quopri
import random
import time
import uuid
from copy import deepcopy
from email import policy, message_from_bytes, message_from_string
from email.header import decode_header, Header
from email.message import Message, EmailMessage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import make_msgid, formatdate, formataddr
from smtplib import SMTP, SMTPException
from typing import Tuple, List, Optional, Union
import arrow
import dkim
import re2 as re
import spf
from aiosmtpd.smtp import Envelope
from cachetools import cached, TTLCache
from email_validator import (
validate_email,
EmailNotValidError,
ValidatedEmail,
)
from flanker.addresslib import address
from flanker.addresslib.address import EmailAddress
from jinja2 import Environment, FileSystemLoader
from sqlalchemy import func
from app import config
from app.db import Session
from app.dns_utils import get_mx_domains
from app.email import headers
from app.log import LOG
from app.mail_sender import sl_sendmail
from app.message_utils import message_to_bytes
from app.models import (
Mailbox,
User,
SentAlert,
CustomDomain,
SLDomain,
Contact,
Alias,
EmailLog,
TransactionalEmail,
IgnoreBounceSender,
InvalidMailboxDomain,
VerpType,
available_sl_email,
)
from app.utils import (
random_string,
convert_to_id,
convert_to_alphanumeric,
sanitize_email,
)
def parse_full_address(full_address) -> (str, str):
"""
parse the email address full format and return the display name and address
For ex: ab <cd@xy.com> -> (ab, cd@xy.com)
'=?UTF-8?B?TmjGoW4gTmd1eeG7hW4=?= <abcd@gmail.com>' -> ('Nhơn Nguyễn', "abcd@gmail.com")
If the parsing fails, raise ValueError
"""
full_address: EmailAddress = address.parse(full_address)
if full_address is None:
raise ValueError
# address.parse can also parse a URL and return UrlAddress
if type(full_address) is not EmailAddress:
raise ValueError
return full_address.display_name, full_address.address
The provided code snippet includes necessary dependencies for implementing the `parse_address_list` function. Write a Python function `def parse_address_list(address_list: str) -> List[Tuple[str, str]]` to solve the following problem:
Parse a list of email addresses from a header in the form "ab <ab@sd.com>, cd <cd@cd.com>" and return a list [("ab", "ab@sd.com"),("cd", "cd@cd.com")]
Here is the function:
def parse_address_list(address_list: str) -> List[Tuple[str, str]]:
"""
Parse a list of email addresses from a header in the form "ab <ab@sd.com>, cd <cd@cd.com>"
and return a list [("ab", "ab@sd.com"),("cd", "cd@cd.com")]
"""
processed_addresses = []
for split_address in address_list.split(","):
split_address = split_address.strip()
if not split_address:
continue
processed_addresses.append(parse_full_address(split_address))
return processed_addresses | Parse a list of email addresses from a header in the form "ab <ab@sd.com>, cd <cd@cd.com>" and return a list [("ab", "ab@sd.com"),("cd", "cd@cd.com")] |
180,574 | import base64
import binascii
import enum
import hmac
import json
import os
import quopri
import random
import time
import uuid
from copy import deepcopy
from email import policy, message_from_bytes, message_from_string
from email.header import decode_header, Header
from email.message import Message, EmailMessage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import make_msgid, formatdate, formataddr
from smtplib import SMTP, SMTPException
from typing import Tuple, List, Optional, Union
import arrow
import dkim
import re2 as re
import spf
from aiosmtpd.smtp import Envelope
from cachetools import cached, TTLCache
from email_validator import (
validate_email,
EmailNotValidError,
ValidatedEmail,
)
from flanker.addresslib import address
from flanker.addresslib.address import EmailAddress
from jinja2 import Environment, FileSystemLoader
from sqlalchemy import func
from app import config
from app.db import Session
from app.dns_utils import get_mx_domains
from app.email import headers
from app.log import LOG
from app.mail_sender import sl_sendmail
from app.message_utils import message_to_bytes
from app.models import (
Mailbox,
User,
SentAlert,
CustomDomain,
SLDomain,
Contact,
Alias,
EmailLog,
TransactionalEmail,
IgnoreBounceSender,
InvalidMailboxDomain,
VerpType,
available_sl_email,
)
from app.utils import (
random_string,
convert_to_id,
convert_to_alphanumeric,
sanitize_email,
)
LOG = _get_logger("SL")
The provided code snippet includes necessary dependencies for implementing the `save_envelope_for_debugging` function. Write a Python function `def save_envelope_for_debugging(envelope: Envelope, file_name_prefix=None) -> str` to solve the following problem:
Save envelope for debugging to temporary location Return the file path
Here is the function:
def save_envelope_for_debugging(envelope: Envelope, file_name_prefix=None) -> str:
"""Save envelope for debugging to temporary location
Return the file path
"""
if config.TEMP_DIR:
file_name = str(uuid.uuid4()) + ".eml"
if file_name_prefix:
file_name = "{}-{}".format(file_name_prefix, file_name)
with open(os.path.join(config.TEMP_DIR, file_name), "wb") as f:
f.write(envelope.original_content)
LOG.d("envelope saved to %s", file_name)
return file_name
return "" | Save envelope for debugging to temporary location Return the file path |
180,575 | from flask import g
from flask import jsonify
from app.api.base import api_bp, require_api_auth
from app.models import Alias, Client, CustomDomain
from app.alias_utils import alias_export_csv
class Client(Base, ModelMixin):
__tablename__ = "client"
oauth_client_id = sa.Column(sa.String(128), unique=True, nullable=False)
oauth_client_secret = sa.Column(sa.String(128), nullable=False)
name = sa.Column(sa.String(128), nullable=False)
home_url = sa.Column(sa.String(1024))
# user who created this client
user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False)
icon_id = sa.Column(sa.ForeignKey(File.id), nullable=True)
# an app needs to be approved by SimpleLogin team
approved = sa.Column(sa.Boolean, nullable=False, default=False, server_default="0")
description = sa.Column(sa.Text, nullable=True)
# a referral can be attached to a client
# so all users who sign up via the authorize screen are counted towards this referral
referral_id = sa.Column(
sa.ForeignKey("referral.id", ondelete="SET NULL"), nullable=True
)
icon = orm.relationship(File)
user = orm.relationship(User)
referral = orm.relationship("Referral")
def nb_user(self):
return ClientUser.filter_by(client_id=self.id).count()
def get_scopes(self) -> [Scope]:
# todo: client can choose which scopes they want to have access
return [Scope.NAME, Scope.EMAIL, Scope.AVATAR_URL]
def create_new(cls, name, user_id) -> "Client":
# generate a client-id
oauth_client_id = generate_oauth_client_id(name)
oauth_client_secret = random_string(40)
client = Client.create(
name=name,
oauth_client_id=oauth_client_id,
oauth_client_secret=oauth_client_secret,
user_id=user_id,
)
return client
def get_icon_url(self):
if self.icon_id:
return self.icon.get_url()
else:
return config.URL + "/static/default-icon.svg"
def last_user_login(self) -> "ClientUser":
client_user = (
ClientUser.filter(ClientUser.client_id == self.id)
.order_by(ClientUser.updated_at)
.first()
)
if client_user:
return client_user
return None
class Alias(Base, ModelMixin):
__tablename__ = "alias"
FLAG_PARTNER_CREATED = 1 << 0
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, index=True
)
email = sa.Column(sa.String(128), unique=True, nullable=False)
# the name to use when user replies/sends from alias
name = sa.Column(sa.String(128), nullable=True, default=None)
enabled = sa.Column(sa.Boolean(), default=True, nullable=False)
flags = sa.Column(
sa.BigInteger(), default=0, server_default="0", nullable=False, index=True
)
custom_domain_id = sa.Column(
sa.ForeignKey("custom_domain.id", ondelete="cascade"), nullable=True, index=True
)
custom_domain = orm.relationship("CustomDomain", foreign_keys=[custom_domain_id])
# To know whether an alias is created "on the fly", i.e. via the custom domain catch-all feature
automatic_creation = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# to know whether an alias belongs to a directory
directory_id = sa.Column(
sa.ForeignKey("directory.id", ondelete="cascade"), nullable=True, index=True
)
note = sa.Column(sa.Text, default=None, nullable=True)
# an alias can be owned by another mailbox
mailbox_id = sa.Column(
sa.ForeignKey("mailbox.id", ondelete="cascade"), nullable=False, index=True
)
# prefix _ to avoid this object being used accidentally.
# To have the list of all mailboxes, should use AliasInfo instead
_mailboxes = orm.relationship("Mailbox", secondary="alias_mailbox", lazy="joined")
# If the mailbox has PGP-enabled, user can choose disable the PGP on the alias
# this is useful when some senders already support PGP
disable_pgp = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# a way to bypass the bounce automatic disable mechanism
cannot_be_disabled = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# when a mailbox wants to send an email on behalf of the alias via the reverse-alias
# several checks are performed to avoid email spoofing
# this option allow disabling these checks
disable_email_spoofing_check = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# to know whether an alias is added using a batch import
batch_import_id = sa.Column(
sa.ForeignKey("batch_import.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
# set in case of alias transfer.
original_owner_id = sa.Column(
sa.ForeignKey(User.id, ondelete="SET NULL"), nullable=True
)
# alias is pinned on top
pinned = sa.Column(sa.Boolean, nullable=False, default=False, server_default="0")
# used to transfer an alias to another user
transfer_token = sa.Column(sa.String(64), default=None, unique=True, nullable=True)
transfer_token_expiration = sa.Column(
ArrowType, default=arrow.utcnow, nullable=True
)
# have I been pwned
hibp_last_check = sa.Column(ArrowType, default=None, index=True)
hibp_breaches = orm.relationship("Hibp", secondary="alias_hibp")
# to use Postgres full text search. Only applied on "note" column for now
# this is a generated Postgres column
ts_vector = sa.Column(
TSVector(), sa.Computed("to_tsvector('english', note)", persisted=True)
)
last_email_log_id = sa.Column(sa.Integer, default=None, nullable=True)
__table_args__ = (
Index("ix_video___ts_vector__", ts_vector, postgresql_using="gin"),
# index on note column using pg_trgm
Index(
"note_pg_trgm_index",
"note",
postgresql_ops={"note": "gin_trgm_ops"},
postgresql_using="gin",
),
)
user = orm.relationship(User, foreign_keys=[user_id])
mailbox = orm.relationship("Mailbox", lazy="joined")
def mailboxes(self):
ret = [self.mailbox]
for m in self._mailboxes:
if m.id is not self.mailbox.id:
ret.append(m)
ret = [mb for mb in ret if mb.verified]
ret = sorted(ret, key=lambda mb: mb.email)
return ret
def authorized_addresses(self) -> [str]:
"""return addresses that can send on behalf of this alias, i.e. can send emails to this alias's reverse-aliases
Including its mailboxes and their authorized addresses
"""
mailboxes = self.mailboxes
ret = [mb.email for mb in mailboxes]
for mailbox in mailboxes:
for aa in mailbox.authorized_addresses:
ret.append(aa.email)
return ret
def mailbox_support_pgp(self) -> bool:
"""return True of one of the mailboxes support PGP"""
for mb in self.mailboxes:
if mb.pgp_enabled():
return True
return False
def pgp_enabled(self) -> bool:
if self.mailbox_support_pgp() and not self.disable_pgp:
return True
return False
def get_custom_domain(alias_address) -> Optional["CustomDomain"]:
alias_domain = validate_email(
alias_address, check_deliverability=False, allow_smtputf8=False
).domain
# handle the case a SLDomain is also a CustomDomain
if SLDomain.get_by(domain=alias_domain) is None:
custom_domain = CustomDomain.get_by(domain=alias_domain)
if custom_domain:
return custom_domain
def create(cls, **kw):
commit = kw.pop("commit", False)
flush = kw.pop("flush", False)
new_alias = cls(**kw)
user = User.get(new_alias.user_id)
if user.is_premium():
limits = config.ALIAS_CREATE_RATE_LIMIT_PAID
else:
limits = config.ALIAS_CREATE_RATE_LIMIT_FREE
# limits is array of (hits,days)
for limit in limits:
key = f"alias_create_{limit[1]}d:{user.id}"
rate_limiter.check_bucket_limit(key, limit[0], limit[1])
email = kw["email"]
# make sure email is lowercase and doesn't have any whitespace
email = sanitize_email(email)
# make sure alias is not in global trash, i.e. DeletedAlias table
if DeletedAlias.get_by(email=email):
raise AliasInTrashError
if DomainDeletedAlias.get_by(email=email):
raise AliasInTrashError
# detect whether alias should belong to a custom domain
if "custom_domain_id" not in kw:
custom_domain = Alias.get_custom_domain(email)
if custom_domain:
new_alias.custom_domain_id = custom_domain.id
Session.add(new_alias)
DailyMetric.get_or_create_today_metric().nb_alias += 1
if commit:
Session.commit()
if flush:
Session.flush()
return new_alias
def create_new(cls, user, prefix, note=None, mailbox_id=None):
prefix = prefix.lower().strip().replace(" ", "")
if not prefix:
raise Exception("alias prefix cannot be empty")
# find the right suffix - avoid infinite loop by running this at max 1000 times
for _ in range(1000):
suffix = user.get_random_alias_suffix()
email = f"{prefix}.{suffix}@{config.FIRST_ALIAS_DOMAIN}"
if available_sl_email(email):
break
return Alias.create(
user_id=user.id,
email=email,
note=note,
mailbox_id=mailbox_id or user.default_mailbox_id,
)
def delete(cls, obj_id):
raise Exception("should use delete_alias(alias,user) instead")
def create_new_random(
cls,
user,
scheme: int = AliasGeneratorEnum.word.value,
in_hex: bool = False,
note: str = None,
):
"""create a new random alias"""
custom_domain = None
random_email = None
if user.default_alias_custom_domain_id:
custom_domain = CustomDomain.get(user.default_alias_custom_domain_id)
random_email = generate_random_alias_email(
scheme=scheme, in_hex=in_hex, alias_domain=custom_domain.domain
)
elif user.default_alias_public_domain_id:
sl_domain: SLDomain = SLDomain.get(user.default_alias_public_domain_id)
if sl_domain.premium_only and not user.is_premium():
LOG.w("%s not premium, cannot use %s", user, sl_domain)
else:
random_email = generate_random_alias_email(
scheme=scheme, in_hex=in_hex, alias_domain=sl_domain.domain
)
if not random_email:
random_email = generate_random_alias_email(scheme=scheme, in_hex=in_hex)
alias = Alias.create(
user_id=user.id,
email=random_email,
mailbox_id=user.default_mailbox_id,
note=note,
)
if custom_domain:
alias.custom_domain_id = custom_domain.id
return alias
def mailbox_email(self):
if self.mailbox_id:
return self.mailbox.email
else:
return self.user.email
def __repr__(self):
return f"<Alias {self.id} {self.email}>"
class CustomDomain(Base, ModelMixin):
__tablename__ = "custom_domain"
user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False)
domain = sa.Column(sa.String(128), unique=True, nullable=False)
# default name to use when user replies/sends from alias
name = sa.Column(sa.String(128), nullable=True, default=None)
# mx verified
verified = sa.Column(sa.Boolean, nullable=False, default=False)
dkim_verified = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
spf_verified = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
dmarc_verified = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
_mailboxes = orm.relationship("Mailbox", secondary="domain_mailbox", lazy="joined")
# an alias is created automatically the first time it receives an email
catch_all = sa.Column(sa.Boolean, nullable=False, default=False, server_default="0")
# option to generate random prefix version automatically
random_prefix_generation = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# incremented when a check is failed on the domain
# alert when the number exceeds a threshold
# used in check_custom_domain()
nb_failed_checks = sa.Column(
sa.Integer, default=0, server_default="0", nullable=False
)
# only domain has the ownership verified can go the next DNS step
# MX verified domains before this change don't have to do the TXT check
# and therefore have ownership_verified=True
ownership_verified = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# randomly generated TXT value for verifying domain ownership
# the TXT record should be sl-verification=txt_token
ownership_txt_token = sa.Column(sa.String(128), nullable=True)
# if the domain is SimpleLogin subdomain, no need for the ownership, SPF, DKIM, DMARC check
is_sl_subdomain = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
__table_args__ = (
Index(
"ix_unique_domain", # Index name
"domain", # Columns which are part of the index
unique=True,
postgresql_where=Column("ownership_verified"),
), # The condition
)
user = orm.relationship(User, foreign_keys=[user_id], backref="custom_domains")
def mailboxes(self):
if self._mailboxes:
return self._mailboxes
else:
return [self.user.default_mailbox]
def nb_alias(self):
return Alias.filter_by(custom_domain_id=self.id).count()
def get_trash_url(self):
return config.URL + f"/dashboard/domains/{self.id}/trash"
def get_ownership_dns_txt_value(self):
return f"sl-verification={self.ownership_txt_token}"
def create(cls, **kwargs):
domain = kwargs.get("domain")
kwargs["domain"] = domain.replace("\n", "")
if DeletedSubdomain.get_by(domain=domain):
raise SubdomainInTrashError
domain: CustomDomain = super(CustomDomain, cls).create(**kwargs)
# generate a domain ownership txt token
if not domain.ownership_txt_token:
domain.ownership_txt_token = random_string(30)
Session.commit()
if domain.is_sl_subdomain:
user = domain.user
user._subdomain_quota -= 1
Session.flush()
return domain
def delete(cls, obj_id):
obj: CustomDomain = cls.get(obj_id)
if obj.is_sl_subdomain:
DeletedSubdomain.create(domain=obj.domain)
return super(CustomDomain, cls).delete(obj_id)
def auto_create_rules(self):
return sorted(self._auto_create_rules, key=lambda rule: rule.order)
def __repr__(self):
return f"<Custom Domain {self.domain}>"
The provided code snippet includes necessary dependencies for implementing the `export_data` function. Write a Python function `def export_data()` to solve the following problem:
Get user data Output: Alias, custom domain and app info
Here is the function:
def export_data():
"""
Get user data
Output:
Alias, custom domain and app info
"""
user = g.user
data = {
"email": user.email,
"name": user.name,
"aliases": [],
"apps": [],
"custom_domains": [],
}
for alias in Alias.filter_by(user_id=user.id).all(): # type: Alias
data["aliases"].append(dict(email=alias.email, enabled=alias.enabled))
for custom_domain in CustomDomain.filter_by(user_id=user.id).all():
data["custom_domains"].append(custom_domain.domain)
for app in Client.filter_by(user_id=user.id): # type: Client
data["apps"].append(dict(name=app.name, home_url=app.home_url))
return jsonify(data) | Get user data Output: Alias, custom domain and app info |
180,576 | from flask import g
from flask import jsonify
from app.api.base import api_bp, require_api_auth
from app.models import Alias, Client, CustomDomain
from app.alias_utils import alias_export_csv
def alias_export_csv(user, csv_direct_export=False):
"""
Get user aliases as importable CSV file
Output:
Importable CSV file
"""
data = [["alias", "note", "enabled", "mailboxes"]]
for alias in Alias.filter_by(user_id=user.id).all(): # type: Alias
# Always put the main mailbox first
# It is seen a primary while importing
alias_mailboxes = alias.mailboxes
alias_mailboxes.insert(
0, alias_mailboxes.pop(alias_mailboxes.index(alias.mailbox))
)
mailboxes = " ".join([mailbox.email for mailbox in alias_mailboxes])
data.append([alias.email, alias.note, alias.enabled, mailboxes])
si = StringIO()
cw = csv.writer(si)
cw.writerows(data)
if csv_direct_export:
return si.getvalue()
output = make_response(si.getvalue())
output.headers["Content-Disposition"] = "attachment; filename=aliases.csv"
output.headers["Content-type"] = "text/csv"
return output
The provided code snippet includes necessary dependencies for implementing the `export_aliases` function. Write a Python function `def export_aliases()` to solve the following problem:
Get user aliases as importable CSV file Output: Importable CSV file
Here is the function:
def export_aliases():
"""
Get user aliases as importable CSV file
Output:
Importable CSV file
"""
return alias_export_csv(g.user) | Get user aliases as importable CSV file Output: Importable CSV file |
180,577 | from flask import g
from flask import jsonify, request
from app import parallel_limiter
from app.alias_suffix import check_suffix_signature, verify_prefix_suffix
from app.alias_utils import check_alias_prefix
from app.api.base import api_bp, require_api_auth
from app.api.serializer import (
serialize_alias_info_v2,
get_alias_info_v2,
)
from app.config import MAX_NB_EMAIL_FREE_PLAN, ALIAS_LIMIT
from app.db import Session
from app.extensions import limiter
from app.log import LOG
from app.models import (
Alias,
AliasUsedOn,
User,
DeletedAlias,
DomainDeletedAlias,
Mailbox,
AliasMailbox,
)
from app.utils import convert_to_id
def check_suffix_signature(signed_suffix: str) -> Optional[str]:
# hypothesis: user will click on the button in the 600 secs
try:
return signer.unsign(signed_suffix, max_age=600).decode()
except itsdangerous.BadSignature:
return None
def verify_prefix_suffix(
user: User, alias_prefix, alias_suffix, alias_options: Optional[AliasOptions] = None
) -> bool:
"""verify if user could create an alias with the given prefix and suffix"""
if not alias_prefix or not alias_suffix: # should be caught on frontend
return False
user_custom_domains = [cd.domain for cd in user.verified_custom_domains()]
# make sure alias_suffix is either .random_word@simplelogin.co or @my-domain.com
alias_suffix = alias_suffix.strip()
# alias_domain_prefix is either a .random_word or ""
alias_domain_prefix, alias_domain = alias_suffix.split("@", 1)
# alias_domain must be either one of user custom domains or built-in domains
if alias_domain not in user.available_alias_domains(alias_options=alias_options):
LOG.e("wrong alias suffix %s, user %s", alias_suffix, user)
return False
# SimpleLogin domain case:
# 1) alias_suffix must start with "." and
# 2) alias_domain_prefix must come from the word list
if (
alias_domain in user.available_sl_domains(alias_options=alias_options)
and alias_domain not in user_custom_domains
# when DISABLE_ALIAS_SUFFIX is true, alias_domain_prefix is empty
and not config.DISABLE_ALIAS_SUFFIX
):
if not alias_domain_prefix.startswith("."):
LOG.e("User %s submits a wrong alias suffix %s", user, alias_suffix)
return False
else:
if alias_domain not in user_custom_domains:
if not config.DISABLE_ALIAS_SUFFIX:
LOG.e("wrong alias suffix %s, user %s", alias_suffix, user)
return False
if alias_domain not in user.available_sl_domains(
alias_options=alias_options
):
LOG.e("wrong alias suffix %s, user %s", alias_suffix, user)
return False
return True
def serialize_alias_info_v2(alias_info: AliasInfo) -> dict:
res = {
# Alias field
"id": alias_info.alias.id,
"email": alias_info.alias.email,
"creation_date": alias_info.alias.created_at.format(),
"creation_timestamp": alias_info.alias.created_at.timestamp,
"enabled": alias_info.alias.enabled,
"note": alias_info.alias.note,
"name": alias_info.alias.name,
# activity
"nb_forward": alias_info.nb_forward,
"nb_block": alias_info.nb_blocked,
"nb_reply": alias_info.nb_reply,
# mailbox
"mailbox": {"id": alias_info.mailbox.id, "email": alias_info.mailbox.email},
"mailboxes": [
{"id": mailbox.id, "email": mailbox.email}
for mailbox in alias_info.mailboxes
],
"support_pgp": alias_info.alias.mailbox_support_pgp(),
"disable_pgp": alias_info.alias.disable_pgp,
"latest_activity": None,
"pinned": alias_info.alias.pinned,
}
if alias_info.latest_email_log:
email_log = alias_info.latest_email_log
contact = alias_info.latest_contact
# latest activity
res["latest_activity"] = {
"timestamp": email_log.created_at.timestamp,
"action": email_log.get_action(),
"contact": {
"email": contact.website_email,
"name": contact.name,
"reverse_alias": contact.website_send_to(),
},
}
return res
def get_alias_info_v2(alias: Alias, mailbox=None) -> AliasInfo:
if not mailbox:
mailbox = alias.mailbox
q = (
Session.query(Contact, EmailLog)
.filter(Contact.alias_id == alias.id)
.filter(EmailLog.contact_id == Contact.id)
)
latest_activity: Arrow = alias.created_at
latest_email_log = None
latest_contact = None
alias_info = AliasInfo(
alias=alias,
nb_blocked=0,
nb_forward=0,
nb_reply=0,
mailbox=mailbox,
mailboxes=[mailbox],
)
for m in alias._mailboxes:
alias_info.mailboxes.append(m)
# remove duplicates
# can happen that alias.mailbox_id also appears in AliasMailbox table
alias_info.mailboxes = list(set(alias_info.mailboxes))
for contact, email_log in q:
if email_log.is_reply:
alias_info.nb_reply += 1
elif email_log.blocked:
alias_info.nb_blocked += 1
else:
alias_info.nb_forward += 1
if email_log.created_at > latest_activity:
latest_activity = email_log.created_at
latest_email_log = email_log
latest_contact = contact
alias_info.latest_contact = latest_contact
alias_info.latest_email_log = latest_email_log
return alias_info
try:
MAX_NB_EMAIL_FREE_PLAN = int(os.environ["MAX_NB_EMAIL_FREE_PLAN"])
except Exception:
print("MAX_NB_EMAIL_FREE_PLAN is not set, use 5 as default value")
MAX_NB_EMAIL_FREE_PLAN = 5
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
LOG = _get_logger("SL")
class User(Base, ModelMixin, UserMixin, PasswordOracle):
__tablename__ = "users"
FLAG_FREE_DISABLE_CREATE_ALIAS = 1 << 0
FLAG_CREATED_FROM_PARTNER = 1 << 1
FLAG_FREE_OLD_ALIAS_LIMIT = 1 << 2
email = sa.Column(sa.String(256), unique=True, nullable=False)
name = sa.Column(sa.String(128), nullable=True)
is_admin = sa.Column(sa.Boolean, nullable=False, default=False)
alias_generator = sa.Column(
sa.Integer,
nullable=False,
default=AliasGeneratorEnum.word.value,
server_default=str(AliasGeneratorEnum.word.value),
)
notification = sa.Column(
sa.Boolean, default=True, nullable=False, server_default="1"
)
activated = sa.Column(sa.Boolean, default=False, nullable=False, index=True)
# an account can be disabled if having harmful behavior
disabled = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0")
profile_picture_id = sa.Column(sa.ForeignKey(File.id), nullable=True)
otp_secret = sa.Column(sa.String(16), nullable=True)
enable_otp = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
last_otp = sa.Column(sa.String(12), nullable=True, default=False)
# Fields for WebAuthn
fido_uuid = sa.Column(sa.String(), nullable=True, unique=True)
# the default domain that's used when user creates a new random alias
# default_alias_custom_domain_id XOR default_alias_public_domain_id
default_alias_custom_domain_id = sa.Column(
sa.ForeignKey("custom_domain.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
default_alias_public_domain_id = sa.Column(
sa.ForeignKey("public_domain.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
# some users could have lifetime premium
lifetime = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0")
paid_lifetime = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
lifetime_coupon_id = sa.Column(
sa.ForeignKey("lifetime_coupon.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
# user can use all premium features until this date
trial_end = sa.Column(
ArrowType, default=lambda: arrow.now().shift(days=7, hours=1), nullable=True
)
# the mailbox used when create random alias
# this field is nullable but in practice, it's always set
# it cannot be set to non-nullable though
# as this will create foreign key cycle between User and Mailbox
default_mailbox_id = sa.Column(
sa.ForeignKey("mailbox.id"), nullable=True, default=None
)
profile_picture = orm.relationship(File, foreign_keys=[profile_picture_id])
# Specify the format for sender address
# for the full list, see SenderFormatEnum
sender_format = sa.Column(
sa.Integer, default="0", nullable=False, server_default="0"
)
# to know whether user has explicitly chosen a sender format as opposed to those who use the default ones.
# users who haven't chosen a sender format and are using 1 or 3 format, their sender format will be set to 0
sender_format_updated_at = sa.Column(ArrowType, default=None)
replace_reverse_alias = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
referral_id = sa.Column(
sa.ForeignKey("referral.id", ondelete="SET NULL"),
nullable=True,
default=None,
index=True,
)
referral = orm.relationship("Referral", foreign_keys=[referral_id])
# whether intro has been shown to user
intro_shown = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
default_mailbox = orm.relationship("Mailbox", foreign_keys=[default_mailbox_id])
# user can set a more strict max_spam score to block spams more aggressively
max_spam_score = sa.Column(sa.Integer, nullable=True)
# newsletter is sent to this address
newsletter_alias_id = sa.Column(
sa.ForeignKey("alias.id", ondelete="SET NULL"),
nullable=True,
default=None,
index=True,
)
# whether to include the sender address in reverse-alias
include_sender_in_reverse_alias = sa.Column(
sa.Boolean, default=True, nullable=False, server_default="0"
)
# whether to use random string or random word as suffix
# Random word from dictionary file -> 0
# Completely random string -> 1
random_alias_suffix = sa.Column(
sa.Integer,
nullable=False,
default=AliasSuffixEnum.word.value,
server_default=str(AliasSuffixEnum.random_string.value),
)
# always expand the alias info, i.e. without needing to press "More"
expand_alias_info = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# ignore emails send from a mailbox to its alias. This can happen when replying all to a forwarded email
# can automatically re-includes the alias
ignore_loop_email = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# used for flask-login as an "alternative token"
# cf https://flask-login.readthedocs.io/en/latest/#alternative-tokens
alternative_id = sa.Column(sa.String(128), unique=True, nullable=True)
# by default, when an alias is automatically created, a note like "Created with ...." is created
# If this field is True, the note won't be created.
disable_automatic_alias_note = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# By default, the one-click unsubscribe disable the alias
# If set to true, it will block the sender instead
one_click_unsubscribe_block_sender = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# automatically include the website name when user creates an alias via the SimpleLogin icon in the email field
include_website_in_one_click_alias = sa.Column(
sa.Boolean,
# new user will have this option turned on automatically
default=True,
nullable=False,
# old user will have this option turned off
server_default="0",
)
_directory_quota = sa.Column(
"directory_quota", sa.Integer, default=50, nullable=False, server_default="50"
)
_subdomain_quota = sa.Column(
"subdomain_quota", sa.Integer, default=5, nullable=False, server_default="5"
)
# user can use import to import too many aliases
disable_import = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# user can use the phone feature
can_use_phone = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# in minutes
phone_quota = sa.Column(sa.Integer, nullable=True)
# Status code to return if is blocked
block_behaviour = sa.Column(
sa.Enum(BlockBehaviourEnum),
nullable=False,
server_default=BlockBehaviourEnum.return_2xx.name,
)
include_header_email_header = sa.Column(
sa.Boolean, default=True, nullable=False, server_default="1"
)
# bitwise flags. Allow for future expansion
flags = sa.Column(
sa.BigInteger,
default=FLAG_FREE_DISABLE_CREATE_ALIAS,
server_default="0",
nullable=False,
)
# Keep original unsub behaviour
unsub_behaviour = sa.Column(
IntEnumType(UnsubscribeBehaviourEnum),
default=UnsubscribeBehaviourEnum.PreserveOriginal,
server_default=str(UnsubscribeBehaviourEnum.DisableAlias.value),
nullable=False,
)
# Trigger hard deletion of the account at this time
delete_on = sa.Column(ArrowType, default=None)
__table_args__ = (
sa.Index(
"ix_users_activated_trial_end_lifetime", activated, trial_end, lifetime
),
sa.Index("ix_users_delete_on", delete_on),
)
def directory_quota(self):
return min(
self._directory_quota,
config.MAX_NB_DIRECTORY - Directory.filter_by(user_id=self.id).count(),
)
def subdomain_quota(self):
return min(
self._subdomain_quota,
config.MAX_NB_SUBDOMAIN
- CustomDomain.filter_by(user_id=self.id, is_sl_subdomain=True).count(),
)
def created_by_partner(self):
return User.FLAG_CREATED_FROM_PARTNER == (
self.flags & User.FLAG_CREATED_FROM_PARTNER
)
def subdomain_is_available():
return SLDomain.filter_by(can_use_subdomain=True).count() > 0
# implement flask-login "alternative token"
def get_id(self):
if self.alternative_id:
return self.alternative_id
else:
return str(self.id)
def create(cls, email, name="", password=None, from_partner=False, **kwargs):
email = sanitize_email(email)
user: User = super(User, cls).create(email=email, name=name[:100], **kwargs)
if password:
user.set_password(password)
Session.flush()
mb = Mailbox.create(user_id=user.id, email=user.email, verified=True)
Session.flush()
user.default_mailbox_id = mb.id
# generate an alternative_id if needed
if "alternative_id" not in kwargs:
user.alternative_id = str(uuid.uuid4())
# If the user is created from partner, do not notify
# nor give a trial
if from_partner:
user.flags = User.FLAG_CREATED_FROM_PARTNER
user.notification = False
user.trial_end = None
Job.create(
name=config.JOB_SEND_PROTON_WELCOME_1,
payload={"user_id": user.id},
run_at=arrow.now(),
)
Session.flush()
return user
# create a first alias mail to show user how to use when they login
alias = Alias.create_new(
user,
prefix="simplelogin-newsletter",
mailbox_id=mb.id,
note="This is your first alias. It's used to receive SimpleLogin communications "
"like new features announcements, newsletters.",
)
Session.flush()
user.newsletter_alias_id = alias.id
Session.flush()
if config.DISABLE_ONBOARDING:
LOG.d("Disable onboarding emails")
return user
# Schedule onboarding emails
Job.create(
name=config.JOB_ONBOARDING_1,
payload={"user_id": user.id},
run_at=arrow.now().shift(days=1),
)
Job.create(
name=config.JOB_ONBOARDING_2,
payload={"user_id": user.id},
run_at=arrow.now().shift(days=2),
)
Job.create(
name=config.JOB_ONBOARDING_4,
payload={"user_id": user.id},
run_at=arrow.now().shift(days=3),
)
Session.flush()
return user
def get_active_subscription(
self, include_partner_subscription: bool = True
) -> Optional[
Union[
Subscription
| AppleSubscription
| ManualSubscription
| CoinbaseSubscription
| PartnerSubscription
]
]:
sub: Subscription = self.get_paddle_subscription()
if sub:
return sub
apple_sub: AppleSubscription = AppleSubscription.get_by(user_id=self.id)
if apple_sub and apple_sub.is_valid():
return apple_sub
manual_sub: ManualSubscription = ManualSubscription.get_by(user_id=self.id)
if manual_sub and manual_sub.is_active():
return manual_sub
coinbase_subscription: CoinbaseSubscription = CoinbaseSubscription.get_by(
user_id=self.id
)
if coinbase_subscription and coinbase_subscription.is_active():
return coinbase_subscription
if include_partner_subscription:
partner_sub: PartnerSubscription = PartnerSubscription.find_by_user_id(
self.id
)
if partner_sub and partner_sub.is_active():
return partner_sub
return None
def get_active_subscription_end(
self, include_partner_subscription: bool = True
) -> Optional[arrow.Arrow]:
sub = self.get_active_subscription(
include_partner_subscription=include_partner_subscription
)
if isinstance(sub, Subscription):
return arrow.get(sub.next_bill_date)
if isinstance(sub, AppleSubscription):
return sub.expires_date
if isinstance(sub, ManualSubscription):
return sub.end_at
if isinstance(sub, CoinbaseSubscription):
return sub.end_at
return None
# region Billing
def lifetime_or_active_subscription(
self, include_partner_subscription: bool = True
) -> bool:
"""True if user has lifetime licence or active subscription"""
if self.lifetime:
return True
return self.get_active_subscription(include_partner_subscription) is not None
def is_paid(self) -> bool:
"""same as _lifetime_or_active_subscription but not include free manual subscription"""
sub = self.get_active_subscription()
if sub is None:
return False
if isinstance(sub, ManualSubscription) and sub.is_giveaway:
return False
return True
def is_active(self) -> bool:
if self.delete_on is None:
return True
return self.delete_on < arrow.now()
def in_trial(self):
"""return True if user does not have lifetime licence or an active subscription AND is in trial period"""
if self.lifetime_or_active_subscription():
return False
if self.trial_end and arrow.now() < self.trial_end:
return True
return False
def should_show_upgrade_button(self):
if self.lifetime_or_active_subscription():
return False
return True
def is_premium(self, include_partner_subscription: bool = True) -> bool:
"""
user is premium if they:
- have a lifetime deal or
- in trial period or
- active subscription
"""
if self.lifetime_or_active_subscription(include_partner_subscription):
return True
if self.trial_end and arrow.now() < self.trial_end:
return True
return False
def upgrade_channel(self) -> str:
"""Used on admin dashboard"""
# user can have multiple subscription channel
channels = []
if self.lifetime:
channels.append("Lifetime")
sub: Subscription = self.get_paddle_subscription()
if sub:
if sub.cancelled:
channels.append(
f"""Cancelled Paddle Subscription <a href="https://vendors.paddle.com/subscriptions/customers/manage/{sub.subscription_id}">{sub.subscription_id}</a> {sub.plan_name()} ends at {sub.next_bill_date}"""
)
else:
channels.append(
f"""Active Paddle Subscription <a href="https://vendors.paddle.com/subscriptions/customers/manage/{sub.subscription_id}">{sub.subscription_id}</a> {sub.plan_name()}, renews at {sub.next_bill_date}"""
)
apple_sub: AppleSubscription = AppleSubscription.get_by(user_id=self.id)
if apple_sub and apple_sub.is_valid():
channels.append(f"Apple Subscription {apple_sub.expires_date.humanize()}")
manual_sub: ManualSubscription = ManualSubscription.get_by(user_id=self.id)
if manual_sub and manual_sub.is_active():
mode = "Giveaway" if manual_sub.is_giveaway else "Paid"
channels.append(
f"Manual Subscription {manual_sub.comment} {mode} {manual_sub.end_at.humanize()}"
)
coinbase_subscription: CoinbaseSubscription = CoinbaseSubscription.get_by(
user_id=self.id
)
if coinbase_subscription and coinbase_subscription.is_active():
channels.append(
f"Coinbase Subscription ends {coinbase_subscription.end_at.humanize()}"
)
r = (
Session.query(PartnerSubscription, PartnerUser, Partner)
.filter(
PartnerSubscription.partner_user_id == PartnerUser.id,
PartnerUser.user_id == self.id,
Partner.id == PartnerUser.partner_id,
)
.first()
)
if r and r[0].is_active():
channels.append(
f"Subscription via {r[2].name} partner , ends {r[0].end_at.humanize()}"
)
return ".\n".join(channels)
# endregion
def max_alias_for_free_account(self) -> int:
if (
self.FLAG_FREE_OLD_ALIAS_LIMIT
== self.flags & self.FLAG_FREE_OLD_ALIAS_LIMIT
):
return config.MAX_NB_EMAIL_OLD_FREE_PLAN
else:
return config.MAX_NB_EMAIL_FREE_PLAN
def can_create_new_alias(self) -> bool:
"""
Whether user can create a new alias. User can't create a new alias if
- has more than 15 aliases in the free plan, *even in the free trial*
"""
if not self.is_active():
return False
if self.disabled:
return False
if self.lifetime_or_active_subscription():
return True
else:
return (
Alias.filter_by(user_id=self.id).count()
< self.max_alias_for_free_account()
)
def can_send_or_receive(self) -> bool:
if self.disabled:
LOG.i(f"User {self} is disabled. Cannot receive or send emails")
return False
if self.delete_on is not None:
LOG.i(
f"User {self} is scheduled to be deleted. Cannot receive or send emails"
)
return False
return True
def profile_picture_url(self):
if self.profile_picture_id:
return self.profile_picture.get_url()
else:
return url_for("static", filename="default-avatar.png")
def suggested_emails(self, website_name) -> (str, [str]):
"""return suggested email and other email choices"""
website_name = convert_to_id(website_name)
all_aliases = [
ge.email for ge in Alias.filter_by(user_id=self.id, enabled=True)
]
if self.can_create_new_alias():
suggested_alias = Alias.create_new(self, prefix=website_name).email
else:
# pick an email from the list of gen emails
suggested_alias = random.choice(all_aliases)
return (
suggested_alias,
list(set(all_aliases).difference({suggested_alias})),
)
def suggested_names(self) -> (str, [str]):
"""return suggested name and other name choices"""
other_name = convert_to_id(self.name)
return self.name, [other_name, "Anonymous", "whoami"]
def get_name_initial(self) -> str:
if not self.name:
return ""
names = self.name.split(" ")
return "".join([n[0].upper() for n in names if n])
def get_paddle_subscription(self) -> Optional["Subscription"]:
"""return *active* Paddle subscription
Return None if the subscription is already expired
TODO: support user unsubscribe and re-subscribe
"""
sub = Subscription.get_by(user_id=self.id)
if sub:
# grace period is 14 days
# sub is active until the next billing_date + PADDLE_SUBSCRIPTION_GRACE_DAYS
if (
sub.next_bill_date
>= arrow.now().shift(days=-PADDLE_SUBSCRIPTION_GRACE_DAYS).date()
):
return sub
# past subscription, user is considered not having a subscription = free plan
else:
return None
else:
return sub
def verified_custom_domains(self) -> List["CustomDomain"]:
return (
CustomDomain.filter_by(user_id=self.id, ownership_verified=True)
.order_by(CustomDomain.domain.asc())
.all()
)
def mailboxes(self) -> List["Mailbox"]:
"""list of mailbox that user own"""
mailboxes = []
for mailbox in Mailbox.filter_by(user_id=self.id, verified=True):
mailboxes.append(mailbox)
return mailboxes
def nb_directory(self):
return Directory.filter_by(user_id=self.id).count()
def has_custom_domain(self):
return CustomDomain.filter_by(user_id=self.id, verified=True).count() > 0
def custom_domains(self):
return CustomDomain.filter_by(user_id=self.id, verified=True).all()
def available_domains_for_random_alias(
self, alias_options: Optional[AliasOptions] = None
) -> List[Tuple[bool, str]]:
"""Return available domains for user to create random aliases
Each result record contains:
- whether the domain belongs to SimpleLogin
- the domain
"""
res = []
for domain in self.available_sl_domains(alias_options=alias_options):
res.append((True, domain))
for custom_domain in self.verified_custom_domains():
res.append((False, custom_domain.domain))
return res
def default_random_alias_domain(self) -> str:
"""return the domain used for the random alias"""
if self.default_alias_custom_domain_id:
custom_domain = CustomDomain.get(self.default_alias_custom_domain_id)
# sanity check
if (
not custom_domain
or not custom_domain.verified
or custom_domain.user_id != self.id
):
LOG.w("Problem with %s default random alias domain", self)
return config.FIRST_ALIAS_DOMAIN
return custom_domain.domain
if self.default_alias_public_domain_id:
sl_domain = SLDomain.get(self.default_alias_public_domain_id)
# sanity check
if not sl_domain:
LOG.e("Problem with %s public random alias domain", self)
return config.FIRST_ALIAS_DOMAIN
if sl_domain.premium_only and not self.is_premium():
LOG.w(
"%s is not premium and cannot use %s. Reset default random alias domain setting",
self,
sl_domain,
)
self.default_alias_custom_domain_id = None
self.default_alias_public_domain_id = None
Session.commit()
return config.FIRST_ALIAS_DOMAIN
return sl_domain.domain
return config.FIRST_ALIAS_DOMAIN
def fido_enabled(self) -> bool:
if self.fido_uuid is not None:
return True
return False
def two_factor_authentication_enabled(self) -> bool:
return self.enable_otp or self.fido_enabled()
def get_communication_email(self) -> (Optional[str], str, bool):
"""
Return
- the email that user uses to receive email communication. None if user unsubscribes from newsletter
- the unsubscribe URL
- whether the unsubscribe method is via sending email (mailto:) or Http POST
"""
if self.notification and self.activated and not self.disabled:
if self.newsletter_alias_id:
alias = Alias.get(self.newsletter_alias_id)
if alias.enabled:
unsub = UnsubscribeEncoder.encode(
UnsubscribeAction.DisableAlias, alias.id
)
return alias.email, unsub.link, unsub.via_email
# alias disabled -> user doesn't want to receive newsletter
else:
return None, "", False
else:
# do not handle http POST unsubscribe
if config.UNSUBSCRIBER:
# use * as suffix instead of = as for alias unsubscribe
return (
self.email,
UnsubscribeEncoder.encode_mailto(
UnsubscribeAction.UnsubscribeNewsletter, self.id
),
True,
)
return None, "", False
def available_sl_domains(
self, alias_options: Optional[AliasOptions] = None
) -> [str]:
"""
Return all SimpleLogin domains that user can use when creating a new alias, including:
- SimpleLogin public domains, available for all users (ALIAS_DOMAIN)
- SimpleLogin premium domains, only available for Premium accounts (PREMIUM_ALIAS_DOMAIN)
"""
return [
sl_domain.domain
for sl_domain in self.get_sl_domains(alias_options=alias_options)
]
def get_sl_domains(
self, alias_options: Optional[AliasOptions] = None
) -> list["SLDomain"]:
if alias_options is None:
alias_options = AliasOptions()
top_conds = [SLDomain.hidden == False] # noqa: E712
or_conds = [] # noqa:E711
if self.default_alias_public_domain_id is not None:
default_domain_conds = [SLDomain.id == self.default_alias_public_domain_id]
if not self.is_premium():
default_domain_conds.append(
SLDomain.premium_only == False # noqa: E712
)
or_conds.append(and_(*default_domain_conds).self_group())
if alias_options.show_partner_domains is not None:
partner_user = PartnerUser.filter_by(
user_id=self.id, partner_id=alias_options.show_partner_domains.id
).first()
if partner_user is not None:
partner_domain_cond = [SLDomain.partner_id == partner_user.partner_id]
if alias_options.show_partner_premium is None:
alias_options.show_partner_premium = self.is_premium()
if not alias_options.show_partner_premium:
partner_domain_cond.append(
SLDomain.premium_only == False # noqa: E712
)
or_conds.append(and_(*partner_domain_cond).self_group())
if alias_options.show_sl_domains:
sl_conds = [SLDomain.partner_id == None] # noqa: E711
if not self.is_premium():
sl_conds.append(SLDomain.premium_only == False) # noqa: E712
or_conds.append(and_(*sl_conds).self_group())
top_conds.append(or_(*or_conds))
query = Session.query(SLDomain).filter(*top_conds).order_by(SLDomain.order)
return query.all()
def available_alias_domains(
self, alias_options: Optional[AliasOptions] = None
) -> [str]:
"""return all domains that user can use when creating a new alias, including:
- SimpleLogin public domains, available for all users (ALIAS_DOMAIN)
- SimpleLogin premium domains, only available for Premium accounts (PREMIUM_ALIAS_DOMAIN)
- Verified custom domains
"""
domains = self.available_sl_domains(alias_options=alias_options)
for custom_domain in self.verified_custom_domains():
domains.append(custom_domain.domain)
# can have duplicate where a "root" user has a domain that's also listed in SL domains
return list(set(domains))
def should_show_app_page(self) -> bool:
"""whether to show the app page"""
return (
# when user has used the "Sign in with SL" button before
ClientUser.filter(ClientUser.user_id == self.id).count()
# or when user has created an app
+ Client.filter(Client.user_id == self.id).count()
> 0
)
def get_random_alias_suffix(self, custom_domain: Optional["CustomDomain"] = None):
"""Get random suffix for an alias based on user's preference.
Use a shorter suffix in case of custom domain
Returns:
str: the random suffix generated
"""
if self.random_alias_suffix == AliasSuffixEnum.random_string.value:
return random_string(config.ALIAS_RANDOM_SUFFIX_LENGTH, include_digits=True)
if custom_domain is None:
return random_words(1, 3)
return random_words(1)
def can_create_contacts(self) -> bool:
if self.is_premium():
return True
if self.flags & User.FLAG_FREE_DISABLE_CREATE_ALIAS == 0:
return True
return not config.DISABLE_CREATE_CONTACTS_FOR_FREE_USERS
def __repr__(self):
return f"<User {self.id} {self.name} {self.email}>"
class Alias(Base, ModelMixin):
__tablename__ = "alias"
FLAG_PARTNER_CREATED = 1 << 0
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, index=True
)
email = sa.Column(sa.String(128), unique=True, nullable=False)
# the name to use when user replies/sends from alias
name = sa.Column(sa.String(128), nullable=True, default=None)
enabled = sa.Column(sa.Boolean(), default=True, nullable=False)
flags = sa.Column(
sa.BigInteger(), default=0, server_default="0", nullable=False, index=True
)
custom_domain_id = sa.Column(
sa.ForeignKey("custom_domain.id", ondelete="cascade"), nullable=True, index=True
)
custom_domain = orm.relationship("CustomDomain", foreign_keys=[custom_domain_id])
# To know whether an alias is created "on the fly", i.e. via the custom domain catch-all feature
automatic_creation = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# to know whether an alias belongs to a directory
directory_id = sa.Column(
sa.ForeignKey("directory.id", ondelete="cascade"), nullable=True, index=True
)
note = sa.Column(sa.Text, default=None, nullable=True)
# an alias can be owned by another mailbox
mailbox_id = sa.Column(
sa.ForeignKey("mailbox.id", ondelete="cascade"), nullable=False, index=True
)
# prefix _ to avoid this object being used accidentally.
# To have the list of all mailboxes, should use AliasInfo instead
_mailboxes = orm.relationship("Mailbox", secondary="alias_mailbox", lazy="joined")
# If the mailbox has PGP-enabled, user can choose disable the PGP on the alias
# this is useful when some senders already support PGP
disable_pgp = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# a way to bypass the bounce automatic disable mechanism
cannot_be_disabled = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# when a mailbox wants to send an email on behalf of the alias via the reverse-alias
# several checks are performed to avoid email spoofing
# this option allow disabling these checks
disable_email_spoofing_check = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# to know whether an alias is added using a batch import
batch_import_id = sa.Column(
sa.ForeignKey("batch_import.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
# set in case of alias transfer.
original_owner_id = sa.Column(
sa.ForeignKey(User.id, ondelete="SET NULL"), nullable=True
)
# alias is pinned on top
pinned = sa.Column(sa.Boolean, nullable=False, default=False, server_default="0")
# used to transfer an alias to another user
transfer_token = sa.Column(sa.String(64), default=None, unique=True, nullable=True)
transfer_token_expiration = sa.Column(
ArrowType, default=arrow.utcnow, nullable=True
)
# have I been pwned
hibp_last_check = sa.Column(ArrowType, default=None, index=True)
hibp_breaches = orm.relationship("Hibp", secondary="alias_hibp")
# to use Postgres full text search. Only applied on "note" column for now
# this is a generated Postgres column
ts_vector = sa.Column(
TSVector(), sa.Computed("to_tsvector('english', note)", persisted=True)
)
last_email_log_id = sa.Column(sa.Integer, default=None, nullable=True)
__table_args__ = (
Index("ix_video___ts_vector__", ts_vector, postgresql_using="gin"),
# index on note column using pg_trgm
Index(
"note_pg_trgm_index",
"note",
postgresql_ops={"note": "gin_trgm_ops"},
postgresql_using="gin",
),
)
user = orm.relationship(User, foreign_keys=[user_id])
mailbox = orm.relationship("Mailbox", lazy="joined")
def mailboxes(self):
ret = [self.mailbox]
for m in self._mailboxes:
if m.id is not self.mailbox.id:
ret.append(m)
ret = [mb for mb in ret if mb.verified]
ret = sorted(ret, key=lambda mb: mb.email)
return ret
def authorized_addresses(self) -> [str]:
"""return addresses that can send on behalf of this alias, i.e. can send emails to this alias's reverse-aliases
Including its mailboxes and their authorized addresses
"""
mailboxes = self.mailboxes
ret = [mb.email for mb in mailboxes]
for mailbox in mailboxes:
for aa in mailbox.authorized_addresses:
ret.append(aa.email)
return ret
def mailbox_support_pgp(self) -> bool:
"""return True of one of the mailboxes support PGP"""
for mb in self.mailboxes:
if mb.pgp_enabled():
return True
return False
def pgp_enabled(self) -> bool:
if self.mailbox_support_pgp() and not self.disable_pgp:
return True
return False
def get_custom_domain(alias_address) -> Optional["CustomDomain"]:
alias_domain = validate_email(
alias_address, check_deliverability=False, allow_smtputf8=False
).domain
# handle the case a SLDomain is also a CustomDomain
if SLDomain.get_by(domain=alias_domain) is None:
custom_domain = CustomDomain.get_by(domain=alias_domain)
if custom_domain:
return custom_domain
def create(cls, **kw):
commit = kw.pop("commit", False)
flush = kw.pop("flush", False)
new_alias = cls(**kw)
user = User.get(new_alias.user_id)
if user.is_premium():
limits = config.ALIAS_CREATE_RATE_LIMIT_PAID
else:
limits = config.ALIAS_CREATE_RATE_LIMIT_FREE
# limits is array of (hits,days)
for limit in limits:
key = f"alias_create_{limit[1]}d:{user.id}"
rate_limiter.check_bucket_limit(key, limit[0], limit[1])
email = kw["email"]
# make sure email is lowercase and doesn't have any whitespace
email = sanitize_email(email)
# make sure alias is not in global trash, i.e. DeletedAlias table
if DeletedAlias.get_by(email=email):
raise AliasInTrashError
if DomainDeletedAlias.get_by(email=email):
raise AliasInTrashError
# detect whether alias should belong to a custom domain
if "custom_domain_id" not in kw:
custom_domain = Alias.get_custom_domain(email)
if custom_domain:
new_alias.custom_domain_id = custom_domain.id
Session.add(new_alias)
DailyMetric.get_or_create_today_metric().nb_alias += 1
if commit:
Session.commit()
if flush:
Session.flush()
return new_alias
def create_new(cls, user, prefix, note=None, mailbox_id=None):
prefix = prefix.lower().strip().replace(" ", "")
if not prefix:
raise Exception("alias prefix cannot be empty")
# find the right suffix - avoid infinite loop by running this at max 1000 times
for _ in range(1000):
suffix = user.get_random_alias_suffix()
email = f"{prefix}.{suffix}@{config.FIRST_ALIAS_DOMAIN}"
if available_sl_email(email):
break
return Alias.create(
user_id=user.id,
email=email,
note=note,
mailbox_id=mailbox_id or user.default_mailbox_id,
)
def delete(cls, obj_id):
raise Exception("should use delete_alias(alias,user) instead")
def create_new_random(
cls,
user,
scheme: int = AliasGeneratorEnum.word.value,
in_hex: bool = False,
note: str = None,
):
"""create a new random alias"""
custom_domain = None
random_email = None
if user.default_alias_custom_domain_id:
custom_domain = CustomDomain.get(user.default_alias_custom_domain_id)
random_email = generate_random_alias_email(
scheme=scheme, in_hex=in_hex, alias_domain=custom_domain.domain
)
elif user.default_alias_public_domain_id:
sl_domain: SLDomain = SLDomain.get(user.default_alias_public_domain_id)
if sl_domain.premium_only and not user.is_premium():
LOG.w("%s not premium, cannot use %s", user, sl_domain)
else:
random_email = generate_random_alias_email(
scheme=scheme, in_hex=in_hex, alias_domain=sl_domain.domain
)
if not random_email:
random_email = generate_random_alias_email(scheme=scheme, in_hex=in_hex)
alias = Alias.create(
user_id=user.id,
email=random_email,
mailbox_id=user.default_mailbox_id,
note=note,
)
if custom_domain:
alias.custom_domain_id = custom_domain.id
return alias
def mailbox_email(self):
if self.mailbox_id:
return self.mailbox.email
else:
return self.user.email
def __repr__(self):
return f"<Alias {self.id} {self.email}>"
class DeletedAlias(Base, ModelMixin):
"""Store all deleted alias to make sure they are NOT reused"""
__tablename__ = "deleted_alias"
email = sa.Column(sa.String(256), unique=True, nullable=False)
def create(cls, **kw):
raise Exception("should use delete_alias(alias,user) instead")
def __repr__(self):
return f"<Deleted Alias {self.email}>"
class AliasUsedOn(Base, ModelMixin):
"""Used to know where an alias is created"""
__tablename__ = "alias_used_on"
__table_args__ = (
sa.UniqueConstraint("alias_id", "hostname", name="uq_alias_used"),
)
alias_id = sa.Column(
sa.ForeignKey(Alias.id, ondelete="cascade"), nullable=False, index=True
)
user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False)
alias = orm.relationship(Alias)
hostname = sa.Column(sa.String(1024), nullable=False)
class DomainDeletedAlias(Base, ModelMixin):
"""Store all deleted alias for a domain"""
__tablename__ = "domain_deleted_alias"
__table_args__ = (
sa.UniqueConstraint("domain_id", "email", name="uq_domain_trash"),
)
email = sa.Column(sa.String(256), nullable=False)
domain_id = sa.Column(
sa.ForeignKey("custom_domain.id", ondelete="cascade"), nullable=False
)
user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False)
domain = orm.relationship(CustomDomain)
user = orm.relationship(User, foreign_keys=[user_id])
def create(cls, **kw):
raise Exception("should use delete_alias(alias,user) instead")
def __repr__(self):
return f"<DomainDeletedAlias {self.id} {self.email}>"
def convert_to_id(s: str):
"""convert a string to id-like: remove space, remove special accent"""
s = s.lower()
s = unidecode(s)
s = s.replace(" ", "")
return s[:256]
The provided code snippet includes necessary dependencies for implementing the `new_custom_alias_v2` function. Write a Python function `def new_custom_alias_v2()` to solve the following problem:
Create a new custom alias Same as v1 but signed_suffix is actually the suffix with signature, e.g. .random_word@SL.co.Xq19rQ.s99uWQ7jD1s5JZDZqczYI5TbNNU Input: alias_prefix, for ex "www_groupon_com" signed_suffix, either .random_letters@simplelogin.co or @my-domain.com optional "hostname" in args optional "note" Output: 201 if success 409 if the alias already exists
Here is the function:
def new_custom_alias_v2():
"""
Create a new custom alias
Same as v1 but signed_suffix is actually the suffix with signature, e.g.
.random_word@SL.co.Xq19rQ.s99uWQ7jD1s5JZDZqczYI5TbNNU
Input:
alias_prefix, for ex "www_groupon_com"
signed_suffix, either .random_letters@simplelogin.co or @my-domain.com
optional "hostname" in args
optional "note"
Output:
201 if success
409 if the alias already exists
"""
user: User = g.user
if not user.can_create_new_alias():
LOG.d("user %s cannot create any custom alias", user)
return (
jsonify(
error="You have reached the limitation of a free account with the maximum of "
f"{MAX_NB_EMAIL_FREE_PLAN} aliases, please upgrade your plan to create more aliases"
),
400,
)
hostname = request.args.get("hostname")
data = request.get_json()
if not data:
return jsonify(error="request body cannot be empty"), 400
alias_prefix = data.get("alias_prefix", "").strip().lower().replace(" ", "")
signed_suffix = data.get("signed_suffix", "").strip()
note = data.get("note")
alias_prefix = convert_to_id(alias_prefix)
try:
alias_suffix = check_suffix_signature(signed_suffix)
if not alias_suffix:
LOG.w("Alias creation time expired for %s", user)
return jsonify(error="Alias creation time is expired, please retry"), 412
except Exception:
LOG.w("Alias suffix is tampered, user %s", user)
return jsonify(error="Tampered suffix"), 400
if not verify_prefix_suffix(user, alias_prefix, alias_suffix):
return jsonify(error="wrong alias prefix or suffix"), 400
full_alias = alias_prefix + alias_suffix
if (
Alias.get_by(email=full_alias)
or DeletedAlias.get_by(email=full_alias)
or DomainDeletedAlias.get_by(email=full_alias)
):
LOG.d("full alias already used %s", full_alias)
return jsonify(error=f"alias {full_alias} already exists"), 409
if ".." in full_alias:
return (
jsonify(error="2 consecutive dot signs aren't allowed in an email address"),
400,
)
alias = Alias.create(
user_id=user.id,
email=full_alias,
mailbox_id=user.default_mailbox_id,
note=note,
)
Session.commit()
if hostname:
AliasUsedOn.create(alias_id=alias.id, hostname=hostname, user_id=alias.user_id)
Session.commit()
return (
jsonify(alias=full_alias, **serialize_alias_info_v2(get_alias_info_v2(alias))),
201,
) | Create a new custom alias Same as v1 but signed_suffix is actually the suffix with signature, e.g. .random_word@SL.co.Xq19rQ.s99uWQ7jD1s5JZDZqczYI5TbNNU Input: alias_prefix, for ex "www_groupon_com" signed_suffix, either .random_letters@simplelogin.co or @my-domain.com optional "hostname" in args optional "note" Output: 201 if success 409 if the alias already exists |
180,578 | from flask import g
from flask import jsonify, request
from app import parallel_limiter
from app.alias_suffix import check_suffix_signature, verify_prefix_suffix
from app.alias_utils import check_alias_prefix
from app.api.base import api_bp, require_api_auth
from app.api.serializer import (
serialize_alias_info_v2,
get_alias_info_v2,
)
from app.config import MAX_NB_EMAIL_FREE_PLAN, ALIAS_LIMIT
from app.db import Session
from app.extensions import limiter
from app.log import LOG
from app.models import (
Alias,
AliasUsedOn,
User,
DeletedAlias,
DomainDeletedAlias,
Mailbox,
AliasMailbox,
)
from app.utils import convert_to_id
def check_suffix_signature(signed_suffix: str) -> Optional[str]:
# hypothesis: user will click on the button in the 600 secs
try:
return signer.unsign(signed_suffix, max_age=600).decode()
except itsdangerous.BadSignature:
return None
def verify_prefix_suffix(
user: User, alias_prefix, alias_suffix, alias_options: Optional[AliasOptions] = None
) -> bool:
"""verify if user could create an alias with the given prefix and suffix"""
if not alias_prefix or not alias_suffix: # should be caught on frontend
return False
user_custom_domains = [cd.domain for cd in user.verified_custom_domains()]
# make sure alias_suffix is either .random_word@simplelogin.co or @my-domain.com
alias_suffix = alias_suffix.strip()
# alias_domain_prefix is either a .random_word or ""
alias_domain_prefix, alias_domain = alias_suffix.split("@", 1)
# alias_domain must be either one of user custom domains or built-in domains
if alias_domain not in user.available_alias_domains(alias_options=alias_options):
LOG.e("wrong alias suffix %s, user %s", alias_suffix, user)
return False
# SimpleLogin domain case:
# 1) alias_suffix must start with "." and
# 2) alias_domain_prefix must come from the word list
if (
alias_domain in user.available_sl_domains(alias_options=alias_options)
and alias_domain not in user_custom_domains
# when DISABLE_ALIAS_SUFFIX is true, alias_domain_prefix is empty
and not config.DISABLE_ALIAS_SUFFIX
):
if not alias_domain_prefix.startswith("."):
LOG.e("User %s submits a wrong alias suffix %s", user, alias_suffix)
return False
else:
if alias_domain not in user_custom_domains:
if not config.DISABLE_ALIAS_SUFFIX:
LOG.e("wrong alias suffix %s, user %s", alias_suffix, user)
return False
if alias_domain not in user.available_sl_domains(
alias_options=alias_options
):
LOG.e("wrong alias suffix %s, user %s", alias_suffix, user)
return False
return True
def check_alias_prefix(alias_prefix) -> bool:
if len(alias_prefix) > 40:
return False
if re.fullmatch(_ALIAS_PREFIX_PATTERN, alias_prefix) is None:
return False
return True
def serialize_alias_info_v2(alias_info: AliasInfo) -> dict:
res = {
# Alias field
"id": alias_info.alias.id,
"email": alias_info.alias.email,
"creation_date": alias_info.alias.created_at.format(),
"creation_timestamp": alias_info.alias.created_at.timestamp,
"enabled": alias_info.alias.enabled,
"note": alias_info.alias.note,
"name": alias_info.alias.name,
# activity
"nb_forward": alias_info.nb_forward,
"nb_block": alias_info.nb_blocked,
"nb_reply": alias_info.nb_reply,
# mailbox
"mailbox": {"id": alias_info.mailbox.id, "email": alias_info.mailbox.email},
"mailboxes": [
{"id": mailbox.id, "email": mailbox.email}
for mailbox in alias_info.mailboxes
],
"support_pgp": alias_info.alias.mailbox_support_pgp(),
"disable_pgp": alias_info.alias.disable_pgp,
"latest_activity": None,
"pinned": alias_info.alias.pinned,
}
if alias_info.latest_email_log:
email_log = alias_info.latest_email_log
contact = alias_info.latest_contact
# latest activity
res["latest_activity"] = {
"timestamp": email_log.created_at.timestamp,
"action": email_log.get_action(),
"contact": {
"email": contact.website_email,
"name": contact.name,
"reverse_alias": contact.website_send_to(),
},
}
return res
def get_alias_info_v2(alias: Alias, mailbox=None) -> AliasInfo:
if not mailbox:
mailbox = alias.mailbox
q = (
Session.query(Contact, EmailLog)
.filter(Contact.alias_id == alias.id)
.filter(EmailLog.contact_id == Contact.id)
)
latest_activity: Arrow = alias.created_at
latest_email_log = None
latest_contact = None
alias_info = AliasInfo(
alias=alias,
nb_blocked=0,
nb_forward=0,
nb_reply=0,
mailbox=mailbox,
mailboxes=[mailbox],
)
for m in alias._mailboxes:
alias_info.mailboxes.append(m)
# remove duplicates
# can happen that alias.mailbox_id also appears in AliasMailbox table
alias_info.mailboxes = list(set(alias_info.mailboxes))
for contact, email_log in q:
if email_log.is_reply:
alias_info.nb_reply += 1
elif email_log.blocked:
alias_info.nb_blocked += 1
else:
alias_info.nb_forward += 1
if email_log.created_at > latest_activity:
latest_activity = email_log.created_at
latest_email_log = email_log
latest_contact = contact
alias_info.latest_contact = latest_contact
alias_info.latest_email_log = latest_email_log
return alias_info
try:
MAX_NB_EMAIL_FREE_PLAN = int(os.environ["MAX_NB_EMAIL_FREE_PLAN"])
except Exception:
print("MAX_NB_EMAIL_FREE_PLAN is not set, use 5 as default value")
MAX_NB_EMAIL_FREE_PLAN = 5
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
LOG = _get_logger("SL")
class User(Base, ModelMixin, UserMixin, PasswordOracle):
__tablename__ = "users"
FLAG_FREE_DISABLE_CREATE_ALIAS = 1 << 0
FLAG_CREATED_FROM_PARTNER = 1 << 1
FLAG_FREE_OLD_ALIAS_LIMIT = 1 << 2
email = sa.Column(sa.String(256), unique=True, nullable=False)
name = sa.Column(sa.String(128), nullable=True)
is_admin = sa.Column(sa.Boolean, nullable=False, default=False)
alias_generator = sa.Column(
sa.Integer,
nullable=False,
default=AliasGeneratorEnum.word.value,
server_default=str(AliasGeneratorEnum.word.value),
)
notification = sa.Column(
sa.Boolean, default=True, nullable=False, server_default="1"
)
activated = sa.Column(sa.Boolean, default=False, nullable=False, index=True)
# an account can be disabled if having harmful behavior
disabled = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0")
profile_picture_id = sa.Column(sa.ForeignKey(File.id), nullable=True)
otp_secret = sa.Column(sa.String(16), nullable=True)
enable_otp = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
last_otp = sa.Column(sa.String(12), nullable=True, default=False)
# Fields for WebAuthn
fido_uuid = sa.Column(sa.String(), nullable=True, unique=True)
# the default domain that's used when user creates a new random alias
# default_alias_custom_domain_id XOR default_alias_public_domain_id
default_alias_custom_domain_id = sa.Column(
sa.ForeignKey("custom_domain.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
default_alias_public_domain_id = sa.Column(
sa.ForeignKey("public_domain.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
# some users could have lifetime premium
lifetime = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0")
paid_lifetime = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
lifetime_coupon_id = sa.Column(
sa.ForeignKey("lifetime_coupon.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
# user can use all premium features until this date
trial_end = sa.Column(
ArrowType, default=lambda: arrow.now().shift(days=7, hours=1), nullable=True
)
# the mailbox used when create random alias
# this field is nullable but in practice, it's always set
# it cannot be set to non-nullable though
# as this will create foreign key cycle between User and Mailbox
default_mailbox_id = sa.Column(
sa.ForeignKey("mailbox.id"), nullable=True, default=None
)
profile_picture = orm.relationship(File, foreign_keys=[profile_picture_id])
# Specify the format for sender address
# for the full list, see SenderFormatEnum
sender_format = sa.Column(
sa.Integer, default="0", nullable=False, server_default="0"
)
# to know whether user has explicitly chosen a sender format as opposed to those who use the default ones.
# users who haven't chosen a sender format and are using 1 or 3 format, their sender format will be set to 0
sender_format_updated_at = sa.Column(ArrowType, default=None)
replace_reverse_alias = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
referral_id = sa.Column(
sa.ForeignKey("referral.id", ondelete="SET NULL"),
nullable=True,
default=None,
index=True,
)
referral = orm.relationship("Referral", foreign_keys=[referral_id])
# whether intro has been shown to user
intro_shown = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
default_mailbox = orm.relationship("Mailbox", foreign_keys=[default_mailbox_id])
# user can set a more strict max_spam score to block spams more aggressively
max_spam_score = sa.Column(sa.Integer, nullable=True)
# newsletter is sent to this address
newsletter_alias_id = sa.Column(
sa.ForeignKey("alias.id", ondelete="SET NULL"),
nullable=True,
default=None,
index=True,
)
# whether to include the sender address in reverse-alias
include_sender_in_reverse_alias = sa.Column(
sa.Boolean, default=True, nullable=False, server_default="0"
)
# whether to use random string or random word as suffix
# Random word from dictionary file -> 0
# Completely random string -> 1
random_alias_suffix = sa.Column(
sa.Integer,
nullable=False,
default=AliasSuffixEnum.word.value,
server_default=str(AliasSuffixEnum.random_string.value),
)
# always expand the alias info, i.e. without needing to press "More"
expand_alias_info = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# ignore emails send from a mailbox to its alias. This can happen when replying all to a forwarded email
# can automatically re-includes the alias
ignore_loop_email = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# used for flask-login as an "alternative token"
# cf https://flask-login.readthedocs.io/en/latest/#alternative-tokens
alternative_id = sa.Column(sa.String(128), unique=True, nullable=True)
# by default, when an alias is automatically created, a note like "Created with ...." is created
# If this field is True, the note won't be created.
disable_automatic_alias_note = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# By default, the one-click unsubscribe disable the alias
# If set to true, it will block the sender instead
one_click_unsubscribe_block_sender = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# automatically include the website name when user creates an alias via the SimpleLogin icon in the email field
include_website_in_one_click_alias = sa.Column(
sa.Boolean,
# new user will have this option turned on automatically
default=True,
nullable=False,
# old user will have this option turned off
server_default="0",
)
_directory_quota = sa.Column(
"directory_quota", sa.Integer, default=50, nullable=False, server_default="50"
)
_subdomain_quota = sa.Column(
"subdomain_quota", sa.Integer, default=5, nullable=False, server_default="5"
)
# user can use import to import too many aliases
disable_import = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# user can use the phone feature
can_use_phone = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# in minutes
phone_quota = sa.Column(sa.Integer, nullable=True)
# Status code to return if is blocked
block_behaviour = sa.Column(
sa.Enum(BlockBehaviourEnum),
nullable=False,
server_default=BlockBehaviourEnum.return_2xx.name,
)
include_header_email_header = sa.Column(
sa.Boolean, default=True, nullable=False, server_default="1"
)
# bitwise flags. Allow for future expansion
flags = sa.Column(
sa.BigInteger,
default=FLAG_FREE_DISABLE_CREATE_ALIAS,
server_default="0",
nullable=False,
)
# Keep original unsub behaviour
unsub_behaviour = sa.Column(
IntEnumType(UnsubscribeBehaviourEnum),
default=UnsubscribeBehaviourEnum.PreserveOriginal,
server_default=str(UnsubscribeBehaviourEnum.DisableAlias.value),
nullable=False,
)
# Trigger hard deletion of the account at this time
delete_on = sa.Column(ArrowType, default=None)
__table_args__ = (
sa.Index(
"ix_users_activated_trial_end_lifetime", activated, trial_end, lifetime
),
sa.Index("ix_users_delete_on", delete_on),
)
def directory_quota(self):
return min(
self._directory_quota,
config.MAX_NB_DIRECTORY - Directory.filter_by(user_id=self.id).count(),
)
def subdomain_quota(self):
return min(
self._subdomain_quota,
config.MAX_NB_SUBDOMAIN
- CustomDomain.filter_by(user_id=self.id, is_sl_subdomain=True).count(),
)
def created_by_partner(self):
return User.FLAG_CREATED_FROM_PARTNER == (
self.flags & User.FLAG_CREATED_FROM_PARTNER
)
def subdomain_is_available():
return SLDomain.filter_by(can_use_subdomain=True).count() > 0
# implement flask-login "alternative token"
def get_id(self):
if self.alternative_id:
return self.alternative_id
else:
return str(self.id)
def create(cls, email, name="", password=None, from_partner=False, **kwargs):
email = sanitize_email(email)
user: User = super(User, cls).create(email=email, name=name[:100], **kwargs)
if password:
user.set_password(password)
Session.flush()
mb = Mailbox.create(user_id=user.id, email=user.email, verified=True)
Session.flush()
user.default_mailbox_id = mb.id
# generate an alternative_id if needed
if "alternative_id" not in kwargs:
user.alternative_id = str(uuid.uuid4())
# If the user is created from partner, do not notify
# nor give a trial
if from_partner:
user.flags = User.FLAG_CREATED_FROM_PARTNER
user.notification = False
user.trial_end = None
Job.create(
name=config.JOB_SEND_PROTON_WELCOME_1,
payload={"user_id": user.id},
run_at=arrow.now(),
)
Session.flush()
return user
# create a first alias mail to show user how to use when they login
alias = Alias.create_new(
user,
prefix="simplelogin-newsletter",
mailbox_id=mb.id,
note="This is your first alias. It's used to receive SimpleLogin communications "
"like new features announcements, newsletters.",
)
Session.flush()
user.newsletter_alias_id = alias.id
Session.flush()
if config.DISABLE_ONBOARDING:
LOG.d("Disable onboarding emails")
return user
# Schedule onboarding emails
Job.create(
name=config.JOB_ONBOARDING_1,
payload={"user_id": user.id},
run_at=arrow.now().shift(days=1),
)
Job.create(
name=config.JOB_ONBOARDING_2,
payload={"user_id": user.id},
run_at=arrow.now().shift(days=2),
)
Job.create(
name=config.JOB_ONBOARDING_4,
payload={"user_id": user.id},
run_at=arrow.now().shift(days=3),
)
Session.flush()
return user
def get_active_subscription(
self, include_partner_subscription: bool = True
) -> Optional[
Union[
Subscription
| AppleSubscription
| ManualSubscription
| CoinbaseSubscription
| PartnerSubscription
]
]:
sub: Subscription = self.get_paddle_subscription()
if sub:
return sub
apple_sub: AppleSubscription = AppleSubscription.get_by(user_id=self.id)
if apple_sub and apple_sub.is_valid():
return apple_sub
manual_sub: ManualSubscription = ManualSubscription.get_by(user_id=self.id)
if manual_sub and manual_sub.is_active():
return manual_sub
coinbase_subscription: CoinbaseSubscription = CoinbaseSubscription.get_by(
user_id=self.id
)
if coinbase_subscription and coinbase_subscription.is_active():
return coinbase_subscription
if include_partner_subscription:
partner_sub: PartnerSubscription = PartnerSubscription.find_by_user_id(
self.id
)
if partner_sub and partner_sub.is_active():
return partner_sub
return None
def get_active_subscription_end(
self, include_partner_subscription: bool = True
) -> Optional[arrow.Arrow]:
sub = self.get_active_subscription(
include_partner_subscription=include_partner_subscription
)
if isinstance(sub, Subscription):
return arrow.get(sub.next_bill_date)
if isinstance(sub, AppleSubscription):
return sub.expires_date
if isinstance(sub, ManualSubscription):
return sub.end_at
if isinstance(sub, CoinbaseSubscription):
return sub.end_at
return None
# region Billing
def lifetime_or_active_subscription(
self, include_partner_subscription: bool = True
) -> bool:
"""True if user has lifetime licence or active subscription"""
if self.lifetime:
return True
return self.get_active_subscription(include_partner_subscription) is not None
def is_paid(self) -> bool:
"""same as _lifetime_or_active_subscription but not include free manual subscription"""
sub = self.get_active_subscription()
if sub is None:
return False
if isinstance(sub, ManualSubscription) and sub.is_giveaway:
return False
return True
def is_active(self) -> bool:
if self.delete_on is None:
return True
return self.delete_on < arrow.now()
def in_trial(self):
"""return True if user does not have lifetime licence or an active subscription AND is in trial period"""
if self.lifetime_or_active_subscription():
return False
if self.trial_end and arrow.now() < self.trial_end:
return True
return False
def should_show_upgrade_button(self):
if self.lifetime_or_active_subscription():
return False
return True
def is_premium(self, include_partner_subscription: bool = True) -> bool:
"""
user is premium if they:
- have a lifetime deal or
- in trial period or
- active subscription
"""
if self.lifetime_or_active_subscription(include_partner_subscription):
return True
if self.trial_end and arrow.now() < self.trial_end:
return True
return False
def upgrade_channel(self) -> str:
"""Used on admin dashboard"""
# user can have multiple subscription channel
channels = []
if self.lifetime:
channels.append("Lifetime")
sub: Subscription = self.get_paddle_subscription()
if sub:
if sub.cancelled:
channels.append(
f"""Cancelled Paddle Subscription <a href="https://vendors.paddle.com/subscriptions/customers/manage/{sub.subscription_id}">{sub.subscription_id}</a> {sub.plan_name()} ends at {sub.next_bill_date}"""
)
else:
channels.append(
f"""Active Paddle Subscription <a href="https://vendors.paddle.com/subscriptions/customers/manage/{sub.subscription_id}">{sub.subscription_id}</a> {sub.plan_name()}, renews at {sub.next_bill_date}"""
)
apple_sub: AppleSubscription = AppleSubscription.get_by(user_id=self.id)
if apple_sub and apple_sub.is_valid():
channels.append(f"Apple Subscription {apple_sub.expires_date.humanize()}")
manual_sub: ManualSubscription = ManualSubscription.get_by(user_id=self.id)
if manual_sub and manual_sub.is_active():
mode = "Giveaway" if manual_sub.is_giveaway else "Paid"
channels.append(
f"Manual Subscription {manual_sub.comment} {mode} {manual_sub.end_at.humanize()}"
)
coinbase_subscription: CoinbaseSubscription = CoinbaseSubscription.get_by(
user_id=self.id
)
if coinbase_subscription and coinbase_subscription.is_active():
channels.append(
f"Coinbase Subscription ends {coinbase_subscription.end_at.humanize()}"
)
r = (
Session.query(PartnerSubscription, PartnerUser, Partner)
.filter(
PartnerSubscription.partner_user_id == PartnerUser.id,
PartnerUser.user_id == self.id,
Partner.id == PartnerUser.partner_id,
)
.first()
)
if r and r[0].is_active():
channels.append(
f"Subscription via {r[2].name} partner , ends {r[0].end_at.humanize()}"
)
return ".\n".join(channels)
# endregion
def max_alias_for_free_account(self) -> int:
if (
self.FLAG_FREE_OLD_ALIAS_LIMIT
== self.flags & self.FLAG_FREE_OLD_ALIAS_LIMIT
):
return config.MAX_NB_EMAIL_OLD_FREE_PLAN
else:
return config.MAX_NB_EMAIL_FREE_PLAN
def can_create_new_alias(self) -> bool:
"""
Whether user can create a new alias. User can't create a new alias if
- has more than 15 aliases in the free plan, *even in the free trial*
"""
if not self.is_active():
return False
if self.disabled:
return False
if self.lifetime_or_active_subscription():
return True
else:
return (
Alias.filter_by(user_id=self.id).count()
< self.max_alias_for_free_account()
)
def can_send_or_receive(self) -> bool:
if self.disabled:
LOG.i(f"User {self} is disabled. Cannot receive or send emails")
return False
if self.delete_on is not None:
LOG.i(
f"User {self} is scheduled to be deleted. Cannot receive or send emails"
)
return False
return True
def profile_picture_url(self):
if self.profile_picture_id:
return self.profile_picture.get_url()
else:
return url_for("static", filename="default-avatar.png")
def suggested_emails(self, website_name) -> (str, [str]):
"""return suggested email and other email choices"""
website_name = convert_to_id(website_name)
all_aliases = [
ge.email for ge in Alias.filter_by(user_id=self.id, enabled=True)
]
if self.can_create_new_alias():
suggested_alias = Alias.create_new(self, prefix=website_name).email
else:
# pick an email from the list of gen emails
suggested_alias = random.choice(all_aliases)
return (
suggested_alias,
list(set(all_aliases).difference({suggested_alias})),
)
def suggested_names(self) -> (str, [str]):
"""return suggested name and other name choices"""
other_name = convert_to_id(self.name)
return self.name, [other_name, "Anonymous", "whoami"]
def get_name_initial(self) -> str:
if not self.name:
return ""
names = self.name.split(" ")
return "".join([n[0].upper() for n in names if n])
def get_paddle_subscription(self) -> Optional["Subscription"]:
"""return *active* Paddle subscription
Return None if the subscription is already expired
TODO: support user unsubscribe and re-subscribe
"""
sub = Subscription.get_by(user_id=self.id)
if sub:
# grace period is 14 days
# sub is active until the next billing_date + PADDLE_SUBSCRIPTION_GRACE_DAYS
if (
sub.next_bill_date
>= arrow.now().shift(days=-PADDLE_SUBSCRIPTION_GRACE_DAYS).date()
):
return sub
# past subscription, user is considered not having a subscription = free plan
else:
return None
else:
return sub
def verified_custom_domains(self) -> List["CustomDomain"]:
return (
CustomDomain.filter_by(user_id=self.id, ownership_verified=True)
.order_by(CustomDomain.domain.asc())
.all()
)
def mailboxes(self) -> List["Mailbox"]:
"""list of mailbox that user own"""
mailboxes = []
for mailbox in Mailbox.filter_by(user_id=self.id, verified=True):
mailboxes.append(mailbox)
return mailboxes
def nb_directory(self):
return Directory.filter_by(user_id=self.id).count()
def has_custom_domain(self):
return CustomDomain.filter_by(user_id=self.id, verified=True).count() > 0
def custom_domains(self):
return CustomDomain.filter_by(user_id=self.id, verified=True).all()
def available_domains_for_random_alias(
self, alias_options: Optional[AliasOptions] = None
) -> List[Tuple[bool, str]]:
"""Return available domains for user to create random aliases
Each result record contains:
- whether the domain belongs to SimpleLogin
- the domain
"""
res = []
for domain in self.available_sl_domains(alias_options=alias_options):
res.append((True, domain))
for custom_domain in self.verified_custom_domains():
res.append((False, custom_domain.domain))
return res
def default_random_alias_domain(self) -> str:
"""return the domain used for the random alias"""
if self.default_alias_custom_domain_id:
custom_domain = CustomDomain.get(self.default_alias_custom_domain_id)
# sanity check
if (
not custom_domain
or not custom_domain.verified
or custom_domain.user_id != self.id
):
LOG.w("Problem with %s default random alias domain", self)
return config.FIRST_ALIAS_DOMAIN
return custom_domain.domain
if self.default_alias_public_domain_id:
sl_domain = SLDomain.get(self.default_alias_public_domain_id)
# sanity check
if not sl_domain:
LOG.e("Problem with %s public random alias domain", self)
return config.FIRST_ALIAS_DOMAIN
if sl_domain.premium_only and not self.is_premium():
LOG.w(
"%s is not premium and cannot use %s. Reset default random alias domain setting",
self,
sl_domain,
)
self.default_alias_custom_domain_id = None
self.default_alias_public_domain_id = None
Session.commit()
return config.FIRST_ALIAS_DOMAIN
return sl_domain.domain
return config.FIRST_ALIAS_DOMAIN
def fido_enabled(self) -> bool:
if self.fido_uuid is not None:
return True
return False
def two_factor_authentication_enabled(self) -> bool:
return self.enable_otp or self.fido_enabled()
def get_communication_email(self) -> (Optional[str], str, bool):
"""
Return
- the email that user uses to receive email communication. None if user unsubscribes from newsletter
- the unsubscribe URL
- whether the unsubscribe method is via sending email (mailto:) or Http POST
"""
if self.notification and self.activated and not self.disabled:
if self.newsletter_alias_id:
alias = Alias.get(self.newsletter_alias_id)
if alias.enabled:
unsub = UnsubscribeEncoder.encode(
UnsubscribeAction.DisableAlias, alias.id
)
return alias.email, unsub.link, unsub.via_email
# alias disabled -> user doesn't want to receive newsletter
else:
return None, "", False
else:
# do not handle http POST unsubscribe
if config.UNSUBSCRIBER:
# use * as suffix instead of = as for alias unsubscribe
return (
self.email,
UnsubscribeEncoder.encode_mailto(
UnsubscribeAction.UnsubscribeNewsletter, self.id
),
True,
)
return None, "", False
def available_sl_domains(
self, alias_options: Optional[AliasOptions] = None
) -> [str]:
"""
Return all SimpleLogin domains that user can use when creating a new alias, including:
- SimpleLogin public domains, available for all users (ALIAS_DOMAIN)
- SimpleLogin premium domains, only available for Premium accounts (PREMIUM_ALIAS_DOMAIN)
"""
return [
sl_domain.domain
for sl_domain in self.get_sl_domains(alias_options=alias_options)
]
def get_sl_domains(
self, alias_options: Optional[AliasOptions] = None
) -> list["SLDomain"]:
if alias_options is None:
alias_options = AliasOptions()
top_conds = [SLDomain.hidden == False] # noqa: E712
or_conds = [] # noqa:E711
if self.default_alias_public_domain_id is not None:
default_domain_conds = [SLDomain.id == self.default_alias_public_domain_id]
if not self.is_premium():
default_domain_conds.append(
SLDomain.premium_only == False # noqa: E712
)
or_conds.append(and_(*default_domain_conds).self_group())
if alias_options.show_partner_domains is not None:
partner_user = PartnerUser.filter_by(
user_id=self.id, partner_id=alias_options.show_partner_domains.id
).first()
if partner_user is not None:
partner_domain_cond = [SLDomain.partner_id == partner_user.partner_id]
if alias_options.show_partner_premium is None:
alias_options.show_partner_premium = self.is_premium()
if not alias_options.show_partner_premium:
partner_domain_cond.append(
SLDomain.premium_only == False # noqa: E712
)
or_conds.append(and_(*partner_domain_cond).self_group())
if alias_options.show_sl_domains:
sl_conds = [SLDomain.partner_id == None] # noqa: E711
if not self.is_premium():
sl_conds.append(SLDomain.premium_only == False) # noqa: E712
or_conds.append(and_(*sl_conds).self_group())
top_conds.append(or_(*or_conds))
query = Session.query(SLDomain).filter(*top_conds).order_by(SLDomain.order)
return query.all()
def available_alias_domains(
self, alias_options: Optional[AliasOptions] = None
) -> [str]:
"""return all domains that user can use when creating a new alias, including:
- SimpleLogin public domains, available for all users (ALIAS_DOMAIN)
- SimpleLogin premium domains, only available for Premium accounts (PREMIUM_ALIAS_DOMAIN)
- Verified custom domains
"""
domains = self.available_sl_domains(alias_options=alias_options)
for custom_domain in self.verified_custom_domains():
domains.append(custom_domain.domain)
# can have duplicate where a "root" user has a domain that's also listed in SL domains
return list(set(domains))
def should_show_app_page(self) -> bool:
"""whether to show the app page"""
return (
# when user has used the "Sign in with SL" button before
ClientUser.filter(ClientUser.user_id == self.id).count()
# or when user has created an app
+ Client.filter(Client.user_id == self.id).count()
> 0
)
def get_random_alias_suffix(self, custom_domain: Optional["CustomDomain"] = None):
"""Get random suffix for an alias based on user's preference.
Use a shorter suffix in case of custom domain
Returns:
str: the random suffix generated
"""
if self.random_alias_suffix == AliasSuffixEnum.random_string.value:
return random_string(config.ALIAS_RANDOM_SUFFIX_LENGTH, include_digits=True)
if custom_domain is None:
return random_words(1, 3)
return random_words(1)
def can_create_contacts(self) -> bool:
if self.is_premium():
return True
if self.flags & User.FLAG_FREE_DISABLE_CREATE_ALIAS == 0:
return True
return not config.DISABLE_CREATE_CONTACTS_FOR_FREE_USERS
def __repr__(self):
return f"<User {self.id} {self.name} {self.email}>"
class Alias(Base, ModelMixin):
__tablename__ = "alias"
FLAG_PARTNER_CREATED = 1 << 0
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, index=True
)
email = sa.Column(sa.String(128), unique=True, nullable=False)
# the name to use when user replies/sends from alias
name = sa.Column(sa.String(128), nullable=True, default=None)
enabled = sa.Column(sa.Boolean(), default=True, nullable=False)
flags = sa.Column(
sa.BigInteger(), default=0, server_default="0", nullable=False, index=True
)
custom_domain_id = sa.Column(
sa.ForeignKey("custom_domain.id", ondelete="cascade"), nullable=True, index=True
)
custom_domain = orm.relationship("CustomDomain", foreign_keys=[custom_domain_id])
# To know whether an alias is created "on the fly", i.e. via the custom domain catch-all feature
automatic_creation = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# to know whether an alias belongs to a directory
directory_id = sa.Column(
sa.ForeignKey("directory.id", ondelete="cascade"), nullable=True, index=True
)
note = sa.Column(sa.Text, default=None, nullable=True)
# an alias can be owned by another mailbox
mailbox_id = sa.Column(
sa.ForeignKey("mailbox.id", ondelete="cascade"), nullable=False, index=True
)
# prefix _ to avoid this object being used accidentally.
# To have the list of all mailboxes, should use AliasInfo instead
_mailboxes = orm.relationship("Mailbox", secondary="alias_mailbox", lazy="joined")
# If the mailbox has PGP-enabled, user can choose disable the PGP on the alias
# this is useful when some senders already support PGP
disable_pgp = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# a way to bypass the bounce automatic disable mechanism
cannot_be_disabled = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# when a mailbox wants to send an email on behalf of the alias via the reverse-alias
# several checks are performed to avoid email spoofing
# this option allow disabling these checks
disable_email_spoofing_check = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# to know whether an alias is added using a batch import
batch_import_id = sa.Column(
sa.ForeignKey("batch_import.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
# set in case of alias transfer.
original_owner_id = sa.Column(
sa.ForeignKey(User.id, ondelete="SET NULL"), nullable=True
)
# alias is pinned on top
pinned = sa.Column(sa.Boolean, nullable=False, default=False, server_default="0")
# used to transfer an alias to another user
transfer_token = sa.Column(sa.String(64), default=None, unique=True, nullable=True)
transfer_token_expiration = sa.Column(
ArrowType, default=arrow.utcnow, nullable=True
)
# have I been pwned
hibp_last_check = sa.Column(ArrowType, default=None, index=True)
hibp_breaches = orm.relationship("Hibp", secondary="alias_hibp")
# to use Postgres full text search. Only applied on "note" column for now
# this is a generated Postgres column
ts_vector = sa.Column(
TSVector(), sa.Computed("to_tsvector('english', note)", persisted=True)
)
last_email_log_id = sa.Column(sa.Integer, default=None, nullable=True)
__table_args__ = (
Index("ix_video___ts_vector__", ts_vector, postgresql_using="gin"),
# index on note column using pg_trgm
Index(
"note_pg_trgm_index",
"note",
postgresql_ops={"note": "gin_trgm_ops"},
postgresql_using="gin",
),
)
user = orm.relationship(User, foreign_keys=[user_id])
mailbox = orm.relationship("Mailbox", lazy="joined")
def mailboxes(self):
ret = [self.mailbox]
for m in self._mailboxes:
if m.id is not self.mailbox.id:
ret.append(m)
ret = [mb for mb in ret if mb.verified]
ret = sorted(ret, key=lambda mb: mb.email)
return ret
def authorized_addresses(self) -> [str]:
"""return addresses that can send on behalf of this alias, i.e. can send emails to this alias's reverse-aliases
Including its mailboxes and their authorized addresses
"""
mailboxes = self.mailboxes
ret = [mb.email for mb in mailboxes]
for mailbox in mailboxes:
for aa in mailbox.authorized_addresses:
ret.append(aa.email)
return ret
def mailbox_support_pgp(self) -> bool:
"""return True of one of the mailboxes support PGP"""
for mb in self.mailboxes:
if mb.pgp_enabled():
return True
return False
def pgp_enabled(self) -> bool:
if self.mailbox_support_pgp() and not self.disable_pgp:
return True
return False
def get_custom_domain(alias_address) -> Optional["CustomDomain"]:
alias_domain = validate_email(
alias_address, check_deliverability=False, allow_smtputf8=False
).domain
# handle the case a SLDomain is also a CustomDomain
if SLDomain.get_by(domain=alias_domain) is None:
custom_domain = CustomDomain.get_by(domain=alias_domain)
if custom_domain:
return custom_domain
def create(cls, **kw):
commit = kw.pop("commit", False)
flush = kw.pop("flush", False)
new_alias = cls(**kw)
user = User.get(new_alias.user_id)
if user.is_premium():
limits = config.ALIAS_CREATE_RATE_LIMIT_PAID
else:
limits = config.ALIAS_CREATE_RATE_LIMIT_FREE
# limits is array of (hits,days)
for limit in limits:
key = f"alias_create_{limit[1]}d:{user.id}"
rate_limiter.check_bucket_limit(key, limit[0], limit[1])
email = kw["email"]
# make sure email is lowercase and doesn't have any whitespace
email = sanitize_email(email)
# make sure alias is not in global trash, i.e. DeletedAlias table
if DeletedAlias.get_by(email=email):
raise AliasInTrashError
if DomainDeletedAlias.get_by(email=email):
raise AliasInTrashError
# detect whether alias should belong to a custom domain
if "custom_domain_id" not in kw:
custom_domain = Alias.get_custom_domain(email)
if custom_domain:
new_alias.custom_domain_id = custom_domain.id
Session.add(new_alias)
DailyMetric.get_or_create_today_metric().nb_alias += 1
if commit:
Session.commit()
if flush:
Session.flush()
return new_alias
def create_new(cls, user, prefix, note=None, mailbox_id=None):
prefix = prefix.lower().strip().replace(" ", "")
if not prefix:
raise Exception("alias prefix cannot be empty")
# find the right suffix - avoid infinite loop by running this at max 1000 times
for _ in range(1000):
suffix = user.get_random_alias_suffix()
email = f"{prefix}.{suffix}@{config.FIRST_ALIAS_DOMAIN}"
if available_sl_email(email):
break
return Alias.create(
user_id=user.id,
email=email,
note=note,
mailbox_id=mailbox_id or user.default_mailbox_id,
)
def delete(cls, obj_id):
raise Exception("should use delete_alias(alias,user) instead")
def create_new_random(
cls,
user,
scheme: int = AliasGeneratorEnum.word.value,
in_hex: bool = False,
note: str = None,
):
"""create a new random alias"""
custom_domain = None
random_email = None
if user.default_alias_custom_domain_id:
custom_domain = CustomDomain.get(user.default_alias_custom_domain_id)
random_email = generate_random_alias_email(
scheme=scheme, in_hex=in_hex, alias_domain=custom_domain.domain
)
elif user.default_alias_public_domain_id:
sl_domain: SLDomain = SLDomain.get(user.default_alias_public_domain_id)
if sl_domain.premium_only and not user.is_premium():
LOG.w("%s not premium, cannot use %s", user, sl_domain)
else:
random_email = generate_random_alias_email(
scheme=scheme, in_hex=in_hex, alias_domain=sl_domain.domain
)
if not random_email:
random_email = generate_random_alias_email(scheme=scheme, in_hex=in_hex)
alias = Alias.create(
user_id=user.id,
email=random_email,
mailbox_id=user.default_mailbox_id,
note=note,
)
if custom_domain:
alias.custom_domain_id = custom_domain.id
return alias
def mailbox_email(self):
if self.mailbox_id:
return self.mailbox.email
else:
return self.user.email
def __repr__(self):
return f"<Alias {self.id} {self.email}>"
class DeletedAlias(Base, ModelMixin):
"""Store all deleted alias to make sure they are NOT reused"""
__tablename__ = "deleted_alias"
email = sa.Column(sa.String(256), unique=True, nullable=False)
def create(cls, **kw):
raise Exception("should use delete_alias(alias,user) instead")
def __repr__(self):
return f"<Deleted Alias {self.email}>"
class AliasUsedOn(Base, ModelMixin):
"""Used to know where an alias is created"""
__tablename__ = "alias_used_on"
__table_args__ = (
sa.UniqueConstraint("alias_id", "hostname", name="uq_alias_used"),
)
alias_id = sa.Column(
sa.ForeignKey(Alias.id, ondelete="cascade"), nullable=False, index=True
)
user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False)
alias = orm.relationship(Alias)
hostname = sa.Column(sa.String(1024), nullable=False)
class DomainDeletedAlias(Base, ModelMixin):
"""Store all deleted alias for a domain"""
__tablename__ = "domain_deleted_alias"
__table_args__ = (
sa.UniqueConstraint("domain_id", "email", name="uq_domain_trash"),
)
email = sa.Column(sa.String(256), nullable=False)
domain_id = sa.Column(
sa.ForeignKey("custom_domain.id", ondelete="cascade"), nullable=False
)
user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False)
domain = orm.relationship(CustomDomain)
user = orm.relationship(User, foreign_keys=[user_id])
def create(cls, **kw):
raise Exception("should use delete_alias(alias,user) instead")
def __repr__(self):
return f"<DomainDeletedAlias {self.id} {self.email}>"
class Mailbox(Base, ModelMixin):
__tablename__ = "mailbox"
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, index=True
)
email = sa.Column(sa.String(256), nullable=False, index=True)
verified = sa.Column(sa.Boolean, default=False, nullable=False)
force_spf = sa.Column(sa.Boolean, default=True, server_default="1", nullable=False)
# used when user wants to update mailbox email
new_email = sa.Column(sa.String(256), unique=True)
pgp_public_key = sa.Column(sa.Text, nullable=True)
pgp_finger_print = sa.Column(sa.String(512), nullable=True)
disable_pgp = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# incremented when a check is failed on the mailbox
# alert when the number exceeds a threshold
# used in sanity_check()
nb_failed_checks = sa.Column(
sa.Integer, default=0, server_default="0", nullable=False
)
# a mailbox can be disabled if it can't be reached
disabled = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0")
generic_subject = sa.Column(sa.String(78), nullable=True)
__table_args__ = (sa.UniqueConstraint("user_id", "email", name="uq_mailbox_user"),)
user = orm.relationship(User, foreign_keys=[user_id])
def pgp_enabled(self) -> bool:
if self.pgp_finger_print and not self.disable_pgp:
return True
return False
def nb_alias(self):
return (
AliasMailbox.filter_by(mailbox_id=self.id).count()
+ Alias.filter_by(mailbox_id=self.id).count()
)
def is_proton(self) -> bool:
if (
self.email.endswith("@proton.me")
or self.email.endswith("@protonmail.com")
or self.email.endswith("@protonmail.ch")
or self.email.endswith("@proton.ch")
or self.email.endswith("@pm.me")
):
return True
from app.email_utils import get_email_local_part
mx_domains: [(int, str)] = get_mx_domains(get_email_local_part(self.email))
# Proton is the first domain
if mx_domains and mx_domains[0][1] in (
"mail.protonmail.ch.",
"mailsec.protonmail.ch.",
):
return True
return False
def delete(cls, obj_id):
mailbox: Mailbox = cls.get(obj_id)
user = mailbox.user
# Put all aliases belonging to this mailbox to global or domain trash
for alias in Alias.filter_by(mailbox_id=obj_id):
# special handling for alias that has several mailboxes and has mailbox_id=obj_id
if len(alias.mailboxes) > 1:
# use the first mailbox found in alias._mailboxes
first_mb = alias._mailboxes[0]
alias.mailbox_id = first_mb.id
alias._mailboxes.remove(first_mb)
else:
from app import alias_utils
# only put aliases that have mailbox as a single mailbox into trash
alias_utils.delete_alias(alias, user)
Session.commit()
cls.filter(cls.id == obj_id).delete()
Session.commit()
def aliases(self) -> [Alias]:
ret = Alias.filter_by(mailbox_id=self.id).all()
for am in AliasMailbox.filter_by(mailbox_id=self.id):
ret.append(am.alias)
return ret
def create(cls, **kw):
if "email" in kw:
kw["email"] = sanitize_email(kw["email"])
return super().create(**kw)
def __repr__(self):
return f"<Mailbox {self.id} {self.email}>"
class AliasMailbox(Base, ModelMixin):
__tablename__ = "alias_mailbox"
__table_args__ = (
sa.UniqueConstraint("alias_id", "mailbox_id", name="uq_alias_mailbox"),
)
alias_id = sa.Column(
sa.ForeignKey(Alias.id, ondelete="cascade"), nullable=False, index=True
)
mailbox_id = sa.Column(
sa.ForeignKey(Mailbox.id, ondelete="cascade"), nullable=False, index=True
)
alias = orm.relationship(Alias)
def convert_to_id(s: str):
"""convert a string to id-like: remove space, remove special accent"""
s = s.lower()
s = unidecode(s)
s = s.replace(" ", "")
return s[:256]
The provided code snippet includes necessary dependencies for implementing the `new_custom_alias_v3` function. Write a Python function `def new_custom_alias_v3()` to solve the following problem:
Create a new custom alias Same as v2 but accept a list of mailboxes as input Input: alias_prefix, for ex "www_groupon_com" signed_suffix, either .random_letters@simplelogin.co or @my-domain.com mailbox_ids: list of int optional "hostname" in args optional "note" optional "name" Output: 201 if success 409 if the alias already exists
Here is the function:
def new_custom_alias_v3():
"""
Create a new custom alias
Same as v2 but accept a list of mailboxes as input
Input:
alias_prefix, for ex "www_groupon_com"
signed_suffix, either .random_letters@simplelogin.co or @my-domain.com
mailbox_ids: list of int
optional "hostname" in args
optional "note"
optional "name"
Output:
201 if success
409 if the alias already exists
"""
user: User = g.user
if not user.can_create_new_alias():
LOG.d("user %s cannot create any custom alias", user)
return (
jsonify(
error="You have reached the limitation of a free account with the maximum of "
f"{MAX_NB_EMAIL_FREE_PLAN} aliases, please upgrade your plan to create more aliases"
),
400,
)
hostname = request.args.get("hostname")
data = request.get_json()
if not data:
return jsonify(error="request body cannot be empty"), 400
if not isinstance(data, dict):
return jsonify(error="request body does not follow the required format"), 400
alias_prefix = data.get("alias_prefix", "").strip().lower().replace(" ", "")
signed_suffix = data.get("signed_suffix", "") or ""
signed_suffix = signed_suffix.strip()
mailbox_ids = data.get("mailbox_ids")
note = data.get("note")
name = data.get("name")
if name:
name = name.replace("\n", "")
alias_prefix = convert_to_id(alias_prefix)
if not check_alias_prefix(alias_prefix):
return jsonify(error="alias prefix invalid format or too long"), 400
# check if mailbox is not tempered with
if not isinstance(mailbox_ids, list):
return jsonify(error="mailbox_ids must be an array of id"), 400
mailboxes = []
for mailbox_id in mailbox_ids:
mailbox = Mailbox.get(mailbox_id)
if not mailbox or mailbox.user_id != user.id or not mailbox.verified:
return jsonify(error="Errors with Mailbox"), 400
mailboxes.append(mailbox)
if not mailboxes:
return jsonify(error="At least one mailbox must be selected"), 400
# hypothesis: user will click on the button in the 600 secs
try:
alias_suffix = check_suffix_signature(signed_suffix)
if not alias_suffix:
LOG.w("Alias creation time expired for %s", user)
return jsonify(error="Alias creation time is expired, please retry"), 412
except Exception:
LOG.w("Alias suffix is tampered, user %s", user)
return jsonify(error="Tampered suffix"), 400
if not verify_prefix_suffix(user, alias_prefix, alias_suffix):
return jsonify(error="wrong alias prefix or suffix"), 400
full_alias = alias_prefix + alias_suffix
if (
Alias.get_by(email=full_alias)
or DeletedAlias.get_by(email=full_alias)
or DomainDeletedAlias.get_by(email=full_alias)
):
LOG.d("full alias already used %s", full_alias)
return jsonify(error=f"alias {full_alias} already exists"), 409
if ".." in full_alias:
return (
jsonify(error="2 consecutive dot signs aren't allowed in an email address"),
400,
)
alias = Alias.create(
user_id=user.id,
email=full_alias,
note=note,
name=name or None,
mailbox_id=mailboxes[0].id,
)
Session.flush()
for i in range(1, len(mailboxes)):
AliasMailbox.create(
alias_id=alias.id,
mailbox_id=mailboxes[i].id,
)
Session.commit()
if hostname:
AliasUsedOn.create(alias_id=alias.id, hostname=hostname, user_id=alias.user_id)
Session.commit()
return (
jsonify(alias=full_alias, **serialize_alias_info_v2(get_alias_info_v2(alias))),
201,
) | Create a new custom alias Same as v2 but accept a list of mailboxes as input Input: alias_prefix, for ex "www_groupon_com" signed_suffix, either .random_letters@simplelogin.co or @my-domain.com mailbox_ids: list of int optional "hostname" in args optional "note" optional "name" Output: 201 if success 409 if the alias already exists |
180,579 | import tldextract
from flask import g
from flask import jsonify, request
from app import parallel_limiter
from app.alias_suffix import get_alias_suffixes
from app.api.base import api_bp, require_api_auth
from app.api.serializer import (
get_alias_info_v2,
serialize_alias_info_v2,
)
from app.config import MAX_NB_EMAIL_FREE_PLAN, ALIAS_LIMIT
from app.db import Session
from app.errors import AliasInTrashError
from app.extensions import limiter
from app.log import LOG
from app.models import Alias, AliasUsedOn, AliasGeneratorEnum
from app.utils import convert_to_id
def get_alias_suffixes(
user: User, alias_options: Optional[AliasOptions] = None
) -> [AliasSuffix]:
"""
Similar to as get_available_suffixes() but also return custom domain that doesn't have MX set up.
"""
user_custom_domains = user.verified_custom_domains()
alias_suffixes: [AliasSuffix] = []
# put custom domain first
# for each user domain, generate both the domain and a random suffix version
for custom_domain in user_custom_domains:
if custom_domain.random_prefix_generation:
suffix = (
f".{user.get_random_alias_suffix(custom_domain)}@{custom_domain.domain}"
)
alias_suffix = AliasSuffix(
is_custom=True,
suffix=suffix,
signed_suffix=signer.sign(suffix).decode(),
is_premium=False,
domain=custom_domain.domain,
mx_verified=custom_domain.verified,
)
if user.default_alias_custom_domain_id == custom_domain.id:
alias_suffixes.insert(0, alias_suffix)
else:
alias_suffixes.append(alias_suffix)
suffix = f"@{custom_domain.domain}"
alias_suffix = AliasSuffix(
is_custom=True,
suffix=suffix,
signed_suffix=signer.sign(suffix).decode(),
is_premium=False,
domain=custom_domain.domain,
mx_verified=custom_domain.verified,
)
# put the default domain to top
# only if random_prefix_generation isn't enabled
if (
user.default_alias_custom_domain_id == custom_domain.id
and not custom_domain.random_prefix_generation
):
alias_suffixes.insert(0, alias_suffix)
else:
alias_suffixes.append(alias_suffix)
# then SimpleLogin domain
sl_domains = user.get_sl_domains(alias_options=alias_options)
default_domain_found = False
for sl_domain in sl_domains:
prefix = (
"" if config.DISABLE_ALIAS_SUFFIX else f".{user.get_random_alias_suffix()}"
)
suffix = f"{prefix}@{sl_domain.domain}"
alias_suffix = AliasSuffix(
is_custom=False,
suffix=suffix,
signed_suffix=signer.sign(suffix).decode(),
is_premium=sl_domain.premium_only,
domain=sl_domain.domain,
mx_verified=True,
)
# No default or this is not the default
if (
user.default_alias_public_domain_id is None
or user.default_alias_public_domain_id != sl_domain.id
):
alias_suffixes.append(alias_suffix)
else:
default_domain_found = True
alias_suffixes.insert(0, alias_suffix)
if not default_domain_found:
domain_conditions = {"id": user.default_alias_public_domain_id, "hidden": False}
if not user.is_premium():
domain_conditions["premium_only"] = False
sl_domain = SLDomain.get_by(**domain_conditions)
if sl_domain:
prefix = (
""
if config.DISABLE_ALIAS_SUFFIX
else f".{user.get_random_alias_suffix()}"
)
suffix = f"{prefix}@{sl_domain.domain}"
alias_suffix = AliasSuffix(
is_custom=False,
suffix=suffix,
signed_suffix=signer.sign(suffix).decode(),
is_premium=sl_domain.premium_only,
domain=sl_domain.domain,
mx_verified=True,
)
alias_suffixes.insert(0, alias_suffix)
return alias_suffixes
def serialize_alias_info_v2(alias_info: AliasInfo) -> dict:
res = {
# Alias field
"id": alias_info.alias.id,
"email": alias_info.alias.email,
"creation_date": alias_info.alias.created_at.format(),
"creation_timestamp": alias_info.alias.created_at.timestamp,
"enabled": alias_info.alias.enabled,
"note": alias_info.alias.note,
"name": alias_info.alias.name,
# activity
"nb_forward": alias_info.nb_forward,
"nb_block": alias_info.nb_blocked,
"nb_reply": alias_info.nb_reply,
# mailbox
"mailbox": {"id": alias_info.mailbox.id, "email": alias_info.mailbox.email},
"mailboxes": [
{"id": mailbox.id, "email": mailbox.email}
for mailbox in alias_info.mailboxes
],
"support_pgp": alias_info.alias.mailbox_support_pgp(),
"disable_pgp": alias_info.alias.disable_pgp,
"latest_activity": None,
"pinned": alias_info.alias.pinned,
}
if alias_info.latest_email_log:
email_log = alias_info.latest_email_log
contact = alias_info.latest_contact
# latest activity
res["latest_activity"] = {
"timestamp": email_log.created_at.timestamp,
"action": email_log.get_action(),
"contact": {
"email": contact.website_email,
"name": contact.name,
"reverse_alias": contact.website_send_to(),
},
}
return res
def get_alias_info_v2(alias: Alias, mailbox=None) -> AliasInfo:
if not mailbox:
mailbox = alias.mailbox
q = (
Session.query(Contact, EmailLog)
.filter(Contact.alias_id == alias.id)
.filter(EmailLog.contact_id == Contact.id)
)
latest_activity: Arrow = alias.created_at
latest_email_log = None
latest_contact = None
alias_info = AliasInfo(
alias=alias,
nb_blocked=0,
nb_forward=0,
nb_reply=0,
mailbox=mailbox,
mailboxes=[mailbox],
)
for m in alias._mailboxes:
alias_info.mailboxes.append(m)
# remove duplicates
# can happen that alias.mailbox_id also appears in AliasMailbox table
alias_info.mailboxes = list(set(alias_info.mailboxes))
for contact, email_log in q:
if email_log.is_reply:
alias_info.nb_reply += 1
elif email_log.blocked:
alias_info.nb_blocked += 1
else:
alias_info.nb_forward += 1
if email_log.created_at > latest_activity:
latest_activity = email_log.created_at
latest_email_log = email_log
latest_contact = contact
alias_info.latest_contact = latest_contact
alias_info.latest_email_log = latest_email_log
return alias_info
try:
MAX_NB_EMAIL_FREE_PLAN = int(os.environ["MAX_NB_EMAIL_FREE_PLAN"])
except Exception:
print("MAX_NB_EMAIL_FREE_PLAN is not set, use 5 as default value")
MAX_NB_EMAIL_FREE_PLAN = 5
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
class AliasInTrashError(SLException):
"""raised when alias is deleted before"""
pass
LOG = _get_logger("SL")
class AliasGeneratorEnum(EnumE):
word = 1 # aliases are generated based on random words
uuid = 2 # aliases are generated based on uuid
class Alias(Base, ModelMixin):
__tablename__ = "alias"
FLAG_PARTNER_CREATED = 1 << 0
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, index=True
)
email = sa.Column(sa.String(128), unique=True, nullable=False)
# the name to use when user replies/sends from alias
name = sa.Column(sa.String(128), nullable=True, default=None)
enabled = sa.Column(sa.Boolean(), default=True, nullable=False)
flags = sa.Column(
sa.BigInteger(), default=0, server_default="0", nullable=False, index=True
)
custom_domain_id = sa.Column(
sa.ForeignKey("custom_domain.id", ondelete="cascade"), nullable=True, index=True
)
custom_domain = orm.relationship("CustomDomain", foreign_keys=[custom_domain_id])
# To know whether an alias is created "on the fly", i.e. via the custom domain catch-all feature
automatic_creation = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# to know whether an alias belongs to a directory
directory_id = sa.Column(
sa.ForeignKey("directory.id", ondelete="cascade"), nullable=True, index=True
)
note = sa.Column(sa.Text, default=None, nullable=True)
# an alias can be owned by another mailbox
mailbox_id = sa.Column(
sa.ForeignKey("mailbox.id", ondelete="cascade"), nullable=False, index=True
)
# prefix _ to avoid this object being used accidentally.
# To have the list of all mailboxes, should use AliasInfo instead
_mailboxes = orm.relationship("Mailbox", secondary="alias_mailbox", lazy="joined")
# If the mailbox has PGP-enabled, user can choose disable the PGP on the alias
# this is useful when some senders already support PGP
disable_pgp = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# a way to bypass the bounce automatic disable mechanism
cannot_be_disabled = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# when a mailbox wants to send an email on behalf of the alias via the reverse-alias
# several checks are performed to avoid email spoofing
# this option allow disabling these checks
disable_email_spoofing_check = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# to know whether an alias is added using a batch import
batch_import_id = sa.Column(
sa.ForeignKey("batch_import.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
# set in case of alias transfer.
original_owner_id = sa.Column(
sa.ForeignKey(User.id, ondelete="SET NULL"), nullable=True
)
# alias is pinned on top
pinned = sa.Column(sa.Boolean, nullable=False, default=False, server_default="0")
# used to transfer an alias to another user
transfer_token = sa.Column(sa.String(64), default=None, unique=True, nullable=True)
transfer_token_expiration = sa.Column(
ArrowType, default=arrow.utcnow, nullable=True
)
# have I been pwned
hibp_last_check = sa.Column(ArrowType, default=None, index=True)
hibp_breaches = orm.relationship("Hibp", secondary="alias_hibp")
# to use Postgres full text search. Only applied on "note" column for now
# this is a generated Postgres column
ts_vector = sa.Column(
TSVector(), sa.Computed("to_tsvector('english', note)", persisted=True)
)
last_email_log_id = sa.Column(sa.Integer, default=None, nullable=True)
__table_args__ = (
Index("ix_video___ts_vector__", ts_vector, postgresql_using="gin"),
# index on note column using pg_trgm
Index(
"note_pg_trgm_index",
"note",
postgresql_ops={"note": "gin_trgm_ops"},
postgresql_using="gin",
),
)
user = orm.relationship(User, foreign_keys=[user_id])
mailbox = orm.relationship("Mailbox", lazy="joined")
def mailboxes(self):
ret = [self.mailbox]
for m in self._mailboxes:
if m.id is not self.mailbox.id:
ret.append(m)
ret = [mb for mb in ret if mb.verified]
ret = sorted(ret, key=lambda mb: mb.email)
return ret
def authorized_addresses(self) -> [str]:
"""return addresses that can send on behalf of this alias, i.e. can send emails to this alias's reverse-aliases
Including its mailboxes and their authorized addresses
"""
mailboxes = self.mailboxes
ret = [mb.email for mb in mailboxes]
for mailbox in mailboxes:
for aa in mailbox.authorized_addresses:
ret.append(aa.email)
return ret
def mailbox_support_pgp(self) -> bool:
"""return True of one of the mailboxes support PGP"""
for mb in self.mailboxes:
if mb.pgp_enabled():
return True
return False
def pgp_enabled(self) -> bool:
if self.mailbox_support_pgp() and not self.disable_pgp:
return True
return False
def get_custom_domain(alias_address) -> Optional["CustomDomain"]:
alias_domain = validate_email(
alias_address, check_deliverability=False, allow_smtputf8=False
).domain
# handle the case a SLDomain is also a CustomDomain
if SLDomain.get_by(domain=alias_domain) is None:
custom_domain = CustomDomain.get_by(domain=alias_domain)
if custom_domain:
return custom_domain
def create(cls, **kw):
commit = kw.pop("commit", False)
flush = kw.pop("flush", False)
new_alias = cls(**kw)
user = User.get(new_alias.user_id)
if user.is_premium():
limits = config.ALIAS_CREATE_RATE_LIMIT_PAID
else:
limits = config.ALIAS_CREATE_RATE_LIMIT_FREE
# limits is array of (hits,days)
for limit in limits:
key = f"alias_create_{limit[1]}d:{user.id}"
rate_limiter.check_bucket_limit(key, limit[0], limit[1])
email = kw["email"]
# make sure email is lowercase and doesn't have any whitespace
email = sanitize_email(email)
# make sure alias is not in global trash, i.e. DeletedAlias table
if DeletedAlias.get_by(email=email):
raise AliasInTrashError
if DomainDeletedAlias.get_by(email=email):
raise AliasInTrashError
# detect whether alias should belong to a custom domain
if "custom_domain_id" not in kw:
custom_domain = Alias.get_custom_domain(email)
if custom_domain:
new_alias.custom_domain_id = custom_domain.id
Session.add(new_alias)
DailyMetric.get_or_create_today_metric().nb_alias += 1
if commit:
Session.commit()
if flush:
Session.flush()
return new_alias
def create_new(cls, user, prefix, note=None, mailbox_id=None):
prefix = prefix.lower().strip().replace(" ", "")
if not prefix:
raise Exception("alias prefix cannot be empty")
# find the right suffix - avoid infinite loop by running this at max 1000 times
for _ in range(1000):
suffix = user.get_random_alias_suffix()
email = f"{prefix}.{suffix}@{config.FIRST_ALIAS_DOMAIN}"
if available_sl_email(email):
break
return Alias.create(
user_id=user.id,
email=email,
note=note,
mailbox_id=mailbox_id or user.default_mailbox_id,
)
def delete(cls, obj_id):
raise Exception("should use delete_alias(alias,user) instead")
def create_new_random(
cls,
user,
scheme: int = AliasGeneratorEnum.word.value,
in_hex: bool = False,
note: str = None,
):
"""create a new random alias"""
custom_domain = None
random_email = None
if user.default_alias_custom_domain_id:
custom_domain = CustomDomain.get(user.default_alias_custom_domain_id)
random_email = generate_random_alias_email(
scheme=scheme, in_hex=in_hex, alias_domain=custom_domain.domain
)
elif user.default_alias_public_domain_id:
sl_domain: SLDomain = SLDomain.get(user.default_alias_public_domain_id)
if sl_domain.premium_only and not user.is_premium():
LOG.w("%s not premium, cannot use %s", user, sl_domain)
else:
random_email = generate_random_alias_email(
scheme=scheme, in_hex=in_hex, alias_domain=sl_domain.domain
)
if not random_email:
random_email = generate_random_alias_email(scheme=scheme, in_hex=in_hex)
alias = Alias.create(
user_id=user.id,
email=random_email,
mailbox_id=user.default_mailbox_id,
note=note,
)
if custom_domain:
alias.custom_domain_id = custom_domain.id
return alias
def mailbox_email(self):
if self.mailbox_id:
return self.mailbox.email
else:
return self.user.email
def __repr__(self):
return f"<Alias {self.id} {self.email}>"
class AliasUsedOn(Base, ModelMixin):
"""Used to know where an alias is created"""
__tablename__ = "alias_used_on"
__table_args__ = (
sa.UniqueConstraint("alias_id", "hostname", name="uq_alias_used"),
)
alias_id = sa.Column(
sa.ForeignKey(Alias.id, ondelete="cascade"), nullable=False, index=True
)
user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False)
alias = orm.relationship(Alias)
hostname = sa.Column(sa.String(1024), nullable=False)
def convert_to_id(s: str):
"""convert a string to id-like: remove space, remove special accent"""
s = s.lower()
s = unidecode(s)
s = s.replace(" ", "")
return s[:256]
The provided code snippet includes necessary dependencies for implementing the `new_random_alias` function. Write a Python function `def new_random_alias()` to solve the following problem:
Create a new random alias Input: (Optional) note Output: 201 if success
Here is the function:
def new_random_alias():
"""
Create a new random alias
Input:
(Optional) note
Output:
201 if success
"""
user = g.user
if not user.can_create_new_alias():
LOG.d("user %s cannot create new random alias", user)
return (
jsonify(
error=f"You have reached the limitation of a free account with the maximum of "
f"{MAX_NB_EMAIL_FREE_PLAN} aliases, please upgrade your plan to create more aliases"
),
400,
)
note = None
data = request.get_json(silent=True)
if data:
note = data.get("note")
alias = None
# custom alias suggestion and suffix
hostname = request.args.get("hostname")
if hostname and user.include_website_in_one_click_alias:
LOG.d("Use %s to create new alias", hostname)
# keep only the domain name of hostname, ignore TLD and subdomain
# for ex www.groupon.com -> groupon
ext = tldextract.extract(hostname)
prefix_suggestion = ext.domain
prefix_suggestion = convert_to_id(prefix_suggestion)
suffixes = get_alias_suffixes(user)
# use the first suffix
suggested_alias = prefix_suggestion + suffixes[0].suffix
alias = Alias.get_by(email=suggested_alias)
# cannot use this alias as it belongs to another user
if alias and not alias.user_id == user.id:
LOG.d("%s belongs to another user", alias)
alias = None
elif alias and alias.user_id == user.id:
# make sure alias was created for this website
if AliasUsedOn.get_by(
alias_id=alias.id, hostname=hostname, user_id=alias.user_id
):
LOG.d("Use existing alias %s", alias)
else:
LOG.d("%s wasn't created for this website %s", alias, hostname)
alias = None
elif not alias:
LOG.d("create new alias %s", suggested_alias)
try:
alias = Alias.create(
user_id=user.id,
email=suggested_alias,
note=note,
mailbox_id=user.default_mailbox_id,
commit=True,
)
except AliasInTrashError:
LOG.i("Alias %s is in trash", suggested_alias)
alias = None
if not alias:
scheme = user.alias_generator
mode = request.args.get("mode")
if mode:
if mode == "word":
scheme = AliasGeneratorEnum.word.value
elif mode == "uuid":
scheme = AliasGeneratorEnum.uuid.value
else:
return jsonify(error=f"{mode} must be either word or uuid"), 400
alias = Alias.create_new_random(user=user, scheme=scheme, note=note)
Session.commit()
if hostname and not AliasUsedOn.get_by(alias_id=alias.id, hostname=hostname):
AliasUsedOn.create(
alias_id=alias.id, hostname=hostname, user_id=alias.user_id, commit=True
)
return (
jsonify(alias=alias.email, **serialize_alias_info_v2(get_alias_info_v2(alias))),
201,
) | Create a new random alias Input: (Optional) note Output: 201 if success |
180,580 | from smtplib import SMTPRecipientsRefused
import arrow
from flask import g
from flask import jsonify
from flask import request
from app.api.base import api_bp, require_api_auth
from app.config import JOB_DELETE_MAILBOX
from app.dashboard.views.mailbox import send_verification_email
from app.dashboard.views.mailbox_detail import verify_mailbox_change
from app.db import Session
from app.email_utils import (
mailbox_already_used,
email_can_be_used_as_mailbox,
)
from app.email_validation import is_valid_email
from app.log import LOG
from app.models import Mailbox, Job
from app.utils import sanitize_email
def mailbox_to_dict(mailbox: Mailbox):
return {
"id": mailbox.id,
"email": mailbox.email,
"verified": mailbox.verified,
"default": mailbox.user.default_mailbox_id == mailbox.id,
"creation_timestamp": mailbox.created_at.timestamp,
"nb_alias": mailbox.nb_alias(),
}
def send_verification_email(user, mailbox):
s = TimestampSigner(MAILBOX_SECRET)
encoded_data = json.dumps([mailbox.id, mailbox.email]).encode("utf-8")
b64_data = base64.urlsafe_b64encode(encoded_data)
mailbox_id_signed = s.sign(b64_data).decode()
verification_url = (
URL + "/dashboard/mailbox_verify" + f"?mailbox_id={mailbox_id_signed}"
)
send_email(
mailbox.email,
f"Please confirm your mailbox {mailbox.email}",
render(
"transactional/verify-mailbox.txt.jinja2",
user=user,
link=verification_url,
mailbox_email=mailbox.email,
),
render(
"transactional/verify-mailbox.html",
user=user,
link=verification_url,
mailbox_email=mailbox.email,
),
)
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
def email_can_be_used_as_mailbox(email_address: str) -> bool:
"""Return True if an email can be used as a personal email.
Use the email domain as criteria. A domain can be used if it is not:
- one of ALIAS_DOMAINS
- one of PREMIUM_ALIAS_DOMAINS
- one of custom domains
- a disposable domain
"""
try:
domain = validate_email(
email_address, check_deliverability=False, allow_smtputf8=False
).domain
except EmailNotValidError:
LOG.d("%s is invalid email address", email_address)
return False
if not domain:
LOG.d("no valid domain associated to %s", email_address)
return False
if SLDomain.get_by(domain=domain):
LOG.d("%s is a SL domain", email_address)
return False
from app.models import CustomDomain
if CustomDomain.get_by(domain=domain, verified=True):
LOG.d("domain %s is a SimpleLogin custom domain", domain)
return False
if is_invalid_mailbox_domain(domain):
LOG.d("Domain %s is invalid mailbox domain", domain)
return False
# check if email MX domain is disposable
mx_domains = get_mx_domain_list(domain)
# if no MX record, email is not valid
if not config.SKIP_MX_LOOKUP_ON_CHECK and not mx_domains:
LOG.d("No MX record for domain %s", domain)
return False
for mx_domain in mx_domains:
if is_invalid_mailbox_domain(mx_domain):
LOG.d("MX Domain %s %s is invalid mailbox domain", mx_domain, domain)
return False
existing_user = User.get_by(email=email_address)
if existing_user and existing_user.disabled:
LOG.d(
f"User {existing_user} is disabled. {email_address} cannot be used for other mailbox"
)
return False
for existing_user in (
User.query()
.join(Mailbox, User.id == Mailbox.user_id)
.filter(Mailbox.email == email_address)
.group_by(User.id)
.all()
):
if existing_user.disabled:
LOG.d(
f"User {existing_user} is disabled and has a mailbox with {email_address}. Id cannot be used for other mailbox"
)
return False
return True
def mailbox_already_used(email: str, user) -> bool:
if Mailbox.get_by(email=email, user_id=user.id):
return True
# support the case user wants to re-add their real email as mailbox
# can happen when user changes their root email and wants to add this new email as mailbox
if email == user.email:
return False
return False
def is_valid_email(email_address: str) -> bool:
"""
Used to check whether an email address is valid
NOT run MX check.
NOT allow unicode.
"""
try:
validate_email(email_address, check_deliverability=False, allow_smtputf8=False)
return True
except EmailNotValidError:
return False
class Mailbox(Base, ModelMixin):
__tablename__ = "mailbox"
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, index=True
)
email = sa.Column(sa.String(256), nullable=False, index=True)
verified = sa.Column(sa.Boolean, default=False, nullable=False)
force_spf = sa.Column(sa.Boolean, default=True, server_default="1", nullable=False)
# used when user wants to update mailbox email
new_email = sa.Column(sa.String(256), unique=True)
pgp_public_key = sa.Column(sa.Text, nullable=True)
pgp_finger_print = sa.Column(sa.String(512), nullable=True)
disable_pgp = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# incremented when a check is failed on the mailbox
# alert when the number exceeds a threshold
# used in sanity_check()
nb_failed_checks = sa.Column(
sa.Integer, default=0, server_default="0", nullable=False
)
# a mailbox can be disabled if it can't be reached
disabled = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0")
generic_subject = sa.Column(sa.String(78), nullable=True)
__table_args__ = (sa.UniqueConstraint("user_id", "email", name="uq_mailbox_user"),)
user = orm.relationship(User, foreign_keys=[user_id])
def pgp_enabled(self) -> bool:
if self.pgp_finger_print and not self.disable_pgp:
return True
return False
def nb_alias(self):
return (
AliasMailbox.filter_by(mailbox_id=self.id).count()
+ Alias.filter_by(mailbox_id=self.id).count()
)
def is_proton(self) -> bool:
if (
self.email.endswith("@proton.me")
or self.email.endswith("@protonmail.com")
or self.email.endswith("@protonmail.ch")
or self.email.endswith("@proton.ch")
or self.email.endswith("@pm.me")
):
return True
from app.email_utils import get_email_local_part
mx_domains: [(int, str)] = get_mx_domains(get_email_local_part(self.email))
# Proton is the first domain
if mx_domains and mx_domains[0][1] in (
"mail.protonmail.ch.",
"mailsec.protonmail.ch.",
):
return True
return False
def delete(cls, obj_id):
mailbox: Mailbox = cls.get(obj_id)
user = mailbox.user
# Put all aliases belonging to this mailbox to global or domain trash
for alias in Alias.filter_by(mailbox_id=obj_id):
# special handling for alias that has several mailboxes and has mailbox_id=obj_id
if len(alias.mailboxes) > 1:
# use the first mailbox found in alias._mailboxes
first_mb = alias._mailboxes[0]
alias.mailbox_id = first_mb.id
alias._mailboxes.remove(first_mb)
else:
from app import alias_utils
# only put aliases that have mailbox as a single mailbox into trash
alias_utils.delete_alias(alias, user)
Session.commit()
cls.filter(cls.id == obj_id).delete()
Session.commit()
def aliases(self) -> [Alias]:
ret = Alias.filter_by(mailbox_id=self.id).all()
for am in AliasMailbox.filter_by(mailbox_id=self.id):
ret.append(am.alias)
return ret
def create(cls, **kw):
if "email" in kw:
kw["email"] = sanitize_email(kw["email"])
return super().create(**kw)
def __repr__(self):
return f"<Mailbox {self.id} {self.email}>"
def sanitize_email(email_address: str, not_lower=False) -> str:
if email_address:
email_address = email_address.strip().replace(" ", "").replace("\n", " ")
if not not_lower:
email_address = email_address.lower()
return email_address.replace("\u200f", "")
The provided code snippet includes necessary dependencies for implementing the `create_mailbox` function. Write a Python function `def create_mailbox()` to solve the following problem:
Create a new mailbox. User needs to verify the mailbox via an activation email. Input: email: in body Output: the new mailbox dict
Here is the function:
def create_mailbox():
"""
Create a new mailbox. User needs to verify the mailbox via an activation email.
Input:
email: in body
Output:
the new mailbox dict
"""
user = g.user
mailbox_email = sanitize_email(request.get_json().get("email"))
if not user.is_premium():
return jsonify(error="Only premium plan can add additional mailbox"), 400
if not is_valid_email(mailbox_email):
return jsonify(error=f"{mailbox_email} invalid"), 400
elif mailbox_already_used(mailbox_email, user):
return jsonify(error=f"{mailbox_email} already used"), 400
elif not email_can_be_used_as_mailbox(mailbox_email):
return (
jsonify(
error=f"{mailbox_email} cannot be used. Please note a mailbox cannot "
f"be a disposable email address"
),
400,
)
else:
new_mailbox = Mailbox.create(email=mailbox_email, user_id=user.id)
Session.commit()
send_verification_email(user, new_mailbox)
return (
jsonify(mailbox_to_dict(new_mailbox)),
201,
) | Create a new mailbox. User needs to verify the mailbox via an activation email. Input: email: in body Output: the new mailbox dict |
180,581 | from smtplib import SMTPRecipientsRefused
import arrow
from flask import g
from flask import jsonify
from flask import request
from app.api.base import api_bp, require_api_auth
from app.config import JOB_DELETE_MAILBOX
from app.dashboard.views.mailbox import send_verification_email
from app.dashboard.views.mailbox_detail import verify_mailbox_change
from app.db import Session
from app.email_utils import (
mailbox_already_used,
email_can_be_used_as_mailbox,
)
from app.email_validation import is_valid_email
from app.log import LOG
from app.models import Mailbox, Job
from app.utils import sanitize_email
JOB_DELETE_MAILBOX = "delete-mailbox"
LOG = _get_logger("SL")
class Job(Base, ModelMixin):
"""Used to schedule one-time job in the future"""
__tablename__ = "job"
name = sa.Column(sa.String(128), nullable=False)
payload = sa.Column(sa.JSON)
# whether the job has been taken by the job runner
taken = sa.Column(sa.Boolean, default=False, nullable=False)
run_at = sa.Column(ArrowType)
state = sa.Column(
sa.Integer,
nullable=False,
server_default=str(JobState.ready.value),
default=JobState.ready.value,
index=True,
)
attempts = sa.Column(sa.Integer, nullable=False, server_default="0", default=0)
taken_at = sa.Column(ArrowType, nullable=True)
__table_args__ = (Index("ix_state_run_at_taken_at", state, run_at, taken_at),)
def __repr__(self):
return f"<Job {self.id} {self.name} {self.payload}>"
class Mailbox(Base, ModelMixin):
__tablename__ = "mailbox"
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, index=True
)
email = sa.Column(sa.String(256), nullable=False, index=True)
verified = sa.Column(sa.Boolean, default=False, nullable=False)
force_spf = sa.Column(sa.Boolean, default=True, server_default="1", nullable=False)
# used when user wants to update mailbox email
new_email = sa.Column(sa.String(256), unique=True)
pgp_public_key = sa.Column(sa.Text, nullable=True)
pgp_finger_print = sa.Column(sa.String(512), nullable=True)
disable_pgp = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# incremented when a check is failed on the mailbox
# alert when the number exceeds a threshold
# used in sanity_check()
nb_failed_checks = sa.Column(
sa.Integer, default=0, server_default="0", nullable=False
)
# a mailbox can be disabled if it can't be reached
disabled = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0")
generic_subject = sa.Column(sa.String(78), nullable=True)
__table_args__ = (sa.UniqueConstraint("user_id", "email", name="uq_mailbox_user"),)
user = orm.relationship(User, foreign_keys=[user_id])
def pgp_enabled(self) -> bool:
if self.pgp_finger_print and not self.disable_pgp:
return True
return False
def nb_alias(self):
return (
AliasMailbox.filter_by(mailbox_id=self.id).count()
+ Alias.filter_by(mailbox_id=self.id).count()
)
def is_proton(self) -> bool:
if (
self.email.endswith("@proton.me")
or self.email.endswith("@protonmail.com")
or self.email.endswith("@protonmail.ch")
or self.email.endswith("@proton.ch")
or self.email.endswith("@pm.me")
):
return True
from app.email_utils import get_email_local_part
mx_domains: [(int, str)] = get_mx_domains(get_email_local_part(self.email))
# Proton is the first domain
if mx_domains and mx_domains[0][1] in (
"mail.protonmail.ch.",
"mailsec.protonmail.ch.",
):
return True
return False
def delete(cls, obj_id):
mailbox: Mailbox = cls.get(obj_id)
user = mailbox.user
# Put all aliases belonging to this mailbox to global or domain trash
for alias in Alias.filter_by(mailbox_id=obj_id):
# special handling for alias that has several mailboxes and has mailbox_id=obj_id
if len(alias.mailboxes) > 1:
# use the first mailbox found in alias._mailboxes
first_mb = alias._mailboxes[0]
alias.mailbox_id = first_mb.id
alias._mailboxes.remove(first_mb)
else:
from app import alias_utils
# only put aliases that have mailbox as a single mailbox into trash
alias_utils.delete_alias(alias, user)
Session.commit()
cls.filter(cls.id == obj_id).delete()
Session.commit()
def aliases(self) -> [Alias]:
ret = Alias.filter_by(mailbox_id=self.id).all()
for am in AliasMailbox.filter_by(mailbox_id=self.id):
ret.append(am.alias)
return ret
def create(cls, **kw):
if "email" in kw:
kw["email"] = sanitize_email(kw["email"])
return super().create(**kw)
def __repr__(self):
return f"<Mailbox {self.id} {self.email}>"
The provided code snippet includes necessary dependencies for implementing the `delete_mailbox` function. Write a Python function `def delete_mailbox(mailbox_id)` to solve the following problem:
Delete mailbox Input: mailbox_id: in url (optional) transfer_aliases_to: in body. Id of the new mailbox for the aliases. If omitted or the value is set to -1, the aliases of the mailbox will be deleted too. Output: 200 if deleted successfully
Here is the function:
def delete_mailbox(mailbox_id):
"""
Delete mailbox
Input:
mailbox_id: in url
(optional) transfer_aliases_to: in body. Id of the new mailbox for the aliases.
If omitted or the value is set to -1,
the aliases of the mailbox will be deleted too.
Output:
200 if deleted successfully
"""
user = g.user
mailbox = Mailbox.get(mailbox_id)
if not mailbox or mailbox.user_id != user.id:
return jsonify(error="Forbidden"), 403
if mailbox.id == user.default_mailbox_id:
return jsonify(error="You cannot delete the default mailbox"), 400
data = request.get_json() or {}
transfer_mailbox_id = data.get("transfer_aliases_to")
if transfer_mailbox_id and int(transfer_mailbox_id) >= 0:
transfer_mailbox = Mailbox.get(transfer_mailbox_id)
if not transfer_mailbox or transfer_mailbox.user_id != user.id:
return (
jsonify(error="You must transfer the aliases to a mailbox you own."),
403,
)
if transfer_mailbox_id == mailbox_id:
return (
jsonify(
error="You can not transfer the aliases to the mailbox you want to delete."
),
400,
)
if not transfer_mailbox.verified:
return jsonify(error="Your new mailbox is not verified"), 400
# Schedule delete account job
LOG.w("schedule delete mailbox job for %s", mailbox)
Job.create(
name=JOB_DELETE_MAILBOX,
payload={
"mailbox_id": mailbox.id,
"transfer_mailbox_id": transfer_mailbox_id,
},
run_at=arrow.now(),
commit=True,
)
return jsonify(deleted=True), 200 | Delete mailbox Input: mailbox_id: in url (optional) transfer_aliases_to: in body. Id of the new mailbox for the aliases. If omitted or the value is set to -1, the aliases of the mailbox will be deleted too. Output: 200 if deleted successfully |
180,582 | from smtplib import SMTPRecipientsRefused
import arrow
from flask import g
from flask import jsonify
from flask import request
from app.api.base import api_bp, require_api_auth
from app.config import JOB_DELETE_MAILBOX
from app.dashboard.views.mailbox import send_verification_email
from app.dashboard.views.mailbox_detail import verify_mailbox_change
from app.db import Session
from app.email_utils import (
mailbox_already_used,
email_can_be_used_as_mailbox,
)
from app.email_validation import is_valid_email
from app.log import LOG
from app.models import Mailbox, Job
from app.utils import sanitize_email
def verify_mailbox_change(user, mailbox, new_email):
s = TimestampSigner(MAILBOX_SECRET)
mailbox_id_signed = s.sign(str(mailbox.id)).decode()
verification_url = (
f"{URL}/dashboard/mailbox/confirm_change?mailbox_id={mailbox_id_signed}"
)
send_email(
new_email,
"Confirm mailbox change on SimpleLogin",
render(
"transactional/verify-mailbox-change.txt.jinja2",
user=user,
link=verification_url,
mailbox_email=mailbox.email,
mailbox_new_email=new_email,
),
render(
"transactional/verify-mailbox-change.html",
user=user,
link=verification_url,
mailbox_email=mailbox.email,
mailbox_new_email=new_email,
),
)
"/mailbox/<int:mailbox_id>/cancel_email_change", methods=["GET", "POST"]
)
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
def email_can_be_used_as_mailbox(email_address: str) -> bool:
"""Return True if an email can be used as a personal email.
Use the email domain as criteria. A domain can be used if it is not:
- one of ALIAS_DOMAINS
- one of PREMIUM_ALIAS_DOMAINS
- one of custom domains
- a disposable domain
"""
try:
domain = validate_email(
email_address, check_deliverability=False, allow_smtputf8=False
).domain
except EmailNotValidError:
LOG.d("%s is invalid email address", email_address)
return False
if not domain:
LOG.d("no valid domain associated to %s", email_address)
return False
if SLDomain.get_by(domain=domain):
LOG.d("%s is a SL domain", email_address)
return False
from app.models import CustomDomain
if CustomDomain.get_by(domain=domain, verified=True):
LOG.d("domain %s is a SimpleLogin custom domain", domain)
return False
if is_invalid_mailbox_domain(domain):
LOG.d("Domain %s is invalid mailbox domain", domain)
return False
# check if email MX domain is disposable
mx_domains = get_mx_domain_list(domain)
# if no MX record, email is not valid
if not config.SKIP_MX_LOOKUP_ON_CHECK and not mx_domains:
LOG.d("No MX record for domain %s", domain)
return False
for mx_domain in mx_domains:
if is_invalid_mailbox_domain(mx_domain):
LOG.d("MX Domain %s %s is invalid mailbox domain", mx_domain, domain)
return False
existing_user = User.get_by(email=email_address)
if existing_user and existing_user.disabled:
LOG.d(
f"User {existing_user} is disabled. {email_address} cannot be used for other mailbox"
)
return False
for existing_user in (
User.query()
.join(Mailbox, User.id == Mailbox.user_id)
.filter(Mailbox.email == email_address)
.group_by(User.id)
.all()
):
if existing_user.disabled:
LOG.d(
f"User {existing_user} is disabled and has a mailbox with {email_address}. Id cannot be used for other mailbox"
)
return False
return True
def mailbox_already_used(email: str, user) -> bool:
if Mailbox.get_by(email=email, user_id=user.id):
return True
# support the case user wants to re-add their real email as mailbox
# can happen when user changes their root email and wants to add this new email as mailbox
if email == user.email:
return False
return False
class Mailbox(Base, ModelMixin):
__tablename__ = "mailbox"
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, index=True
)
email = sa.Column(sa.String(256), nullable=False, index=True)
verified = sa.Column(sa.Boolean, default=False, nullable=False)
force_spf = sa.Column(sa.Boolean, default=True, server_default="1", nullable=False)
# used when user wants to update mailbox email
new_email = sa.Column(sa.String(256), unique=True)
pgp_public_key = sa.Column(sa.Text, nullable=True)
pgp_finger_print = sa.Column(sa.String(512), nullable=True)
disable_pgp = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# incremented when a check is failed on the mailbox
# alert when the number exceeds a threshold
# used in sanity_check()
nb_failed_checks = sa.Column(
sa.Integer, default=0, server_default="0", nullable=False
)
# a mailbox can be disabled if it can't be reached
disabled = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0")
generic_subject = sa.Column(sa.String(78), nullable=True)
__table_args__ = (sa.UniqueConstraint("user_id", "email", name="uq_mailbox_user"),)
user = orm.relationship(User, foreign_keys=[user_id])
def pgp_enabled(self) -> bool:
if self.pgp_finger_print and not self.disable_pgp:
return True
return False
def nb_alias(self):
return (
AliasMailbox.filter_by(mailbox_id=self.id).count()
+ Alias.filter_by(mailbox_id=self.id).count()
)
def is_proton(self) -> bool:
if (
self.email.endswith("@proton.me")
or self.email.endswith("@protonmail.com")
or self.email.endswith("@protonmail.ch")
or self.email.endswith("@proton.ch")
or self.email.endswith("@pm.me")
):
return True
from app.email_utils import get_email_local_part
mx_domains: [(int, str)] = get_mx_domains(get_email_local_part(self.email))
# Proton is the first domain
if mx_domains and mx_domains[0][1] in (
"mail.protonmail.ch.",
"mailsec.protonmail.ch.",
):
return True
return False
def delete(cls, obj_id):
mailbox: Mailbox = cls.get(obj_id)
user = mailbox.user
# Put all aliases belonging to this mailbox to global or domain trash
for alias in Alias.filter_by(mailbox_id=obj_id):
# special handling for alias that has several mailboxes and has mailbox_id=obj_id
if len(alias.mailboxes) > 1:
# use the first mailbox found in alias._mailboxes
first_mb = alias._mailboxes[0]
alias.mailbox_id = first_mb.id
alias._mailboxes.remove(first_mb)
else:
from app import alias_utils
# only put aliases that have mailbox as a single mailbox into trash
alias_utils.delete_alias(alias, user)
Session.commit()
cls.filter(cls.id == obj_id).delete()
Session.commit()
def aliases(self) -> [Alias]:
ret = Alias.filter_by(mailbox_id=self.id).all()
for am in AliasMailbox.filter_by(mailbox_id=self.id):
ret.append(am.alias)
return ret
def create(cls, **kw):
if "email" in kw:
kw["email"] = sanitize_email(kw["email"])
return super().create(**kw)
def __repr__(self):
return f"<Mailbox {self.id} {self.email}>"
def sanitize_email(email_address: str, not_lower=False) -> str:
if email_address:
email_address = email_address.strip().replace(" ", "").replace("\n", " ")
if not not_lower:
email_address = email_address.lower()
return email_address.replace("\u200f", "")
The provided code snippet includes necessary dependencies for implementing the `update_mailbox` function. Write a Python function `def update_mailbox(mailbox_id)` to solve the following problem:
Update mailbox Input: mailbox_id: in url (optional) default: in body. Set a mailbox as the default mailbox. (optional) email: in body. Change a mailbox email. (optional) cancel_email_change: in body. Cancel mailbox email change. Output: 200 if updated successfully
Here is the function:
def update_mailbox(mailbox_id):
"""
Update mailbox
Input:
mailbox_id: in url
(optional) default: in body. Set a mailbox as the default mailbox.
(optional) email: in body. Change a mailbox email.
(optional) cancel_email_change: in body. Cancel mailbox email change.
Output:
200 if updated successfully
"""
user = g.user
mailbox = Mailbox.get(mailbox_id)
if not mailbox or mailbox.user_id != user.id:
return jsonify(error="Forbidden"), 403
data = request.get_json() or {}
changed = False
if "default" in data:
is_default = data.get("default")
if is_default:
if not mailbox.verified:
return (
jsonify(
error="Unverified mailbox cannot be used as default mailbox"
),
400,
)
user.default_mailbox_id = mailbox.id
changed = True
if "email" in data:
new_email = sanitize_email(data.get("email"))
if mailbox_already_used(new_email, user):
return jsonify(error=f"{new_email} already used"), 400
elif not email_can_be_used_as_mailbox(new_email):
return (
jsonify(
error=f"{new_email} cannot be used. Please note a mailbox cannot "
f"be a disposable email address"
),
400,
)
try:
verify_mailbox_change(user, mailbox, new_email)
except SMTPRecipientsRefused:
return jsonify(error=f"Incorrect mailbox, please recheck {new_email}"), 400
else:
mailbox.new_email = new_email
changed = True
if "cancel_email_change" in data:
cancel_email_change = data.get("cancel_email_change")
if cancel_email_change:
mailbox.new_email = None
changed = True
if changed:
Session.commit()
return jsonify(updated=True), 200 | Update mailbox Input: mailbox_id: in url (optional) default: in body. Set a mailbox as the default mailbox. (optional) email: in body. Change a mailbox email. (optional) cancel_email_change: in body. Cancel mailbox email change. Output: 200 if updated successfully |
180,583 | from smtplib import SMTPRecipientsRefused
import arrow
from flask import g
from flask import jsonify
from flask import request
from app.api.base import api_bp, require_api_auth
from app.config import JOB_DELETE_MAILBOX
from app.dashboard.views.mailbox import send_verification_email
from app.dashboard.views.mailbox_detail import verify_mailbox_change
from app.db import Session
from app.email_utils import (
mailbox_already_used,
email_can_be_used_as_mailbox,
)
from app.email_validation import is_valid_email
from app.log import LOG
from app.models import Mailbox, Job
from app.utils import sanitize_email
def mailbox_to_dict(mailbox: Mailbox):
return {
"id": mailbox.id,
"email": mailbox.email,
"verified": mailbox.verified,
"default": mailbox.user.default_mailbox_id == mailbox.id,
"creation_timestamp": mailbox.created_at.timestamp,
"nb_alias": mailbox.nb_alias(),
}
The provided code snippet includes necessary dependencies for implementing the `get_mailboxes` function. Write a Python function `def get_mailboxes()` to solve the following problem:
Get verified mailboxes Output: - mailboxes: list of mailbox dict
Here is the function:
def get_mailboxes():
"""
Get verified mailboxes
Output:
- mailboxes: list of mailbox dict
"""
user = g.user
return (
jsonify(mailboxes=[mailbox_to_dict(mb) for mb in user.mailboxes()]),
200,
) | Get verified mailboxes Output: - mailboxes: list of mailbox dict |
180,584 | from smtplib import SMTPRecipientsRefused
import arrow
from flask import g
from flask import jsonify
from flask import request
from app.api.base import api_bp, require_api_auth
from app.config import JOB_DELETE_MAILBOX
from app.dashboard.views.mailbox import send_verification_email
from app.dashboard.views.mailbox_detail import verify_mailbox_change
from app.db import Session
from app.email_utils import (
mailbox_already_used,
email_can_be_used_as_mailbox,
)
from app.email_validation import is_valid_email
from app.log import LOG
from app.models import Mailbox, Job
from app.utils import sanitize_email
def mailbox_to_dict(mailbox: Mailbox):
return {
"id": mailbox.id,
"email": mailbox.email,
"verified": mailbox.verified,
"default": mailbox.user.default_mailbox_id == mailbox.id,
"creation_timestamp": mailbox.created_at.timestamp,
"nb_alias": mailbox.nb_alias(),
}
class Mailbox(Base, ModelMixin):
__tablename__ = "mailbox"
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, index=True
)
email = sa.Column(sa.String(256), nullable=False, index=True)
verified = sa.Column(sa.Boolean, default=False, nullable=False)
force_spf = sa.Column(sa.Boolean, default=True, server_default="1", nullable=False)
# used when user wants to update mailbox email
new_email = sa.Column(sa.String(256), unique=True)
pgp_public_key = sa.Column(sa.Text, nullable=True)
pgp_finger_print = sa.Column(sa.String(512), nullable=True)
disable_pgp = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# incremented when a check is failed on the mailbox
# alert when the number exceeds a threshold
# used in sanity_check()
nb_failed_checks = sa.Column(
sa.Integer, default=0, server_default="0", nullable=False
)
# a mailbox can be disabled if it can't be reached
disabled = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0")
generic_subject = sa.Column(sa.String(78), nullable=True)
__table_args__ = (sa.UniqueConstraint("user_id", "email", name="uq_mailbox_user"),)
user = orm.relationship(User, foreign_keys=[user_id])
def pgp_enabled(self) -> bool:
if self.pgp_finger_print and not self.disable_pgp:
return True
return False
def nb_alias(self):
return (
AliasMailbox.filter_by(mailbox_id=self.id).count()
+ Alias.filter_by(mailbox_id=self.id).count()
)
def is_proton(self) -> bool:
if (
self.email.endswith("@proton.me")
or self.email.endswith("@protonmail.com")
or self.email.endswith("@protonmail.ch")
or self.email.endswith("@proton.ch")
or self.email.endswith("@pm.me")
):
return True
from app.email_utils import get_email_local_part
mx_domains: [(int, str)] = get_mx_domains(get_email_local_part(self.email))
# Proton is the first domain
if mx_domains and mx_domains[0][1] in (
"mail.protonmail.ch.",
"mailsec.protonmail.ch.",
):
return True
return False
def delete(cls, obj_id):
mailbox: Mailbox = cls.get(obj_id)
user = mailbox.user
# Put all aliases belonging to this mailbox to global or domain trash
for alias in Alias.filter_by(mailbox_id=obj_id):
# special handling for alias that has several mailboxes and has mailbox_id=obj_id
if len(alias.mailboxes) > 1:
# use the first mailbox found in alias._mailboxes
first_mb = alias._mailboxes[0]
alias.mailbox_id = first_mb.id
alias._mailboxes.remove(first_mb)
else:
from app import alias_utils
# only put aliases that have mailbox as a single mailbox into trash
alias_utils.delete_alias(alias, user)
Session.commit()
cls.filter(cls.id == obj_id).delete()
Session.commit()
def aliases(self) -> [Alias]:
ret = Alias.filter_by(mailbox_id=self.id).all()
for am in AliasMailbox.filter_by(mailbox_id=self.id):
ret.append(am.alias)
return ret
def create(cls, **kw):
if "email" in kw:
kw["email"] = sanitize_email(kw["email"])
return super().create(**kw)
def __repr__(self):
return f"<Mailbox {self.id} {self.email}>"
The provided code snippet includes necessary dependencies for implementing the `get_mailboxes_v2` function. Write a Python function `def get_mailboxes_v2()` to solve the following problem:
Get all mailboxes - including unverified mailboxes Output: - mailboxes: list of mailbox dict
Here is the function:
def get_mailboxes_v2():
"""
Get all mailboxes - including unverified mailboxes
Output:
- mailboxes: list of mailbox dict
"""
user = g.user
mailboxes = []
for mailbox in Mailbox.filter_by(user_id=user.id):
mailboxes.append(mailbox)
return (
jsonify(mailboxes=[mailbox_to_dict(mb) for mb in mailboxes]),
200,
) | Get all mailboxes - including unverified mailboxes Output: - mailboxes: list of mailbox dict |
180,585 | from deprecated import deprecated
from flask import g
from flask import jsonify
from flask import request
from app import alias_utils
from app.api.base import api_bp, require_api_auth
from app.api.serializer import (
AliasInfo,
serialize_alias_info,
serialize_contact,
get_alias_infos_with_pagination,
get_alias_contacts,
serialize_alias_info_v2,
get_alias_info_v2,
get_alias_infos_with_pagination_v3,
)
from app.dashboard.views.alias_contact_manager import create_contact
from app.dashboard.views.alias_log import get_alias_log
from app.db import Session
from app.errors import (
CannotCreateContactForReverseAlias,
ErrContactErrorUpgradeNeeded,
ErrContactAlreadyExists,
ErrAddressInvalid,
)
from app.extensions import limiter
from app.models import Alias, Contact, Mailbox, AliasMailbox
class AliasInfo:
alias: Alias
mailbox: Mailbox
mailboxes: [Mailbox]
nb_forward: int
nb_blocked: int
nb_reply: int
latest_email_log: EmailLog = None
latest_contact: Contact = None
custom_domain: Optional[CustomDomain] = None
def contain_mailbox(self, mailbox_id: int) -> bool:
return mailbox_id in [m.id for m in self.mailboxes]
def serialize_alias_info(alias_info: AliasInfo) -> dict:
return {
# Alias field
"id": alias_info.alias.id,
"email": alias_info.alias.email,
"creation_date": alias_info.alias.created_at.format(),
"creation_timestamp": alias_info.alias.created_at.timestamp,
"enabled": alias_info.alias.enabled,
"note": alias_info.alias.note,
# activity
"nb_forward": alias_info.nb_forward,
"nb_block": alias_info.nb_blocked,
"nb_reply": alias_info.nb_reply,
}
def get_alias_infos_with_pagination(user, page_id=0, query=None) -> [AliasInfo]:
ret = []
q = (
Session.query(Alias)
.options(joinedload(Alias.mailbox))
.filter(Alias.user_id == user.id)
.order_by(Alias.created_at.desc())
)
if query:
q = q.filter(
or_(Alias.email.ilike(f"%{query}%"), Alias.note.ilike(f"%{query}%"))
)
q = q.limit(PAGE_LIMIT).offset(page_id * PAGE_LIMIT)
for alias in q:
ret.append(get_alias_info(alias))
return ret
The provided code snippet includes necessary dependencies for implementing the `get_aliases` function. Write a Python function `def get_aliases()` to solve the following problem:
Get aliases Input: page_id: in query Output: - aliases: list of alias: - id - email - creation_date - creation_timestamp - nb_forward - nb_block - nb_reply - note
Here is the function:
def get_aliases():
"""
Get aliases
Input:
page_id: in query
Output:
- aliases: list of alias:
- id
- email
- creation_date
- creation_timestamp
- nb_forward
- nb_block
- nb_reply
- note
"""
user = g.user
try:
page_id = int(request.args.get("page_id"))
except (ValueError, TypeError):
return jsonify(error="page_id must be provided in request query"), 400
query = None
data = request.get_json(silent=True)
if data:
query = data.get("query")
alias_infos: [AliasInfo] = get_alias_infos_with_pagination(
user, page_id=page_id, query=query
)
return (
jsonify(
aliases=[serialize_alias_info(alias_info) for alias_info in alias_infos]
),
200,
) | Get aliases Input: page_id: in query Output: - aliases: list of alias: - id - email - creation_date - creation_timestamp - nb_forward - nb_block - nb_reply - note |
180,586 | from deprecated import deprecated
from flask import g
from flask import jsonify
from flask import request
from app import alias_utils
from app.api.base import api_bp, require_api_auth
from app.api.serializer import (
AliasInfo,
serialize_alias_info,
serialize_contact,
get_alias_infos_with_pagination,
get_alias_contacts,
serialize_alias_info_v2,
get_alias_info_v2,
get_alias_infos_with_pagination_v3,
)
from app.dashboard.views.alias_contact_manager import create_contact
from app.dashboard.views.alias_log import get_alias_log
from app.db import Session
from app.errors import (
CannotCreateContactForReverseAlias,
ErrContactErrorUpgradeNeeded,
ErrContactAlreadyExists,
ErrAddressInvalid,
)
from app.extensions import limiter
from app.models import Alias, Contact, Mailbox, AliasMailbox
class AliasInfo:
alias: Alias
mailbox: Mailbox
mailboxes: [Mailbox]
nb_forward: int
nb_blocked: int
nb_reply: int
latest_email_log: EmailLog = None
latest_contact: Contact = None
custom_domain: Optional[CustomDomain] = None
def contain_mailbox(self, mailbox_id: int) -> bool:
return mailbox_id in [m.id for m in self.mailboxes]
def serialize_alias_info_v2(alias_info: AliasInfo) -> dict:
res = {
# Alias field
"id": alias_info.alias.id,
"email": alias_info.alias.email,
"creation_date": alias_info.alias.created_at.format(),
"creation_timestamp": alias_info.alias.created_at.timestamp,
"enabled": alias_info.alias.enabled,
"note": alias_info.alias.note,
"name": alias_info.alias.name,
# activity
"nb_forward": alias_info.nb_forward,
"nb_block": alias_info.nb_blocked,
"nb_reply": alias_info.nb_reply,
# mailbox
"mailbox": {"id": alias_info.mailbox.id, "email": alias_info.mailbox.email},
"mailboxes": [
{"id": mailbox.id, "email": mailbox.email}
for mailbox in alias_info.mailboxes
],
"support_pgp": alias_info.alias.mailbox_support_pgp(),
"disable_pgp": alias_info.alias.disable_pgp,
"latest_activity": None,
"pinned": alias_info.alias.pinned,
}
if alias_info.latest_email_log:
email_log = alias_info.latest_email_log
contact = alias_info.latest_contact
# latest activity
res["latest_activity"] = {
"timestamp": email_log.created_at.timestamp,
"action": email_log.get_action(),
"contact": {
"email": contact.website_email,
"name": contact.name,
"reverse_alias": contact.website_send_to(),
},
}
return res
def get_alias_infos_with_pagination_v3(
user,
page_id=0,
query=None,
sort=None,
alias_filter=None,
mailbox_id=None,
directory_id=None,
page_limit=PAGE_LIMIT,
page_size=PAGE_LIMIT,
) -> [AliasInfo]:
q = construct_alias_query(user)
if query:
q = q.filter(
or_(
Alias.email.ilike(f"%{query}%"),
Alias.note.ilike(f"%{query}%"),
# can't use match() here as it uses to_tsquery that expected a tsquery input
# Alias.ts_vector.match(query),
Alias.ts_vector.op("@@")(func.plainto_tsquery("english", query)),
Alias.name.ilike(f"%{query}%"),
)
)
if mailbox_id:
q = q.join(
AliasMailbox, Alias.id == AliasMailbox.alias_id, isouter=True
).filter(
or_(Alias.mailbox_id == mailbox_id, AliasMailbox.mailbox_id == mailbox_id)
)
if directory_id:
q = q.filter(Alias.directory_id == directory_id)
if alias_filter == "enabled":
q = q.filter(Alias.enabled)
elif alias_filter == "disabled":
q = q.filter(Alias.enabled.is_(False))
elif alias_filter == "pinned":
q = q.filter(Alias.pinned)
elif alias_filter == "hibp":
q = q.filter(Alias.hibp_breaches.any())
if sort == "old2new":
q = q.order_by(Alias.created_at)
elif sort == "new2old":
q = q.order_by(Alias.created_at.desc())
elif sort == "a2z":
q = q.order_by(Alias.email)
elif sort == "z2a":
q = q.order_by(Alias.email.desc())
else:
# default sorting
latest_activity = case(
[
(Alias.created_at > EmailLog.created_at, Alias.created_at),
(Alias.created_at < EmailLog.created_at, EmailLog.created_at),
],
else_=Alias.created_at,
)
q = q.order_by(Alias.pinned.desc())
q = q.order_by(latest_activity.desc())
q = q.limit(page_limit).offset(page_id * page_size)
ret = []
for alias, contact, email_log, nb_reply, nb_blocked, nb_forward in list(q):
ret.append(
AliasInfo(
alias=alias,
mailbox=alias.mailbox,
mailboxes=alias.mailboxes,
nb_forward=nb_forward,
nb_blocked=nb_blocked,
nb_reply=nb_reply,
latest_email_log=email_log,
latest_contact=contact,
custom_domain=alias.custom_domain,
)
)
return ret
The provided code snippet includes necessary dependencies for implementing the `get_aliases_v2` function. Write a Python function `def get_aliases_v2()` to solve the following problem:
Get aliases Input: page_id: in query pinned: in query disabled: in query enabled: in query Output: - aliases: list of alias: - id - email - creation_date - creation_timestamp - nb_forward - nb_block - nb_reply - note - mailbox - mailboxes - support_pgp - disable_pgp - latest_activity: null if no activity. - timestamp - action: forward|reply|block|bounced - contact: - email - name - reverse_alias
Here is the function:
def get_aliases_v2():
"""
Get aliases
Input:
page_id: in query
pinned: in query
disabled: in query
enabled: in query
Output:
- aliases: list of alias:
- id
- email
- creation_date
- creation_timestamp
- nb_forward
- nb_block
- nb_reply
- note
- mailbox
- mailboxes
- support_pgp
- disable_pgp
- latest_activity: null if no activity.
- timestamp
- action: forward|reply|block|bounced
- contact:
- email
- name
- reverse_alias
"""
user = g.user
try:
page_id = int(request.args.get("page_id"))
except (ValueError, TypeError):
return jsonify(error="page_id must be provided in request query"), 400
pinned = "pinned" in request.args
disabled = "disabled" in request.args
enabled = "enabled" in request.args
if pinned:
alias_filter = "pinned"
elif disabled:
alias_filter = "disabled"
elif enabled:
alias_filter = "enabled"
else:
alias_filter = None
query = None
data = request.get_json(silent=True)
if data:
query = data.get("query")
alias_infos: [AliasInfo] = get_alias_infos_with_pagination_v3(
user, page_id=page_id, query=query, alias_filter=alias_filter
)
return (
jsonify(
aliases=[serialize_alias_info_v2(alias_info) for alias_info in alias_infos]
),
200,
) | Get aliases Input: page_id: in query pinned: in query disabled: in query enabled: in query Output: - aliases: list of alias: - id - email - creation_date - creation_timestamp - nb_forward - nb_block - nb_reply - note - mailbox - mailboxes - support_pgp - disable_pgp - latest_activity: null if no activity. - timestamp - action: forward|reply|block|bounced - contact: - email - name - reverse_alias |
180,587 | from deprecated import deprecated
from flask import g
from flask import jsonify
from flask import request
from app import alias_utils
from app.api.base import api_bp, require_api_auth
from app.api.serializer import (
AliasInfo,
serialize_alias_info,
serialize_contact,
get_alias_infos_with_pagination,
get_alias_contacts,
serialize_alias_info_v2,
get_alias_info_v2,
get_alias_infos_with_pagination_v3,
)
from app.dashboard.views.alias_contact_manager import create_contact
from app.dashboard.views.alias_log import get_alias_log
from app.db import Session
from app.errors import (
CannotCreateContactForReverseAlias,
ErrContactErrorUpgradeNeeded,
ErrContactAlreadyExists,
ErrAddressInvalid,
)
from app.extensions import limiter
from app.models import Alias, Contact, Mailbox, AliasMailbox
class Alias(Base, ModelMixin):
__tablename__ = "alias"
FLAG_PARTNER_CREATED = 1 << 0
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, index=True
)
email = sa.Column(sa.String(128), unique=True, nullable=False)
# the name to use when user replies/sends from alias
name = sa.Column(sa.String(128), nullable=True, default=None)
enabled = sa.Column(sa.Boolean(), default=True, nullable=False)
flags = sa.Column(
sa.BigInteger(), default=0, server_default="0", nullable=False, index=True
)
custom_domain_id = sa.Column(
sa.ForeignKey("custom_domain.id", ondelete="cascade"), nullable=True, index=True
)
custom_domain = orm.relationship("CustomDomain", foreign_keys=[custom_domain_id])
# To know whether an alias is created "on the fly", i.e. via the custom domain catch-all feature
automatic_creation = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# to know whether an alias belongs to a directory
directory_id = sa.Column(
sa.ForeignKey("directory.id", ondelete="cascade"), nullable=True, index=True
)
note = sa.Column(sa.Text, default=None, nullable=True)
# an alias can be owned by another mailbox
mailbox_id = sa.Column(
sa.ForeignKey("mailbox.id", ondelete="cascade"), nullable=False, index=True
)
# prefix _ to avoid this object being used accidentally.
# To have the list of all mailboxes, should use AliasInfo instead
_mailboxes = orm.relationship("Mailbox", secondary="alias_mailbox", lazy="joined")
# If the mailbox has PGP-enabled, user can choose disable the PGP on the alias
# this is useful when some senders already support PGP
disable_pgp = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# a way to bypass the bounce automatic disable mechanism
cannot_be_disabled = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# when a mailbox wants to send an email on behalf of the alias via the reverse-alias
# several checks are performed to avoid email spoofing
# this option allow disabling these checks
disable_email_spoofing_check = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# to know whether an alias is added using a batch import
batch_import_id = sa.Column(
sa.ForeignKey("batch_import.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
# set in case of alias transfer.
original_owner_id = sa.Column(
sa.ForeignKey(User.id, ondelete="SET NULL"), nullable=True
)
# alias is pinned on top
pinned = sa.Column(sa.Boolean, nullable=False, default=False, server_default="0")
# used to transfer an alias to another user
transfer_token = sa.Column(sa.String(64), default=None, unique=True, nullable=True)
transfer_token_expiration = sa.Column(
ArrowType, default=arrow.utcnow, nullable=True
)
# have I been pwned
hibp_last_check = sa.Column(ArrowType, default=None, index=True)
hibp_breaches = orm.relationship("Hibp", secondary="alias_hibp")
# to use Postgres full text search. Only applied on "note" column for now
# this is a generated Postgres column
ts_vector = sa.Column(
TSVector(), sa.Computed("to_tsvector('english', note)", persisted=True)
)
last_email_log_id = sa.Column(sa.Integer, default=None, nullable=True)
__table_args__ = (
Index("ix_video___ts_vector__", ts_vector, postgresql_using="gin"),
# index on note column using pg_trgm
Index(
"note_pg_trgm_index",
"note",
postgresql_ops={"note": "gin_trgm_ops"},
postgresql_using="gin",
),
)
user = orm.relationship(User, foreign_keys=[user_id])
mailbox = orm.relationship("Mailbox", lazy="joined")
def mailboxes(self):
ret = [self.mailbox]
for m in self._mailboxes:
if m.id is not self.mailbox.id:
ret.append(m)
ret = [mb for mb in ret if mb.verified]
ret = sorted(ret, key=lambda mb: mb.email)
return ret
def authorized_addresses(self) -> [str]:
"""return addresses that can send on behalf of this alias, i.e. can send emails to this alias's reverse-aliases
Including its mailboxes and their authorized addresses
"""
mailboxes = self.mailboxes
ret = [mb.email for mb in mailboxes]
for mailbox in mailboxes:
for aa in mailbox.authorized_addresses:
ret.append(aa.email)
return ret
def mailbox_support_pgp(self) -> bool:
"""return True of one of the mailboxes support PGP"""
for mb in self.mailboxes:
if mb.pgp_enabled():
return True
return False
def pgp_enabled(self) -> bool:
if self.mailbox_support_pgp() and not self.disable_pgp:
return True
return False
def get_custom_domain(alias_address) -> Optional["CustomDomain"]:
alias_domain = validate_email(
alias_address, check_deliverability=False, allow_smtputf8=False
).domain
# handle the case a SLDomain is also a CustomDomain
if SLDomain.get_by(domain=alias_domain) is None:
custom_domain = CustomDomain.get_by(domain=alias_domain)
if custom_domain:
return custom_domain
def create(cls, **kw):
commit = kw.pop("commit", False)
flush = kw.pop("flush", False)
new_alias = cls(**kw)
user = User.get(new_alias.user_id)
if user.is_premium():
limits = config.ALIAS_CREATE_RATE_LIMIT_PAID
else:
limits = config.ALIAS_CREATE_RATE_LIMIT_FREE
# limits is array of (hits,days)
for limit in limits:
key = f"alias_create_{limit[1]}d:{user.id}"
rate_limiter.check_bucket_limit(key, limit[0], limit[1])
email = kw["email"]
# make sure email is lowercase and doesn't have any whitespace
email = sanitize_email(email)
# make sure alias is not in global trash, i.e. DeletedAlias table
if DeletedAlias.get_by(email=email):
raise AliasInTrashError
if DomainDeletedAlias.get_by(email=email):
raise AliasInTrashError
# detect whether alias should belong to a custom domain
if "custom_domain_id" not in kw:
custom_domain = Alias.get_custom_domain(email)
if custom_domain:
new_alias.custom_domain_id = custom_domain.id
Session.add(new_alias)
DailyMetric.get_or_create_today_metric().nb_alias += 1
if commit:
Session.commit()
if flush:
Session.flush()
return new_alias
def create_new(cls, user, prefix, note=None, mailbox_id=None):
prefix = prefix.lower().strip().replace(" ", "")
if not prefix:
raise Exception("alias prefix cannot be empty")
# find the right suffix - avoid infinite loop by running this at max 1000 times
for _ in range(1000):
suffix = user.get_random_alias_suffix()
email = f"{prefix}.{suffix}@{config.FIRST_ALIAS_DOMAIN}"
if available_sl_email(email):
break
return Alias.create(
user_id=user.id,
email=email,
note=note,
mailbox_id=mailbox_id or user.default_mailbox_id,
)
def delete(cls, obj_id):
raise Exception("should use delete_alias(alias,user) instead")
def create_new_random(
cls,
user,
scheme: int = AliasGeneratorEnum.word.value,
in_hex: bool = False,
note: str = None,
):
"""create a new random alias"""
custom_domain = None
random_email = None
if user.default_alias_custom_domain_id:
custom_domain = CustomDomain.get(user.default_alias_custom_domain_id)
random_email = generate_random_alias_email(
scheme=scheme, in_hex=in_hex, alias_domain=custom_domain.domain
)
elif user.default_alias_public_domain_id:
sl_domain: SLDomain = SLDomain.get(user.default_alias_public_domain_id)
if sl_domain.premium_only and not user.is_premium():
LOG.w("%s not premium, cannot use %s", user, sl_domain)
else:
random_email = generate_random_alias_email(
scheme=scheme, in_hex=in_hex, alias_domain=sl_domain.domain
)
if not random_email:
random_email = generate_random_alias_email(scheme=scheme, in_hex=in_hex)
alias = Alias.create(
user_id=user.id,
email=random_email,
mailbox_id=user.default_mailbox_id,
note=note,
)
if custom_domain:
alias.custom_domain_id = custom_domain.id
return alias
def mailbox_email(self):
if self.mailbox_id:
return self.mailbox.email
else:
return self.user.email
def __repr__(self):
return f"<Alias {self.id} {self.email}>"
The provided code snippet includes necessary dependencies for implementing the `delete_alias` function. Write a Python function `def delete_alias(alias_id)` to solve the following problem:
Delete alias Input: alias_id: in url Output: 200 if deleted successfully
Here is the function:
def delete_alias(alias_id):
"""
Delete alias
Input:
alias_id: in url
Output:
200 if deleted successfully
"""
user = g.user
alias = Alias.get(alias_id)
if not alias or alias.user_id != user.id:
return jsonify(error="Forbidden"), 403
alias_utils.delete_alias(alias, user)
return jsonify(deleted=True), 200 | Delete alias Input: alias_id: in url Output: 200 if deleted successfully |
180,588 | from deprecated import deprecated
from flask import g
from flask import jsonify
from flask import request
from app import alias_utils
from app.api.base import api_bp, require_api_auth
from app.api.serializer import (
AliasInfo,
serialize_alias_info,
serialize_contact,
get_alias_infos_with_pagination,
get_alias_contacts,
serialize_alias_info_v2,
get_alias_info_v2,
get_alias_infos_with_pagination_v3,
)
from app.dashboard.views.alias_contact_manager import create_contact
from app.dashboard.views.alias_log import get_alias_log
from app.db import Session
from app.errors import (
CannotCreateContactForReverseAlias,
ErrContactErrorUpgradeNeeded,
ErrContactAlreadyExists,
ErrAddressInvalid,
)
from app.extensions import limiter
from app.models import Alias, Contact, Mailbox, AliasMailbox
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
class Alias(Base, ModelMixin):
__tablename__ = "alias"
FLAG_PARTNER_CREATED = 1 << 0
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, index=True
)
email = sa.Column(sa.String(128), unique=True, nullable=False)
# the name to use when user replies/sends from alias
name = sa.Column(sa.String(128), nullable=True, default=None)
enabled = sa.Column(sa.Boolean(), default=True, nullable=False)
flags = sa.Column(
sa.BigInteger(), default=0, server_default="0", nullable=False, index=True
)
custom_domain_id = sa.Column(
sa.ForeignKey("custom_domain.id", ondelete="cascade"), nullable=True, index=True
)
custom_domain = orm.relationship("CustomDomain", foreign_keys=[custom_domain_id])
# To know whether an alias is created "on the fly", i.e. via the custom domain catch-all feature
automatic_creation = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# to know whether an alias belongs to a directory
directory_id = sa.Column(
sa.ForeignKey("directory.id", ondelete="cascade"), nullable=True, index=True
)
note = sa.Column(sa.Text, default=None, nullable=True)
# an alias can be owned by another mailbox
mailbox_id = sa.Column(
sa.ForeignKey("mailbox.id", ondelete="cascade"), nullable=False, index=True
)
# prefix _ to avoid this object being used accidentally.
# To have the list of all mailboxes, should use AliasInfo instead
_mailboxes = orm.relationship("Mailbox", secondary="alias_mailbox", lazy="joined")
# If the mailbox has PGP-enabled, user can choose disable the PGP on the alias
# this is useful when some senders already support PGP
disable_pgp = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# a way to bypass the bounce automatic disable mechanism
cannot_be_disabled = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# when a mailbox wants to send an email on behalf of the alias via the reverse-alias
# several checks are performed to avoid email spoofing
# this option allow disabling these checks
disable_email_spoofing_check = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# to know whether an alias is added using a batch import
batch_import_id = sa.Column(
sa.ForeignKey("batch_import.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
# set in case of alias transfer.
original_owner_id = sa.Column(
sa.ForeignKey(User.id, ondelete="SET NULL"), nullable=True
)
# alias is pinned on top
pinned = sa.Column(sa.Boolean, nullable=False, default=False, server_default="0")
# used to transfer an alias to another user
transfer_token = sa.Column(sa.String(64), default=None, unique=True, nullable=True)
transfer_token_expiration = sa.Column(
ArrowType, default=arrow.utcnow, nullable=True
)
# have I been pwned
hibp_last_check = sa.Column(ArrowType, default=None, index=True)
hibp_breaches = orm.relationship("Hibp", secondary="alias_hibp")
# to use Postgres full text search. Only applied on "note" column for now
# this is a generated Postgres column
ts_vector = sa.Column(
TSVector(), sa.Computed("to_tsvector('english', note)", persisted=True)
)
last_email_log_id = sa.Column(sa.Integer, default=None, nullable=True)
__table_args__ = (
Index("ix_video___ts_vector__", ts_vector, postgresql_using="gin"),
# index on note column using pg_trgm
Index(
"note_pg_trgm_index",
"note",
postgresql_ops={"note": "gin_trgm_ops"},
postgresql_using="gin",
),
)
user = orm.relationship(User, foreign_keys=[user_id])
mailbox = orm.relationship("Mailbox", lazy="joined")
def mailboxes(self):
ret = [self.mailbox]
for m in self._mailboxes:
if m.id is not self.mailbox.id:
ret.append(m)
ret = [mb for mb in ret if mb.verified]
ret = sorted(ret, key=lambda mb: mb.email)
return ret
def authorized_addresses(self) -> [str]:
"""return addresses that can send on behalf of this alias, i.e. can send emails to this alias's reverse-aliases
Including its mailboxes and their authorized addresses
"""
mailboxes = self.mailboxes
ret = [mb.email for mb in mailboxes]
for mailbox in mailboxes:
for aa in mailbox.authorized_addresses:
ret.append(aa.email)
return ret
def mailbox_support_pgp(self) -> bool:
"""return True of one of the mailboxes support PGP"""
for mb in self.mailboxes:
if mb.pgp_enabled():
return True
return False
def pgp_enabled(self) -> bool:
if self.mailbox_support_pgp() and not self.disable_pgp:
return True
return False
def get_custom_domain(alias_address) -> Optional["CustomDomain"]:
alias_domain = validate_email(
alias_address, check_deliverability=False, allow_smtputf8=False
).domain
# handle the case a SLDomain is also a CustomDomain
if SLDomain.get_by(domain=alias_domain) is None:
custom_domain = CustomDomain.get_by(domain=alias_domain)
if custom_domain:
return custom_domain
def create(cls, **kw):
commit = kw.pop("commit", False)
flush = kw.pop("flush", False)
new_alias = cls(**kw)
user = User.get(new_alias.user_id)
if user.is_premium():
limits = config.ALIAS_CREATE_RATE_LIMIT_PAID
else:
limits = config.ALIAS_CREATE_RATE_LIMIT_FREE
# limits is array of (hits,days)
for limit in limits:
key = f"alias_create_{limit[1]}d:{user.id}"
rate_limiter.check_bucket_limit(key, limit[0], limit[1])
email = kw["email"]
# make sure email is lowercase and doesn't have any whitespace
email = sanitize_email(email)
# make sure alias is not in global trash, i.e. DeletedAlias table
if DeletedAlias.get_by(email=email):
raise AliasInTrashError
if DomainDeletedAlias.get_by(email=email):
raise AliasInTrashError
# detect whether alias should belong to a custom domain
if "custom_domain_id" not in kw:
custom_domain = Alias.get_custom_domain(email)
if custom_domain:
new_alias.custom_domain_id = custom_domain.id
Session.add(new_alias)
DailyMetric.get_or_create_today_metric().nb_alias += 1
if commit:
Session.commit()
if flush:
Session.flush()
return new_alias
def create_new(cls, user, prefix, note=None, mailbox_id=None):
prefix = prefix.lower().strip().replace(" ", "")
if not prefix:
raise Exception("alias prefix cannot be empty")
# find the right suffix - avoid infinite loop by running this at max 1000 times
for _ in range(1000):
suffix = user.get_random_alias_suffix()
email = f"{prefix}.{suffix}@{config.FIRST_ALIAS_DOMAIN}"
if available_sl_email(email):
break
return Alias.create(
user_id=user.id,
email=email,
note=note,
mailbox_id=mailbox_id or user.default_mailbox_id,
)
def delete(cls, obj_id):
raise Exception("should use delete_alias(alias,user) instead")
def create_new_random(
cls,
user,
scheme: int = AliasGeneratorEnum.word.value,
in_hex: bool = False,
note: str = None,
):
"""create a new random alias"""
custom_domain = None
random_email = None
if user.default_alias_custom_domain_id:
custom_domain = CustomDomain.get(user.default_alias_custom_domain_id)
random_email = generate_random_alias_email(
scheme=scheme, in_hex=in_hex, alias_domain=custom_domain.domain
)
elif user.default_alias_public_domain_id:
sl_domain: SLDomain = SLDomain.get(user.default_alias_public_domain_id)
if sl_domain.premium_only and not user.is_premium():
LOG.w("%s not premium, cannot use %s", user, sl_domain)
else:
random_email = generate_random_alias_email(
scheme=scheme, in_hex=in_hex, alias_domain=sl_domain.domain
)
if not random_email:
random_email = generate_random_alias_email(scheme=scheme, in_hex=in_hex)
alias = Alias.create(
user_id=user.id,
email=random_email,
mailbox_id=user.default_mailbox_id,
note=note,
)
if custom_domain:
alias.custom_domain_id = custom_domain.id
return alias
def mailbox_email(self):
if self.mailbox_id:
return self.mailbox.email
else:
return self.user.email
def __repr__(self):
return f"<Alias {self.id} {self.email}>"
The provided code snippet includes necessary dependencies for implementing the `toggle_alias` function. Write a Python function `def toggle_alias(alias_id)` to solve the following problem:
Enable/disable alias Input: alias_id: in url Output: 200 along with new status: - enabled
Here is the function:
def toggle_alias(alias_id):
"""
Enable/disable alias
Input:
alias_id: in url
Output:
200 along with new status:
- enabled
"""
user = g.user
alias: Alias = Alias.get(alias_id)
if not alias or alias.user_id != user.id:
return jsonify(error="Forbidden"), 403
alias.enabled = not alias.enabled
Session.commit()
return jsonify(enabled=alias.enabled), 200 | Enable/disable alias Input: alias_id: in url Output: 200 along with new status: - enabled |
180,589 | from deprecated import deprecated
from flask import g
from flask import jsonify
from flask import request
from app import alias_utils
from app.api.base import api_bp, require_api_auth
from app.api.serializer import (
AliasInfo,
serialize_alias_info,
serialize_contact,
get_alias_infos_with_pagination,
get_alias_contacts,
serialize_alias_info_v2,
get_alias_info_v2,
get_alias_infos_with_pagination_v3,
)
from app.dashboard.views.alias_contact_manager import create_contact
from app.dashboard.views.alias_log import get_alias_log
from app.db import Session
from app.errors import (
CannotCreateContactForReverseAlias,
ErrContactErrorUpgradeNeeded,
ErrContactAlreadyExists,
ErrAddressInvalid,
)
from app.extensions import limiter
from app.models import Alias, Contact, Mailbox, AliasMailbox
)
def get_alias_log(alias: Alias, page_id=0) -> [AliasLog]:
logs: [AliasLog] = []
q = (
Session.query(Contact, EmailLog)
.filter(Contact.id == EmailLog.contact_id)
.filter(Contact.alias_id == alias.id)
.order_by(EmailLog.id.desc())
.limit(PAGE_LIMIT)
.offset(page_id * PAGE_LIMIT)
)
for contact, email_log in q:
al = AliasLog(
website_email=contact.website_email,
reverse_alias=contact.website_send_to(),
alias=alias.email,
when=email_log.created_at,
is_reply=email_log.is_reply,
blocked=email_log.blocked,
bounced=email_log.bounced,
email_log=email_log,
contact=contact,
)
logs.append(al)
logs = sorted(logs, key=lambda log: log.when, reverse=True)
return logs
class Alias(Base, ModelMixin):
__tablename__ = "alias"
FLAG_PARTNER_CREATED = 1 << 0
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, index=True
)
email = sa.Column(sa.String(128), unique=True, nullable=False)
# the name to use when user replies/sends from alias
name = sa.Column(sa.String(128), nullable=True, default=None)
enabled = sa.Column(sa.Boolean(), default=True, nullable=False)
flags = sa.Column(
sa.BigInteger(), default=0, server_default="0", nullable=False, index=True
)
custom_domain_id = sa.Column(
sa.ForeignKey("custom_domain.id", ondelete="cascade"), nullable=True, index=True
)
custom_domain = orm.relationship("CustomDomain", foreign_keys=[custom_domain_id])
# To know whether an alias is created "on the fly", i.e. via the custom domain catch-all feature
automatic_creation = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# to know whether an alias belongs to a directory
directory_id = sa.Column(
sa.ForeignKey("directory.id", ondelete="cascade"), nullable=True, index=True
)
note = sa.Column(sa.Text, default=None, nullable=True)
# an alias can be owned by another mailbox
mailbox_id = sa.Column(
sa.ForeignKey("mailbox.id", ondelete="cascade"), nullable=False, index=True
)
# prefix _ to avoid this object being used accidentally.
# To have the list of all mailboxes, should use AliasInfo instead
_mailboxes = orm.relationship("Mailbox", secondary="alias_mailbox", lazy="joined")
# If the mailbox has PGP-enabled, user can choose disable the PGP on the alias
# this is useful when some senders already support PGP
disable_pgp = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# a way to bypass the bounce automatic disable mechanism
cannot_be_disabled = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# when a mailbox wants to send an email on behalf of the alias via the reverse-alias
# several checks are performed to avoid email spoofing
# this option allow disabling these checks
disable_email_spoofing_check = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# to know whether an alias is added using a batch import
batch_import_id = sa.Column(
sa.ForeignKey("batch_import.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
# set in case of alias transfer.
original_owner_id = sa.Column(
sa.ForeignKey(User.id, ondelete="SET NULL"), nullable=True
)
# alias is pinned on top
pinned = sa.Column(sa.Boolean, nullable=False, default=False, server_default="0")
# used to transfer an alias to another user
transfer_token = sa.Column(sa.String(64), default=None, unique=True, nullable=True)
transfer_token_expiration = sa.Column(
ArrowType, default=arrow.utcnow, nullable=True
)
# have I been pwned
hibp_last_check = sa.Column(ArrowType, default=None, index=True)
hibp_breaches = orm.relationship("Hibp", secondary="alias_hibp")
# to use Postgres full text search. Only applied on "note" column for now
# this is a generated Postgres column
ts_vector = sa.Column(
TSVector(), sa.Computed("to_tsvector('english', note)", persisted=True)
)
last_email_log_id = sa.Column(sa.Integer, default=None, nullable=True)
__table_args__ = (
Index("ix_video___ts_vector__", ts_vector, postgresql_using="gin"),
# index on note column using pg_trgm
Index(
"note_pg_trgm_index",
"note",
postgresql_ops={"note": "gin_trgm_ops"},
postgresql_using="gin",
),
)
user = orm.relationship(User, foreign_keys=[user_id])
mailbox = orm.relationship("Mailbox", lazy="joined")
def mailboxes(self):
ret = [self.mailbox]
for m in self._mailboxes:
if m.id is not self.mailbox.id:
ret.append(m)
ret = [mb for mb in ret if mb.verified]
ret = sorted(ret, key=lambda mb: mb.email)
return ret
def authorized_addresses(self) -> [str]:
"""return addresses that can send on behalf of this alias, i.e. can send emails to this alias's reverse-aliases
Including its mailboxes and their authorized addresses
"""
mailboxes = self.mailboxes
ret = [mb.email for mb in mailboxes]
for mailbox in mailboxes:
for aa in mailbox.authorized_addresses:
ret.append(aa.email)
return ret
def mailbox_support_pgp(self) -> bool:
"""return True of one of the mailboxes support PGP"""
for mb in self.mailboxes:
if mb.pgp_enabled():
return True
return False
def pgp_enabled(self) -> bool:
if self.mailbox_support_pgp() and not self.disable_pgp:
return True
return False
def get_custom_domain(alias_address) -> Optional["CustomDomain"]:
alias_domain = validate_email(
alias_address, check_deliverability=False, allow_smtputf8=False
).domain
# handle the case a SLDomain is also a CustomDomain
if SLDomain.get_by(domain=alias_domain) is None:
custom_domain = CustomDomain.get_by(domain=alias_domain)
if custom_domain:
return custom_domain
def create(cls, **kw):
commit = kw.pop("commit", False)
flush = kw.pop("flush", False)
new_alias = cls(**kw)
user = User.get(new_alias.user_id)
if user.is_premium():
limits = config.ALIAS_CREATE_RATE_LIMIT_PAID
else:
limits = config.ALIAS_CREATE_RATE_LIMIT_FREE
# limits is array of (hits,days)
for limit in limits:
key = f"alias_create_{limit[1]}d:{user.id}"
rate_limiter.check_bucket_limit(key, limit[0], limit[1])
email = kw["email"]
# make sure email is lowercase and doesn't have any whitespace
email = sanitize_email(email)
# make sure alias is not in global trash, i.e. DeletedAlias table
if DeletedAlias.get_by(email=email):
raise AliasInTrashError
if DomainDeletedAlias.get_by(email=email):
raise AliasInTrashError
# detect whether alias should belong to a custom domain
if "custom_domain_id" not in kw:
custom_domain = Alias.get_custom_domain(email)
if custom_domain:
new_alias.custom_domain_id = custom_domain.id
Session.add(new_alias)
DailyMetric.get_or_create_today_metric().nb_alias += 1
if commit:
Session.commit()
if flush:
Session.flush()
return new_alias
def create_new(cls, user, prefix, note=None, mailbox_id=None):
prefix = prefix.lower().strip().replace(" ", "")
if not prefix:
raise Exception("alias prefix cannot be empty")
# find the right suffix - avoid infinite loop by running this at max 1000 times
for _ in range(1000):
suffix = user.get_random_alias_suffix()
email = f"{prefix}.{suffix}@{config.FIRST_ALIAS_DOMAIN}"
if available_sl_email(email):
break
return Alias.create(
user_id=user.id,
email=email,
note=note,
mailbox_id=mailbox_id or user.default_mailbox_id,
)
def delete(cls, obj_id):
raise Exception("should use delete_alias(alias,user) instead")
def create_new_random(
cls,
user,
scheme: int = AliasGeneratorEnum.word.value,
in_hex: bool = False,
note: str = None,
):
"""create a new random alias"""
custom_domain = None
random_email = None
if user.default_alias_custom_domain_id:
custom_domain = CustomDomain.get(user.default_alias_custom_domain_id)
random_email = generate_random_alias_email(
scheme=scheme, in_hex=in_hex, alias_domain=custom_domain.domain
)
elif user.default_alias_public_domain_id:
sl_domain: SLDomain = SLDomain.get(user.default_alias_public_domain_id)
if sl_domain.premium_only and not user.is_premium():
LOG.w("%s not premium, cannot use %s", user, sl_domain)
else:
random_email = generate_random_alias_email(
scheme=scheme, in_hex=in_hex, alias_domain=sl_domain.domain
)
if not random_email:
random_email = generate_random_alias_email(scheme=scheme, in_hex=in_hex)
alias = Alias.create(
user_id=user.id,
email=random_email,
mailbox_id=user.default_mailbox_id,
note=note,
)
if custom_domain:
alias.custom_domain_id = custom_domain.id
return alias
def mailbox_email(self):
if self.mailbox_id:
return self.mailbox.email
else:
return self.user.email
def __repr__(self):
return f"<Alias {self.id} {self.email}>"
The provided code snippet includes necessary dependencies for implementing the `get_alias_activities` function. Write a Python function `def get_alias_activities(alias_id)` to solve the following problem:
Get aliases Input: page_id: in query Output: - activities: list of activity: - from - to - timestamp - action: forward|reply|block|bounced - reverse_alias
Here is the function:
def get_alias_activities(alias_id):
"""
Get aliases
Input:
page_id: in query
Output:
- activities: list of activity:
- from
- to
- timestamp
- action: forward|reply|block|bounced
- reverse_alias
"""
user = g.user
try:
page_id = int(request.args.get("page_id"))
except (ValueError, TypeError):
return jsonify(error="page_id must be provided in request query"), 400
alias: Alias = Alias.get(alias_id)
if not alias or alias.user_id != user.id:
return jsonify(error="Forbidden"), 403
alias_logs = get_alias_log(alias, page_id)
activities = []
for alias_log in alias_logs:
activity = {
"timestamp": alias_log.when.timestamp,
"reverse_alias": alias_log.reverse_alias,
"reverse_alias_address": alias_log.contact.reply_email,
}
if alias_log.is_reply:
activity["from"] = alias_log.alias
activity["to"] = alias_log.website_email
activity["action"] = "reply"
else:
activity["to"] = alias_log.alias
activity["from"] = alias_log.website_email
if alias_log.bounced:
activity["action"] = "bounced"
elif alias_log.blocked:
activity["action"] = "block"
else:
activity["action"] = "forward"
activities.append(activity)
return jsonify(activities=activities), 200 | Get aliases Input: page_id: in query Output: - activities: list of activity: - from - to - timestamp - action: forward|reply|block|bounced - reverse_alias |
180,590 | from deprecated import deprecated
from flask import g
from flask import jsonify
from flask import request
from app import alias_utils
from app.api.base import api_bp, require_api_auth
from app.api.serializer import (
AliasInfo,
serialize_alias_info,
serialize_contact,
get_alias_infos_with_pagination,
get_alias_contacts,
serialize_alias_info_v2,
get_alias_info_v2,
get_alias_infos_with_pagination_v3,
)
from app.dashboard.views.alias_contact_manager import create_contact
from app.dashboard.views.alias_log import get_alias_log
from app.db import Session
from app.errors import (
CannotCreateContactForReverseAlias,
ErrContactErrorUpgradeNeeded,
ErrContactAlreadyExists,
ErrAddressInvalid,
)
from app.extensions import limiter
from app.models import Alias, Contact, Mailbox, AliasMailbox
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
class Alias(Base, ModelMixin):
__tablename__ = "alias"
FLAG_PARTNER_CREATED = 1 << 0
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, index=True
)
email = sa.Column(sa.String(128), unique=True, nullable=False)
# the name to use when user replies/sends from alias
name = sa.Column(sa.String(128), nullable=True, default=None)
enabled = sa.Column(sa.Boolean(), default=True, nullable=False)
flags = sa.Column(
sa.BigInteger(), default=0, server_default="0", nullable=False, index=True
)
custom_domain_id = sa.Column(
sa.ForeignKey("custom_domain.id", ondelete="cascade"), nullable=True, index=True
)
custom_domain = orm.relationship("CustomDomain", foreign_keys=[custom_domain_id])
# To know whether an alias is created "on the fly", i.e. via the custom domain catch-all feature
automatic_creation = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# to know whether an alias belongs to a directory
directory_id = sa.Column(
sa.ForeignKey("directory.id", ondelete="cascade"), nullable=True, index=True
)
note = sa.Column(sa.Text, default=None, nullable=True)
# an alias can be owned by another mailbox
mailbox_id = sa.Column(
sa.ForeignKey("mailbox.id", ondelete="cascade"), nullable=False, index=True
)
# prefix _ to avoid this object being used accidentally.
# To have the list of all mailboxes, should use AliasInfo instead
_mailboxes = orm.relationship("Mailbox", secondary="alias_mailbox", lazy="joined")
# If the mailbox has PGP-enabled, user can choose disable the PGP on the alias
# this is useful when some senders already support PGP
disable_pgp = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# a way to bypass the bounce automatic disable mechanism
cannot_be_disabled = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# when a mailbox wants to send an email on behalf of the alias via the reverse-alias
# several checks are performed to avoid email spoofing
# this option allow disabling these checks
disable_email_spoofing_check = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# to know whether an alias is added using a batch import
batch_import_id = sa.Column(
sa.ForeignKey("batch_import.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
# set in case of alias transfer.
original_owner_id = sa.Column(
sa.ForeignKey(User.id, ondelete="SET NULL"), nullable=True
)
# alias is pinned on top
pinned = sa.Column(sa.Boolean, nullable=False, default=False, server_default="0")
# used to transfer an alias to another user
transfer_token = sa.Column(sa.String(64), default=None, unique=True, nullable=True)
transfer_token_expiration = sa.Column(
ArrowType, default=arrow.utcnow, nullable=True
)
# have I been pwned
hibp_last_check = sa.Column(ArrowType, default=None, index=True)
hibp_breaches = orm.relationship("Hibp", secondary="alias_hibp")
# to use Postgres full text search. Only applied on "note" column for now
# this is a generated Postgres column
ts_vector = sa.Column(
TSVector(), sa.Computed("to_tsvector('english', note)", persisted=True)
)
last_email_log_id = sa.Column(sa.Integer, default=None, nullable=True)
__table_args__ = (
Index("ix_video___ts_vector__", ts_vector, postgresql_using="gin"),
# index on note column using pg_trgm
Index(
"note_pg_trgm_index",
"note",
postgresql_ops={"note": "gin_trgm_ops"},
postgresql_using="gin",
),
)
user = orm.relationship(User, foreign_keys=[user_id])
mailbox = orm.relationship("Mailbox", lazy="joined")
def mailboxes(self):
ret = [self.mailbox]
for m in self._mailboxes:
if m.id is not self.mailbox.id:
ret.append(m)
ret = [mb for mb in ret if mb.verified]
ret = sorted(ret, key=lambda mb: mb.email)
return ret
def authorized_addresses(self) -> [str]:
"""return addresses that can send on behalf of this alias, i.e. can send emails to this alias's reverse-aliases
Including its mailboxes and their authorized addresses
"""
mailboxes = self.mailboxes
ret = [mb.email for mb in mailboxes]
for mailbox in mailboxes:
for aa in mailbox.authorized_addresses:
ret.append(aa.email)
return ret
def mailbox_support_pgp(self) -> bool:
"""return True of one of the mailboxes support PGP"""
for mb in self.mailboxes:
if mb.pgp_enabled():
return True
return False
def pgp_enabled(self) -> bool:
if self.mailbox_support_pgp() and not self.disable_pgp:
return True
return False
def get_custom_domain(alias_address) -> Optional["CustomDomain"]:
alias_domain = validate_email(
alias_address, check_deliverability=False, allow_smtputf8=False
).domain
# handle the case a SLDomain is also a CustomDomain
if SLDomain.get_by(domain=alias_domain) is None:
custom_domain = CustomDomain.get_by(domain=alias_domain)
if custom_domain:
return custom_domain
def create(cls, **kw):
commit = kw.pop("commit", False)
flush = kw.pop("flush", False)
new_alias = cls(**kw)
user = User.get(new_alias.user_id)
if user.is_premium():
limits = config.ALIAS_CREATE_RATE_LIMIT_PAID
else:
limits = config.ALIAS_CREATE_RATE_LIMIT_FREE
# limits is array of (hits,days)
for limit in limits:
key = f"alias_create_{limit[1]}d:{user.id}"
rate_limiter.check_bucket_limit(key, limit[0], limit[1])
email = kw["email"]
# make sure email is lowercase and doesn't have any whitespace
email = sanitize_email(email)
# make sure alias is not in global trash, i.e. DeletedAlias table
if DeletedAlias.get_by(email=email):
raise AliasInTrashError
if DomainDeletedAlias.get_by(email=email):
raise AliasInTrashError
# detect whether alias should belong to a custom domain
if "custom_domain_id" not in kw:
custom_domain = Alias.get_custom_domain(email)
if custom_domain:
new_alias.custom_domain_id = custom_domain.id
Session.add(new_alias)
DailyMetric.get_or_create_today_metric().nb_alias += 1
if commit:
Session.commit()
if flush:
Session.flush()
return new_alias
def create_new(cls, user, prefix, note=None, mailbox_id=None):
prefix = prefix.lower().strip().replace(" ", "")
if not prefix:
raise Exception("alias prefix cannot be empty")
# find the right suffix - avoid infinite loop by running this at max 1000 times
for _ in range(1000):
suffix = user.get_random_alias_suffix()
email = f"{prefix}.{suffix}@{config.FIRST_ALIAS_DOMAIN}"
if available_sl_email(email):
break
return Alias.create(
user_id=user.id,
email=email,
note=note,
mailbox_id=mailbox_id or user.default_mailbox_id,
)
def delete(cls, obj_id):
raise Exception("should use delete_alias(alias,user) instead")
def create_new_random(
cls,
user,
scheme: int = AliasGeneratorEnum.word.value,
in_hex: bool = False,
note: str = None,
):
"""create a new random alias"""
custom_domain = None
random_email = None
if user.default_alias_custom_domain_id:
custom_domain = CustomDomain.get(user.default_alias_custom_domain_id)
random_email = generate_random_alias_email(
scheme=scheme, in_hex=in_hex, alias_domain=custom_domain.domain
)
elif user.default_alias_public_domain_id:
sl_domain: SLDomain = SLDomain.get(user.default_alias_public_domain_id)
if sl_domain.premium_only and not user.is_premium():
LOG.w("%s not premium, cannot use %s", user, sl_domain)
else:
random_email = generate_random_alias_email(
scheme=scheme, in_hex=in_hex, alias_domain=sl_domain.domain
)
if not random_email:
random_email = generate_random_alias_email(scheme=scheme, in_hex=in_hex)
alias = Alias.create(
user_id=user.id,
email=random_email,
mailbox_id=user.default_mailbox_id,
note=note,
)
if custom_domain:
alias.custom_domain_id = custom_domain.id
return alias
def mailbox_email(self):
if self.mailbox_id:
return self.mailbox.email
else:
return self.user.email
def __repr__(self):
return f"<Alias {self.id} {self.email}>"
class Mailbox(Base, ModelMixin):
__tablename__ = "mailbox"
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, index=True
)
email = sa.Column(sa.String(256), nullable=False, index=True)
verified = sa.Column(sa.Boolean, default=False, nullable=False)
force_spf = sa.Column(sa.Boolean, default=True, server_default="1", nullable=False)
# used when user wants to update mailbox email
new_email = sa.Column(sa.String(256), unique=True)
pgp_public_key = sa.Column(sa.Text, nullable=True)
pgp_finger_print = sa.Column(sa.String(512), nullable=True)
disable_pgp = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# incremented when a check is failed on the mailbox
# alert when the number exceeds a threshold
# used in sanity_check()
nb_failed_checks = sa.Column(
sa.Integer, default=0, server_default="0", nullable=False
)
# a mailbox can be disabled if it can't be reached
disabled = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0")
generic_subject = sa.Column(sa.String(78), nullable=True)
__table_args__ = (sa.UniqueConstraint("user_id", "email", name="uq_mailbox_user"),)
user = orm.relationship(User, foreign_keys=[user_id])
def pgp_enabled(self) -> bool:
if self.pgp_finger_print and not self.disable_pgp:
return True
return False
def nb_alias(self):
return (
AliasMailbox.filter_by(mailbox_id=self.id).count()
+ Alias.filter_by(mailbox_id=self.id).count()
)
def is_proton(self) -> bool:
if (
self.email.endswith("@proton.me")
or self.email.endswith("@protonmail.com")
or self.email.endswith("@protonmail.ch")
or self.email.endswith("@proton.ch")
or self.email.endswith("@pm.me")
):
return True
from app.email_utils import get_email_local_part
mx_domains: [(int, str)] = get_mx_domains(get_email_local_part(self.email))
# Proton is the first domain
if mx_domains and mx_domains[0][1] in (
"mail.protonmail.ch.",
"mailsec.protonmail.ch.",
):
return True
return False
def delete(cls, obj_id):
mailbox: Mailbox = cls.get(obj_id)
user = mailbox.user
# Put all aliases belonging to this mailbox to global or domain trash
for alias in Alias.filter_by(mailbox_id=obj_id):
# special handling for alias that has several mailboxes and has mailbox_id=obj_id
if len(alias.mailboxes) > 1:
# use the first mailbox found in alias._mailboxes
first_mb = alias._mailboxes[0]
alias.mailbox_id = first_mb.id
alias._mailboxes.remove(first_mb)
else:
from app import alias_utils
# only put aliases that have mailbox as a single mailbox into trash
alias_utils.delete_alias(alias, user)
Session.commit()
cls.filter(cls.id == obj_id).delete()
Session.commit()
def aliases(self) -> [Alias]:
ret = Alias.filter_by(mailbox_id=self.id).all()
for am in AliasMailbox.filter_by(mailbox_id=self.id):
ret.append(am.alias)
return ret
def create(cls, **kw):
if "email" in kw:
kw["email"] = sanitize_email(kw["email"])
return super().create(**kw)
def __repr__(self):
return f"<Mailbox {self.id} {self.email}>"
class AliasMailbox(Base, ModelMixin):
__tablename__ = "alias_mailbox"
__table_args__ = (
sa.UniqueConstraint("alias_id", "mailbox_id", name="uq_alias_mailbox"),
)
alias_id = sa.Column(
sa.ForeignKey(Alias.id, ondelete="cascade"), nullable=False, index=True
)
mailbox_id = sa.Column(
sa.ForeignKey(Mailbox.id, ondelete="cascade"), nullable=False, index=True
)
alias = orm.relationship(Alias)
The provided code snippet includes necessary dependencies for implementing the `update_alias` function. Write a Python function `def update_alias(alias_id)` to solve the following problem:
Update alias note Input: alias_id: in url note (optional): in body name (optional): in body mailbox_id (optional): in body disable_pgp (optional): in body Output: 200
Here is the function:
def update_alias(alias_id):
"""
Update alias note
Input:
alias_id: in url
note (optional): in body
name (optional): in body
mailbox_id (optional): in body
disable_pgp (optional): in body
Output:
200
"""
data = request.get_json()
if not data:
return jsonify(error="request body cannot be empty"), 400
user = g.user
alias: Alias = Alias.get(alias_id)
if not alias or alias.user_id != user.id:
return jsonify(error="Forbidden"), 403
changed = False
if "note" in data:
new_note = data.get("note")
alias.note = new_note
changed = True
if "mailbox_id" in data:
mailbox_id = int(data.get("mailbox_id"))
mailbox = Mailbox.get(mailbox_id)
if not mailbox or mailbox.user_id != user.id or not mailbox.verified:
return jsonify(error="Forbidden"), 400
alias.mailbox_id = mailbox_id
changed = True
if "mailbox_ids" in data:
mailbox_ids = [int(m_id) for m_id in data.get("mailbox_ids")]
mailboxes: [Mailbox] = []
# check if all mailboxes belong to user
for mailbox_id in mailbox_ids:
mailbox = Mailbox.get(mailbox_id)
if not mailbox or mailbox.user_id != user.id or not mailbox.verified:
return jsonify(error="Forbidden"), 400
mailboxes.append(mailbox)
if not mailboxes:
return jsonify(error="Must choose at least one mailbox"), 400
# <<< update alias mailboxes >>>
# first remove all existing alias-mailboxes links
AliasMailbox.filter_by(alias_id=alias.id).delete()
Session.flush()
# then add all new mailboxes
for i, mailbox in enumerate(mailboxes):
if i == 0:
alias.mailbox_id = mailboxes[0].id
else:
AliasMailbox.create(alias_id=alias.id, mailbox_id=mailbox.id)
# <<< END update alias mailboxes >>>
changed = True
if "name" in data:
# to make sure alias name doesn't contain linebreak
new_name = data.get("name")
if new_name and len(new_name) > 128:
return jsonify(error="Name can't be longer than 128 characters"), 400
if new_name:
new_name = new_name.replace("\n", "")
alias.name = new_name
changed = True
if "disable_pgp" in data:
alias.disable_pgp = data.get("disable_pgp")
changed = True
if "pinned" in data:
alias.pinned = data.get("pinned")
changed = True
if changed:
Session.commit()
return jsonify(ok=True), 200 | Update alias note Input: alias_id: in url note (optional): in body name (optional): in body mailbox_id (optional): in body disable_pgp (optional): in body Output: 200 |
180,591 | from deprecated import deprecated
from flask import g
from flask import jsonify
from flask import request
from app import alias_utils
from app.api.base import api_bp, require_api_auth
from app.api.serializer import (
AliasInfo,
serialize_alias_info,
serialize_contact,
get_alias_infos_with_pagination,
get_alias_contacts,
serialize_alias_info_v2,
get_alias_info_v2,
get_alias_infos_with_pagination_v3,
)
from app.dashboard.views.alias_contact_manager import create_contact
from app.dashboard.views.alias_log import get_alias_log
from app.db import Session
from app.errors import (
CannotCreateContactForReverseAlias,
ErrContactErrorUpgradeNeeded,
ErrContactAlreadyExists,
ErrAddressInvalid,
)
from app.extensions import limiter
from app.models import Alias, Contact, Mailbox, AliasMailbox
def serialize_alias_info_v2(alias_info: AliasInfo) -> dict:
res = {
# Alias field
"id": alias_info.alias.id,
"email": alias_info.alias.email,
"creation_date": alias_info.alias.created_at.format(),
"creation_timestamp": alias_info.alias.created_at.timestamp,
"enabled": alias_info.alias.enabled,
"note": alias_info.alias.note,
"name": alias_info.alias.name,
# activity
"nb_forward": alias_info.nb_forward,
"nb_block": alias_info.nb_blocked,
"nb_reply": alias_info.nb_reply,
# mailbox
"mailbox": {"id": alias_info.mailbox.id, "email": alias_info.mailbox.email},
"mailboxes": [
{"id": mailbox.id, "email": mailbox.email}
for mailbox in alias_info.mailboxes
],
"support_pgp": alias_info.alias.mailbox_support_pgp(),
"disable_pgp": alias_info.alias.disable_pgp,
"latest_activity": None,
"pinned": alias_info.alias.pinned,
}
if alias_info.latest_email_log:
email_log = alias_info.latest_email_log
contact = alias_info.latest_contact
# latest activity
res["latest_activity"] = {
"timestamp": email_log.created_at.timestamp,
"action": email_log.get_action(),
"contact": {
"email": contact.website_email,
"name": contact.name,
"reverse_alias": contact.website_send_to(),
},
}
return res
def get_alias_info_v2(alias: Alias, mailbox=None) -> AliasInfo:
if not mailbox:
mailbox = alias.mailbox
q = (
Session.query(Contact, EmailLog)
.filter(Contact.alias_id == alias.id)
.filter(EmailLog.contact_id == Contact.id)
)
latest_activity: Arrow = alias.created_at
latest_email_log = None
latest_contact = None
alias_info = AliasInfo(
alias=alias,
nb_blocked=0,
nb_forward=0,
nb_reply=0,
mailbox=mailbox,
mailboxes=[mailbox],
)
for m in alias._mailboxes:
alias_info.mailboxes.append(m)
# remove duplicates
# can happen that alias.mailbox_id also appears in AliasMailbox table
alias_info.mailboxes = list(set(alias_info.mailboxes))
for contact, email_log in q:
if email_log.is_reply:
alias_info.nb_reply += 1
elif email_log.blocked:
alias_info.nb_blocked += 1
else:
alias_info.nb_forward += 1
if email_log.created_at > latest_activity:
latest_activity = email_log.created_at
latest_email_log = email_log
latest_contact = contact
alias_info.latest_contact = latest_contact
alias_info.latest_email_log = latest_email_log
return alias_info
class Alias(Base, ModelMixin):
__tablename__ = "alias"
FLAG_PARTNER_CREATED = 1 << 0
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, index=True
)
email = sa.Column(sa.String(128), unique=True, nullable=False)
# the name to use when user replies/sends from alias
name = sa.Column(sa.String(128), nullable=True, default=None)
enabled = sa.Column(sa.Boolean(), default=True, nullable=False)
flags = sa.Column(
sa.BigInteger(), default=0, server_default="0", nullable=False, index=True
)
custom_domain_id = sa.Column(
sa.ForeignKey("custom_domain.id", ondelete="cascade"), nullable=True, index=True
)
custom_domain = orm.relationship("CustomDomain", foreign_keys=[custom_domain_id])
# To know whether an alias is created "on the fly", i.e. via the custom domain catch-all feature
automatic_creation = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# to know whether an alias belongs to a directory
directory_id = sa.Column(
sa.ForeignKey("directory.id", ondelete="cascade"), nullable=True, index=True
)
note = sa.Column(sa.Text, default=None, nullable=True)
# an alias can be owned by another mailbox
mailbox_id = sa.Column(
sa.ForeignKey("mailbox.id", ondelete="cascade"), nullable=False, index=True
)
# prefix _ to avoid this object being used accidentally.
# To have the list of all mailboxes, should use AliasInfo instead
_mailboxes = orm.relationship("Mailbox", secondary="alias_mailbox", lazy="joined")
# If the mailbox has PGP-enabled, user can choose disable the PGP on the alias
# this is useful when some senders already support PGP
disable_pgp = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# a way to bypass the bounce automatic disable mechanism
cannot_be_disabled = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# when a mailbox wants to send an email on behalf of the alias via the reverse-alias
# several checks are performed to avoid email spoofing
# this option allow disabling these checks
disable_email_spoofing_check = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# to know whether an alias is added using a batch import
batch_import_id = sa.Column(
sa.ForeignKey("batch_import.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
# set in case of alias transfer.
original_owner_id = sa.Column(
sa.ForeignKey(User.id, ondelete="SET NULL"), nullable=True
)
# alias is pinned on top
pinned = sa.Column(sa.Boolean, nullable=False, default=False, server_default="0")
# used to transfer an alias to another user
transfer_token = sa.Column(sa.String(64), default=None, unique=True, nullable=True)
transfer_token_expiration = sa.Column(
ArrowType, default=arrow.utcnow, nullable=True
)
# have I been pwned
hibp_last_check = sa.Column(ArrowType, default=None, index=True)
hibp_breaches = orm.relationship("Hibp", secondary="alias_hibp")
# to use Postgres full text search. Only applied on "note" column for now
# this is a generated Postgres column
ts_vector = sa.Column(
TSVector(), sa.Computed("to_tsvector('english', note)", persisted=True)
)
last_email_log_id = sa.Column(sa.Integer, default=None, nullable=True)
__table_args__ = (
Index("ix_video___ts_vector__", ts_vector, postgresql_using="gin"),
# index on note column using pg_trgm
Index(
"note_pg_trgm_index",
"note",
postgresql_ops={"note": "gin_trgm_ops"},
postgresql_using="gin",
),
)
user = orm.relationship(User, foreign_keys=[user_id])
mailbox = orm.relationship("Mailbox", lazy="joined")
def mailboxes(self):
ret = [self.mailbox]
for m in self._mailboxes:
if m.id is not self.mailbox.id:
ret.append(m)
ret = [mb for mb in ret if mb.verified]
ret = sorted(ret, key=lambda mb: mb.email)
return ret
def authorized_addresses(self) -> [str]:
"""return addresses that can send on behalf of this alias, i.e. can send emails to this alias's reverse-aliases
Including its mailboxes and their authorized addresses
"""
mailboxes = self.mailboxes
ret = [mb.email for mb in mailboxes]
for mailbox in mailboxes:
for aa in mailbox.authorized_addresses:
ret.append(aa.email)
return ret
def mailbox_support_pgp(self) -> bool:
"""return True of one of the mailboxes support PGP"""
for mb in self.mailboxes:
if mb.pgp_enabled():
return True
return False
def pgp_enabled(self) -> bool:
if self.mailbox_support_pgp() and not self.disable_pgp:
return True
return False
def get_custom_domain(alias_address) -> Optional["CustomDomain"]:
alias_domain = validate_email(
alias_address, check_deliverability=False, allow_smtputf8=False
).domain
# handle the case a SLDomain is also a CustomDomain
if SLDomain.get_by(domain=alias_domain) is None:
custom_domain = CustomDomain.get_by(domain=alias_domain)
if custom_domain:
return custom_domain
def create(cls, **kw):
commit = kw.pop("commit", False)
flush = kw.pop("flush", False)
new_alias = cls(**kw)
user = User.get(new_alias.user_id)
if user.is_premium():
limits = config.ALIAS_CREATE_RATE_LIMIT_PAID
else:
limits = config.ALIAS_CREATE_RATE_LIMIT_FREE
# limits is array of (hits,days)
for limit in limits:
key = f"alias_create_{limit[1]}d:{user.id}"
rate_limiter.check_bucket_limit(key, limit[0], limit[1])
email = kw["email"]
# make sure email is lowercase and doesn't have any whitespace
email = sanitize_email(email)
# make sure alias is not in global trash, i.e. DeletedAlias table
if DeletedAlias.get_by(email=email):
raise AliasInTrashError
if DomainDeletedAlias.get_by(email=email):
raise AliasInTrashError
# detect whether alias should belong to a custom domain
if "custom_domain_id" not in kw:
custom_domain = Alias.get_custom_domain(email)
if custom_domain:
new_alias.custom_domain_id = custom_domain.id
Session.add(new_alias)
DailyMetric.get_or_create_today_metric().nb_alias += 1
if commit:
Session.commit()
if flush:
Session.flush()
return new_alias
def create_new(cls, user, prefix, note=None, mailbox_id=None):
prefix = prefix.lower().strip().replace(" ", "")
if not prefix:
raise Exception("alias prefix cannot be empty")
# find the right suffix - avoid infinite loop by running this at max 1000 times
for _ in range(1000):
suffix = user.get_random_alias_suffix()
email = f"{prefix}.{suffix}@{config.FIRST_ALIAS_DOMAIN}"
if available_sl_email(email):
break
return Alias.create(
user_id=user.id,
email=email,
note=note,
mailbox_id=mailbox_id or user.default_mailbox_id,
)
def delete(cls, obj_id):
raise Exception("should use delete_alias(alias,user) instead")
def create_new_random(
cls,
user,
scheme: int = AliasGeneratorEnum.word.value,
in_hex: bool = False,
note: str = None,
):
"""create a new random alias"""
custom_domain = None
random_email = None
if user.default_alias_custom_domain_id:
custom_domain = CustomDomain.get(user.default_alias_custom_domain_id)
random_email = generate_random_alias_email(
scheme=scheme, in_hex=in_hex, alias_domain=custom_domain.domain
)
elif user.default_alias_public_domain_id:
sl_domain: SLDomain = SLDomain.get(user.default_alias_public_domain_id)
if sl_domain.premium_only and not user.is_premium():
LOG.w("%s not premium, cannot use %s", user, sl_domain)
else:
random_email = generate_random_alias_email(
scheme=scheme, in_hex=in_hex, alias_domain=sl_domain.domain
)
if not random_email:
random_email = generate_random_alias_email(scheme=scheme, in_hex=in_hex)
alias = Alias.create(
user_id=user.id,
email=random_email,
mailbox_id=user.default_mailbox_id,
note=note,
)
if custom_domain:
alias.custom_domain_id = custom_domain.id
return alias
def mailbox_email(self):
if self.mailbox_id:
return self.mailbox.email
else:
return self.user.email
def __repr__(self):
return f"<Alias {self.id} {self.email}>"
The provided code snippet includes necessary dependencies for implementing the `get_alias` function. Write a Python function `def get_alias(alias_id)` to solve the following problem:
Get alias Input: alias_id: in url Output: Alias info, same as in get_aliases
Here is the function:
def get_alias(alias_id):
"""
Get alias
Input:
alias_id: in url
Output:
Alias info, same as in get_aliases
"""
user = g.user
alias: Alias = Alias.get(alias_id)
if not alias:
return jsonify(error="Unknown error"), 400
if alias.user_id != user.id:
return jsonify(error="Forbidden"), 403
return jsonify(**serialize_alias_info_v2(get_alias_info_v2(alias))), 200 | Get alias Input: alias_id: in url Output: Alias info, same as in get_aliases |
180,592 | from deprecated import deprecated
from flask import g
from flask import jsonify
from flask import request
from app import alias_utils
from app.api.base import api_bp, require_api_auth
from app.api.serializer import (
AliasInfo,
serialize_alias_info,
serialize_contact,
get_alias_infos_with_pagination,
get_alias_contacts,
serialize_alias_info_v2,
get_alias_info_v2,
get_alias_infos_with_pagination_v3,
)
from app.dashboard.views.alias_contact_manager import create_contact
from app.dashboard.views.alias_log import get_alias_log
from app.db import Session
from app.errors import (
CannotCreateContactForReverseAlias,
ErrContactErrorUpgradeNeeded,
ErrContactAlreadyExists,
ErrAddressInvalid,
)
from app.extensions import limiter
from app.models import Alias, Contact, Mailbox, AliasMailbox
def get_alias_contacts(alias, page_id: int) -> [dict]:
q = (
Contact.filter_by(alias_id=alias.id)
.order_by(Contact.id.desc())
.limit(PAGE_LIMIT)
.offset(page_id * PAGE_LIMIT)
)
res = []
for fe in q.all():
res.append(serialize_contact(fe))
return res
class Alias(Base, ModelMixin):
__tablename__ = "alias"
FLAG_PARTNER_CREATED = 1 << 0
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, index=True
)
email = sa.Column(sa.String(128), unique=True, nullable=False)
# the name to use when user replies/sends from alias
name = sa.Column(sa.String(128), nullable=True, default=None)
enabled = sa.Column(sa.Boolean(), default=True, nullable=False)
flags = sa.Column(
sa.BigInteger(), default=0, server_default="0", nullable=False, index=True
)
custom_domain_id = sa.Column(
sa.ForeignKey("custom_domain.id", ondelete="cascade"), nullable=True, index=True
)
custom_domain = orm.relationship("CustomDomain", foreign_keys=[custom_domain_id])
# To know whether an alias is created "on the fly", i.e. via the custom domain catch-all feature
automatic_creation = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# to know whether an alias belongs to a directory
directory_id = sa.Column(
sa.ForeignKey("directory.id", ondelete="cascade"), nullable=True, index=True
)
note = sa.Column(sa.Text, default=None, nullable=True)
# an alias can be owned by another mailbox
mailbox_id = sa.Column(
sa.ForeignKey("mailbox.id", ondelete="cascade"), nullable=False, index=True
)
# prefix _ to avoid this object being used accidentally.
# To have the list of all mailboxes, should use AliasInfo instead
_mailboxes = orm.relationship("Mailbox", secondary="alias_mailbox", lazy="joined")
# If the mailbox has PGP-enabled, user can choose disable the PGP on the alias
# this is useful when some senders already support PGP
disable_pgp = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# a way to bypass the bounce automatic disable mechanism
cannot_be_disabled = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# when a mailbox wants to send an email on behalf of the alias via the reverse-alias
# several checks are performed to avoid email spoofing
# this option allow disabling these checks
disable_email_spoofing_check = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# to know whether an alias is added using a batch import
batch_import_id = sa.Column(
sa.ForeignKey("batch_import.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
# set in case of alias transfer.
original_owner_id = sa.Column(
sa.ForeignKey(User.id, ondelete="SET NULL"), nullable=True
)
# alias is pinned on top
pinned = sa.Column(sa.Boolean, nullable=False, default=False, server_default="0")
# used to transfer an alias to another user
transfer_token = sa.Column(sa.String(64), default=None, unique=True, nullable=True)
transfer_token_expiration = sa.Column(
ArrowType, default=arrow.utcnow, nullable=True
)
# have I been pwned
hibp_last_check = sa.Column(ArrowType, default=None, index=True)
hibp_breaches = orm.relationship("Hibp", secondary="alias_hibp")
# to use Postgres full text search. Only applied on "note" column for now
# this is a generated Postgres column
ts_vector = sa.Column(
TSVector(), sa.Computed("to_tsvector('english', note)", persisted=True)
)
last_email_log_id = sa.Column(sa.Integer, default=None, nullable=True)
__table_args__ = (
Index("ix_video___ts_vector__", ts_vector, postgresql_using="gin"),
# index on note column using pg_trgm
Index(
"note_pg_trgm_index",
"note",
postgresql_ops={"note": "gin_trgm_ops"},
postgresql_using="gin",
),
)
user = orm.relationship(User, foreign_keys=[user_id])
mailbox = orm.relationship("Mailbox", lazy="joined")
def mailboxes(self):
ret = [self.mailbox]
for m in self._mailboxes:
if m.id is not self.mailbox.id:
ret.append(m)
ret = [mb for mb in ret if mb.verified]
ret = sorted(ret, key=lambda mb: mb.email)
return ret
def authorized_addresses(self) -> [str]:
"""return addresses that can send on behalf of this alias, i.e. can send emails to this alias's reverse-aliases
Including its mailboxes and their authorized addresses
"""
mailboxes = self.mailboxes
ret = [mb.email for mb in mailboxes]
for mailbox in mailboxes:
for aa in mailbox.authorized_addresses:
ret.append(aa.email)
return ret
def mailbox_support_pgp(self) -> bool:
"""return True of one of the mailboxes support PGP"""
for mb in self.mailboxes:
if mb.pgp_enabled():
return True
return False
def pgp_enabled(self) -> bool:
if self.mailbox_support_pgp() and not self.disable_pgp:
return True
return False
def get_custom_domain(alias_address) -> Optional["CustomDomain"]:
alias_domain = validate_email(
alias_address, check_deliverability=False, allow_smtputf8=False
).domain
# handle the case a SLDomain is also a CustomDomain
if SLDomain.get_by(domain=alias_domain) is None:
custom_domain = CustomDomain.get_by(domain=alias_domain)
if custom_domain:
return custom_domain
def create(cls, **kw):
commit = kw.pop("commit", False)
flush = kw.pop("flush", False)
new_alias = cls(**kw)
user = User.get(new_alias.user_id)
if user.is_premium():
limits = config.ALIAS_CREATE_RATE_LIMIT_PAID
else:
limits = config.ALIAS_CREATE_RATE_LIMIT_FREE
# limits is array of (hits,days)
for limit in limits:
key = f"alias_create_{limit[1]}d:{user.id}"
rate_limiter.check_bucket_limit(key, limit[0], limit[1])
email = kw["email"]
# make sure email is lowercase and doesn't have any whitespace
email = sanitize_email(email)
# make sure alias is not in global trash, i.e. DeletedAlias table
if DeletedAlias.get_by(email=email):
raise AliasInTrashError
if DomainDeletedAlias.get_by(email=email):
raise AliasInTrashError
# detect whether alias should belong to a custom domain
if "custom_domain_id" not in kw:
custom_domain = Alias.get_custom_domain(email)
if custom_domain:
new_alias.custom_domain_id = custom_domain.id
Session.add(new_alias)
DailyMetric.get_or_create_today_metric().nb_alias += 1
if commit:
Session.commit()
if flush:
Session.flush()
return new_alias
def create_new(cls, user, prefix, note=None, mailbox_id=None):
prefix = prefix.lower().strip().replace(" ", "")
if not prefix:
raise Exception("alias prefix cannot be empty")
# find the right suffix - avoid infinite loop by running this at max 1000 times
for _ in range(1000):
suffix = user.get_random_alias_suffix()
email = f"{prefix}.{suffix}@{config.FIRST_ALIAS_DOMAIN}"
if available_sl_email(email):
break
return Alias.create(
user_id=user.id,
email=email,
note=note,
mailbox_id=mailbox_id or user.default_mailbox_id,
)
def delete(cls, obj_id):
raise Exception("should use delete_alias(alias,user) instead")
def create_new_random(
cls,
user,
scheme: int = AliasGeneratorEnum.word.value,
in_hex: bool = False,
note: str = None,
):
"""create a new random alias"""
custom_domain = None
random_email = None
if user.default_alias_custom_domain_id:
custom_domain = CustomDomain.get(user.default_alias_custom_domain_id)
random_email = generate_random_alias_email(
scheme=scheme, in_hex=in_hex, alias_domain=custom_domain.domain
)
elif user.default_alias_public_domain_id:
sl_domain: SLDomain = SLDomain.get(user.default_alias_public_domain_id)
if sl_domain.premium_only and not user.is_premium():
LOG.w("%s not premium, cannot use %s", user, sl_domain)
else:
random_email = generate_random_alias_email(
scheme=scheme, in_hex=in_hex, alias_domain=sl_domain.domain
)
if not random_email:
random_email = generate_random_alias_email(scheme=scheme, in_hex=in_hex)
alias = Alias.create(
user_id=user.id,
email=random_email,
mailbox_id=user.default_mailbox_id,
note=note,
)
if custom_domain:
alias.custom_domain_id = custom_domain.id
return alias
def mailbox_email(self):
if self.mailbox_id:
return self.mailbox.email
else:
return self.user.email
def __repr__(self):
return f"<Alias {self.id} {self.email}>"
The provided code snippet includes necessary dependencies for implementing the `get_alias_contacts_route` function. Write a Python function `def get_alias_contacts_route(alias_id)` to solve the following problem:
Get alias contacts Input: page_id: in query Output: - contacts: list of contacts: - creation_date - creation_timestamp - last_email_sent_date - last_email_sent_timestamp - contact - reverse_alias
Here is the function:
def get_alias_contacts_route(alias_id):
"""
Get alias contacts
Input:
page_id: in query
Output:
- contacts: list of contacts:
- creation_date
- creation_timestamp
- last_email_sent_date
- last_email_sent_timestamp
- contact
- reverse_alias
"""
user = g.user
try:
page_id = int(request.args.get("page_id"))
except (ValueError, TypeError):
return jsonify(error="page_id must be provided in request query"), 400
alias: Alias = Alias.get(alias_id)
if not alias:
return jsonify(error="No such alias"), 404
if alias.user_id != user.id:
return jsonify(error="Forbidden"), 403
contacts = get_alias_contacts(alias, page_id)
return jsonify(contacts=contacts), 200 | Get alias contacts Input: page_id: in query Output: - contacts: list of contacts: - creation_date - creation_timestamp - last_email_sent_date - last_email_sent_timestamp - contact - reverse_alias |
180,593 | from deprecated import deprecated
from flask import g
from flask import jsonify
from flask import request
from app import alias_utils
from app.api.base import api_bp, require_api_auth
from app.api.serializer import (
AliasInfo,
serialize_alias_info,
serialize_contact,
get_alias_infos_with_pagination,
get_alias_contacts,
serialize_alias_info_v2,
get_alias_info_v2,
get_alias_infos_with_pagination_v3,
)
from app.dashboard.views.alias_contact_manager import create_contact
from app.dashboard.views.alias_log import get_alias_log
from app.db import Session
from app.errors import (
CannotCreateContactForReverseAlias,
ErrContactErrorUpgradeNeeded,
ErrContactAlreadyExists,
ErrAddressInvalid,
)
from app.extensions import limiter
from app.models import Alias, Contact, Mailbox, AliasMailbox
def serialize_contact(contact: Contact, existed=False) -> dict:
res = {
"id": contact.id,
"creation_date": contact.created_at.format(),
"creation_timestamp": contact.created_at.timestamp,
"last_email_sent_date": None,
"last_email_sent_timestamp": None,
"contact": contact.website_email,
"reverse_alias": contact.website_send_to(),
"reverse_alias_address": contact.reply_email,
"existed": existed,
"block_forward": contact.block_forward,
}
email_log: EmailLog = contact.last_reply()
if email_log:
res["last_email_sent_date"] = email_log.created_at.format()
res["last_email_sent_timestamp"] = email_log.created_at.timestamp
return res
def create_contact(user: User, alias: Alias, contact_address: str) -> Contact:
"""
Create a contact for a user. Can be restricted for new free users by enabling DISABLE_CREATE_CONTACTS_FOR_FREE_USERS.
Can throw exceptions:
- ErrAddressInvalid
- ErrContactAlreadyExists
- ErrContactUpgradeNeeded - If DISABLE_CREATE_CONTACTS_FOR_FREE_USERS this exception will be raised for new free users
"""
if not contact_address:
raise ErrAddressInvalid("Empty address")
try:
contact_name, contact_email = parse_full_address(contact_address)
except ValueError:
raise ErrAddressInvalid(contact_address)
contact_email = sanitize_email(contact_email)
if not is_valid_email(contact_email):
raise ErrAddressInvalid(contact_email)
contact = Contact.get_by(alias_id=alias.id, website_email=contact_email)
if contact:
raise ErrContactAlreadyExists(contact)
if not user.can_create_contacts():
raise ErrContactErrorUpgradeNeeded()
contact = Contact.create(
user_id=alias.user_id,
alias_id=alias.id,
website_email=contact_email,
name=contact_name,
reply_email=generate_reply_email(contact_email, alias),
)
LOG.d(
"create reverse-alias for %s %s, reverse alias:%s",
contact_address,
alias,
contact.reply_email,
)
Session.commit()
return contact
class CannotCreateContactForReverseAlias(SLException):
"""raised when a contact is created that has website_email=reverse_alias of another contact"""
def error_for_user(self) -> str:
return "You can't create contact for a reverse alias"
class ErrContactErrorUpgradeNeeded(SLException):
"""raised when user cannot create a contact because the plan doesn't allow it"""
def error_for_user(self) -> str:
return "Please upgrade to premium to create reverse-alias"
class ErrAddressInvalid(SLException):
"""raised when an address is invalid"""
def __init__(self, address: str):
self.address = address
def error_for_user(self) -> str:
return f"{self.address} is not a valid email address"
class ErrContactAlreadyExists(SLException):
"""raised when a contact already exists"""
# TODO: type-hint this as a contact when models are almost dataclasses and don't import errors
def __init__(self, contact: "Contact"): # noqa: F821
self.contact = contact
def error_for_user(self) -> str:
return f"{self.contact.website_email} is already added"
class Alias(Base, ModelMixin):
__tablename__ = "alias"
FLAG_PARTNER_CREATED = 1 << 0
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, index=True
)
email = sa.Column(sa.String(128), unique=True, nullable=False)
# the name to use when user replies/sends from alias
name = sa.Column(sa.String(128), nullable=True, default=None)
enabled = sa.Column(sa.Boolean(), default=True, nullable=False)
flags = sa.Column(
sa.BigInteger(), default=0, server_default="0", nullable=False, index=True
)
custom_domain_id = sa.Column(
sa.ForeignKey("custom_domain.id", ondelete="cascade"), nullable=True, index=True
)
custom_domain = orm.relationship("CustomDomain", foreign_keys=[custom_domain_id])
# To know whether an alias is created "on the fly", i.e. via the custom domain catch-all feature
automatic_creation = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# to know whether an alias belongs to a directory
directory_id = sa.Column(
sa.ForeignKey("directory.id", ondelete="cascade"), nullable=True, index=True
)
note = sa.Column(sa.Text, default=None, nullable=True)
# an alias can be owned by another mailbox
mailbox_id = sa.Column(
sa.ForeignKey("mailbox.id", ondelete="cascade"), nullable=False, index=True
)
# prefix _ to avoid this object being used accidentally.
# To have the list of all mailboxes, should use AliasInfo instead
_mailboxes = orm.relationship("Mailbox", secondary="alias_mailbox", lazy="joined")
# If the mailbox has PGP-enabled, user can choose disable the PGP on the alias
# this is useful when some senders already support PGP
disable_pgp = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# a way to bypass the bounce automatic disable mechanism
cannot_be_disabled = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# when a mailbox wants to send an email on behalf of the alias via the reverse-alias
# several checks are performed to avoid email spoofing
# this option allow disabling these checks
disable_email_spoofing_check = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# to know whether an alias is added using a batch import
batch_import_id = sa.Column(
sa.ForeignKey("batch_import.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
# set in case of alias transfer.
original_owner_id = sa.Column(
sa.ForeignKey(User.id, ondelete="SET NULL"), nullable=True
)
# alias is pinned on top
pinned = sa.Column(sa.Boolean, nullable=False, default=False, server_default="0")
# used to transfer an alias to another user
transfer_token = sa.Column(sa.String(64), default=None, unique=True, nullable=True)
transfer_token_expiration = sa.Column(
ArrowType, default=arrow.utcnow, nullable=True
)
# have I been pwned
hibp_last_check = sa.Column(ArrowType, default=None, index=True)
hibp_breaches = orm.relationship("Hibp", secondary="alias_hibp")
# to use Postgres full text search. Only applied on "note" column for now
# this is a generated Postgres column
ts_vector = sa.Column(
TSVector(), sa.Computed("to_tsvector('english', note)", persisted=True)
)
last_email_log_id = sa.Column(sa.Integer, default=None, nullable=True)
__table_args__ = (
Index("ix_video___ts_vector__", ts_vector, postgresql_using="gin"),
# index on note column using pg_trgm
Index(
"note_pg_trgm_index",
"note",
postgresql_ops={"note": "gin_trgm_ops"},
postgresql_using="gin",
),
)
user = orm.relationship(User, foreign_keys=[user_id])
mailbox = orm.relationship("Mailbox", lazy="joined")
def mailboxes(self):
ret = [self.mailbox]
for m in self._mailboxes:
if m.id is not self.mailbox.id:
ret.append(m)
ret = [mb for mb in ret if mb.verified]
ret = sorted(ret, key=lambda mb: mb.email)
return ret
def authorized_addresses(self) -> [str]:
"""return addresses that can send on behalf of this alias, i.e. can send emails to this alias's reverse-aliases
Including its mailboxes and their authorized addresses
"""
mailboxes = self.mailboxes
ret = [mb.email for mb in mailboxes]
for mailbox in mailboxes:
for aa in mailbox.authorized_addresses:
ret.append(aa.email)
return ret
def mailbox_support_pgp(self) -> bool:
"""return True of one of the mailboxes support PGP"""
for mb in self.mailboxes:
if mb.pgp_enabled():
return True
return False
def pgp_enabled(self) -> bool:
if self.mailbox_support_pgp() and not self.disable_pgp:
return True
return False
def get_custom_domain(alias_address) -> Optional["CustomDomain"]:
alias_domain = validate_email(
alias_address, check_deliverability=False, allow_smtputf8=False
).domain
# handle the case a SLDomain is also a CustomDomain
if SLDomain.get_by(domain=alias_domain) is None:
custom_domain = CustomDomain.get_by(domain=alias_domain)
if custom_domain:
return custom_domain
def create(cls, **kw):
commit = kw.pop("commit", False)
flush = kw.pop("flush", False)
new_alias = cls(**kw)
user = User.get(new_alias.user_id)
if user.is_premium():
limits = config.ALIAS_CREATE_RATE_LIMIT_PAID
else:
limits = config.ALIAS_CREATE_RATE_LIMIT_FREE
# limits is array of (hits,days)
for limit in limits:
key = f"alias_create_{limit[1]}d:{user.id}"
rate_limiter.check_bucket_limit(key, limit[0], limit[1])
email = kw["email"]
# make sure email is lowercase and doesn't have any whitespace
email = sanitize_email(email)
# make sure alias is not in global trash, i.e. DeletedAlias table
if DeletedAlias.get_by(email=email):
raise AliasInTrashError
if DomainDeletedAlias.get_by(email=email):
raise AliasInTrashError
# detect whether alias should belong to a custom domain
if "custom_domain_id" not in kw:
custom_domain = Alias.get_custom_domain(email)
if custom_domain:
new_alias.custom_domain_id = custom_domain.id
Session.add(new_alias)
DailyMetric.get_or_create_today_metric().nb_alias += 1
if commit:
Session.commit()
if flush:
Session.flush()
return new_alias
def create_new(cls, user, prefix, note=None, mailbox_id=None):
prefix = prefix.lower().strip().replace(" ", "")
if not prefix:
raise Exception("alias prefix cannot be empty")
# find the right suffix - avoid infinite loop by running this at max 1000 times
for _ in range(1000):
suffix = user.get_random_alias_suffix()
email = f"{prefix}.{suffix}@{config.FIRST_ALIAS_DOMAIN}"
if available_sl_email(email):
break
return Alias.create(
user_id=user.id,
email=email,
note=note,
mailbox_id=mailbox_id or user.default_mailbox_id,
)
def delete(cls, obj_id):
raise Exception("should use delete_alias(alias,user) instead")
def create_new_random(
cls,
user,
scheme: int = AliasGeneratorEnum.word.value,
in_hex: bool = False,
note: str = None,
):
"""create a new random alias"""
custom_domain = None
random_email = None
if user.default_alias_custom_domain_id:
custom_domain = CustomDomain.get(user.default_alias_custom_domain_id)
random_email = generate_random_alias_email(
scheme=scheme, in_hex=in_hex, alias_domain=custom_domain.domain
)
elif user.default_alias_public_domain_id:
sl_domain: SLDomain = SLDomain.get(user.default_alias_public_domain_id)
if sl_domain.premium_only and not user.is_premium():
LOG.w("%s not premium, cannot use %s", user, sl_domain)
else:
random_email = generate_random_alias_email(
scheme=scheme, in_hex=in_hex, alias_domain=sl_domain.domain
)
if not random_email:
random_email = generate_random_alias_email(scheme=scheme, in_hex=in_hex)
alias = Alias.create(
user_id=user.id,
email=random_email,
mailbox_id=user.default_mailbox_id,
note=note,
)
if custom_domain:
alias.custom_domain_id = custom_domain.id
return alias
def mailbox_email(self):
if self.mailbox_id:
return self.mailbox.email
else:
return self.user.email
def __repr__(self):
return f"<Alias {self.id} {self.email}>"
The provided code snippet includes necessary dependencies for implementing the `create_contact_route` function. Write a Python function `def create_contact_route(alias_id)` to solve the following problem:
Create contact for an alias Input: alias_id: in url contact: in body Output: 201 if success 409 if contact already added
Here is the function:
def create_contact_route(alias_id):
"""
Create contact for an alias
Input:
alias_id: in url
contact: in body
Output:
201 if success
409 if contact already added
"""
data = request.get_json()
if not data:
return jsonify(error="request body cannot be empty"), 400
alias: Alias = Alias.get(alias_id)
if alias.user_id != g.user.id:
return jsonify(error="Forbidden"), 403
contact_address = data.get("contact")
try:
contact = create_contact(g.user, alias, contact_address)
except ErrContactErrorUpgradeNeeded as err:
return jsonify(error=err.error_for_user()), 403
except (ErrAddressInvalid, CannotCreateContactForReverseAlias) as err:
return jsonify(error=err.error_for_user()), 400
except ErrContactAlreadyExists as err:
return jsonify(**serialize_contact(err.contact, existed=True)), 200
return jsonify(**serialize_contact(contact)), 201 | Create contact for an alias Input: alias_id: in url contact: in body Output: 201 if success 409 if contact already added |
180,594 | from deprecated import deprecated
from flask import g
from flask import jsonify
from flask import request
from app import alias_utils
from app.api.base import api_bp, require_api_auth
from app.api.serializer import (
AliasInfo,
serialize_alias_info,
serialize_contact,
get_alias_infos_with_pagination,
get_alias_contacts,
serialize_alias_info_v2,
get_alias_info_v2,
get_alias_infos_with_pagination_v3,
)
from app.dashboard.views.alias_contact_manager import create_contact
from app.dashboard.views.alias_log import get_alias_log
from app.db import Session
from app.errors import (
CannotCreateContactForReverseAlias,
ErrContactErrorUpgradeNeeded,
ErrContactAlreadyExists,
ErrAddressInvalid,
)
from app.extensions import limiter
from app.models import Alias, Contact, Mailbox, AliasMailbox
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
class Contact(Base, ModelMixin):
"""
Store configuration of sender (website-email) and alias.
"""
MAX_NAME_LENGTH = 512
__tablename__ = "contact"
__table_args__ = (
sa.UniqueConstraint("alias_id", "website_email", name="uq_contact"),
)
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, index=True
)
alias_id = sa.Column(
sa.ForeignKey(Alias.id, ondelete="cascade"), nullable=False, index=True
)
name = sa.Column(
sa.String(512), nullable=True, default=None, server_default=text("NULL")
)
website_email = sa.Column(sa.String(512), nullable=False)
# the email from header, e.g. AB CD <ab@cd.com>
# nullable as this field is added after website_email
website_from = sa.Column(sa.String(1024), nullable=True)
# when user clicks on "reply", they will reply to this address.
# This address allows to hide user personal email
# this reply email is created every time a website sends an email to user
# it used to have the prefix "reply+" or "ra+"
reply_email = sa.Column(sa.String(512), nullable=False, index=True)
# whether a contact is created via CC
is_cc = sa.Column(sa.Boolean, nullable=False, default=False, server_default="0")
pgp_public_key = sa.Column(sa.Text, nullable=True)
pgp_finger_print = sa.Column(sa.String(512), nullable=True, index=True)
alias = orm.relationship(Alias, backref="contacts")
user = orm.relationship(User)
# the latest reply sent to this contact
latest_reply: Optional[Arrow] = None
# to investigate why the website_email is sometimes not correctly parsed
# the envelope mail_from
mail_from = sa.Column(sa.Text, nullable=True, default=None)
# a contact can have an empty email address, in this case it can't receive emails
invalid_email = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# emails sent from this contact will be blocked
block_forward = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# whether contact is created automatically during the forward phase
automatic_created = sa.Column(sa.Boolean, nullable=True, default=False)
def email(self):
return self.website_email
def create(cls, **kw):
commit = kw.pop("commit", False)
flush = kw.pop("flush", False)
new_contact = cls(**kw)
website_email = kw["website_email"]
# make sure email is lowercase and doesn't have any whitespace
website_email = sanitize_email(website_email)
# make sure contact.website_email isn't a reverse alias
if website_email != config.NOREPLY:
orig_contact = Contact.get_by(reply_email=website_email)
if orig_contact:
raise CannotCreateContactForReverseAlias(str(orig_contact))
Session.add(new_contact)
if commit:
Session.commit()
if flush:
Session.flush()
return new_contact
def website_send_to(self):
"""return the email address with name.
to use when user wants to send an email from the alias
Return
"First Last | email at example.com" <reverse-alias@SL>
"""
# Prefer using contact name if possible
user = self.user
name = self.name
email = self.website_email
if (
not user
or not SenderFormatEnum.has_value(user.sender_format)
or user.sender_format == SenderFormatEnum.AT.value
):
email = email.replace("@", " at ")
elif user.sender_format == SenderFormatEnum.A.value:
email = email.replace("@", "(a)")
# if no name, try to parse it from website_from
if not name and self.website_from:
try:
name = address.parse(self.website_from).display_name
except Exception:
# Skip if website_from is wrongly formatted
LOG.e(
"Cannot parse contact %s website_from %s", self, self.website_from
)
name = ""
# remove all double quote
if name:
name = name.replace('"', "")
if name:
name = name + " | " + email
else:
name = email
# cannot use formataddr here as this field is for email client, not for MTA
return f'"{name}" <{self.reply_email}>'
def new_addr(self):
"""
Replace original email by reply_email. Possible formats:
- First Last - first at example.com <reply_email> OR
- First Last - first(a)example.com <reply_email> OR
- First Last <reply_email>
- first at example.com <reply_email>
- reply_email
And return new address with RFC 2047 format
"""
user = self.user
sender_format = user.sender_format if user else SenderFormatEnum.AT.value
if sender_format == SenderFormatEnum.NO_NAME.value:
return self.reply_email
if sender_format == SenderFormatEnum.NAME_ONLY.value:
new_name = self.name
elif sender_format == SenderFormatEnum.AT_ONLY.value:
new_name = self.website_email.replace("@", " at ").strip()
elif sender_format == SenderFormatEnum.AT.value:
formatted_email = self.website_email.replace("@", " at ").strip()
new_name = (
(self.name + " - " + formatted_email)
if self.name and self.name != self.website_email.strip()
else formatted_email
)
else: # SenderFormatEnum.A.value
formatted_email = self.website_email.replace("@", "(a)").strip()
new_name = (
(self.name + " - " + formatted_email)
if self.name and self.name != self.website_email.strip()
else formatted_email
)
from app.email_utils import sl_formataddr
new_addr = sl_formataddr((new_name, self.reply_email)).strip()
return new_addr.strip()
def last_reply(self) -> "EmailLog":
"""return the most recent reply"""
return (
EmailLog.filter_by(contact_id=self.id, is_reply=True)
.order_by(desc(EmailLog.created_at))
.first()
)
def __repr__(self):
return f"<Contact {self.id} {self.website_email} {self.alias_id}>"
The provided code snippet includes necessary dependencies for implementing the `delete_contact` function. Write a Python function `def delete_contact(contact_id)` to solve the following problem:
Delete contact Input: contact_id: in url Output: 200
Here is the function:
def delete_contact(contact_id):
"""
Delete contact
Input:
contact_id: in url
Output:
200
"""
user = g.user
contact = Contact.get(contact_id)
if not contact or contact.alias.user_id != user.id:
return jsonify(error="Forbidden"), 403
Contact.delete(contact_id)
Session.commit()
return jsonify(deleted=True), 200 | Delete contact Input: contact_id: in url Output: 200 |
180,595 | from deprecated import deprecated
from flask import g
from flask import jsonify
from flask import request
from app import alias_utils
from app.api.base import api_bp, require_api_auth
from app.api.serializer import (
AliasInfo,
serialize_alias_info,
serialize_contact,
get_alias_infos_with_pagination,
get_alias_contacts,
serialize_alias_info_v2,
get_alias_info_v2,
get_alias_infos_with_pagination_v3,
)
from app.dashboard.views.alias_contact_manager import create_contact
from app.dashboard.views.alias_log import get_alias_log
from app.db import Session
from app.errors import (
CannotCreateContactForReverseAlias,
ErrContactErrorUpgradeNeeded,
ErrContactAlreadyExists,
ErrAddressInvalid,
)
from app.extensions import limiter
from app.models import Alias, Contact, Mailbox, AliasMailbox
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
class Contact(Base, ModelMixin):
"""
Store configuration of sender (website-email) and alias.
"""
MAX_NAME_LENGTH = 512
__tablename__ = "contact"
__table_args__ = (
sa.UniqueConstraint("alias_id", "website_email", name="uq_contact"),
)
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, index=True
)
alias_id = sa.Column(
sa.ForeignKey(Alias.id, ondelete="cascade"), nullable=False, index=True
)
name = sa.Column(
sa.String(512), nullable=True, default=None, server_default=text("NULL")
)
website_email = sa.Column(sa.String(512), nullable=False)
# the email from header, e.g. AB CD <ab@cd.com>
# nullable as this field is added after website_email
website_from = sa.Column(sa.String(1024), nullable=True)
# when user clicks on "reply", they will reply to this address.
# This address allows to hide user personal email
# this reply email is created every time a website sends an email to user
# it used to have the prefix "reply+" or "ra+"
reply_email = sa.Column(sa.String(512), nullable=False, index=True)
# whether a contact is created via CC
is_cc = sa.Column(sa.Boolean, nullable=False, default=False, server_default="0")
pgp_public_key = sa.Column(sa.Text, nullable=True)
pgp_finger_print = sa.Column(sa.String(512), nullable=True, index=True)
alias = orm.relationship(Alias, backref="contacts")
user = orm.relationship(User)
# the latest reply sent to this contact
latest_reply: Optional[Arrow] = None
# to investigate why the website_email is sometimes not correctly parsed
# the envelope mail_from
mail_from = sa.Column(sa.Text, nullable=True, default=None)
# a contact can have an empty email address, in this case it can't receive emails
invalid_email = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# emails sent from this contact will be blocked
block_forward = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# whether contact is created automatically during the forward phase
automatic_created = sa.Column(sa.Boolean, nullable=True, default=False)
def email(self):
return self.website_email
def create(cls, **kw):
commit = kw.pop("commit", False)
flush = kw.pop("flush", False)
new_contact = cls(**kw)
website_email = kw["website_email"]
# make sure email is lowercase and doesn't have any whitespace
website_email = sanitize_email(website_email)
# make sure contact.website_email isn't a reverse alias
if website_email != config.NOREPLY:
orig_contact = Contact.get_by(reply_email=website_email)
if orig_contact:
raise CannotCreateContactForReverseAlias(str(orig_contact))
Session.add(new_contact)
if commit:
Session.commit()
if flush:
Session.flush()
return new_contact
def website_send_to(self):
"""return the email address with name.
to use when user wants to send an email from the alias
Return
"First Last | email at example.com" <reverse-alias@SL>
"""
# Prefer using contact name if possible
user = self.user
name = self.name
email = self.website_email
if (
not user
or not SenderFormatEnum.has_value(user.sender_format)
or user.sender_format == SenderFormatEnum.AT.value
):
email = email.replace("@", " at ")
elif user.sender_format == SenderFormatEnum.A.value:
email = email.replace("@", "(a)")
# if no name, try to parse it from website_from
if not name and self.website_from:
try:
name = address.parse(self.website_from).display_name
except Exception:
# Skip if website_from is wrongly formatted
LOG.e(
"Cannot parse contact %s website_from %s", self, self.website_from
)
name = ""
# remove all double quote
if name:
name = name.replace('"', "")
if name:
name = name + " | " + email
else:
name = email
# cannot use formataddr here as this field is for email client, not for MTA
return f'"{name}" <{self.reply_email}>'
def new_addr(self):
"""
Replace original email by reply_email. Possible formats:
- First Last - first at example.com <reply_email> OR
- First Last - first(a)example.com <reply_email> OR
- First Last <reply_email>
- first at example.com <reply_email>
- reply_email
And return new address with RFC 2047 format
"""
user = self.user
sender_format = user.sender_format if user else SenderFormatEnum.AT.value
if sender_format == SenderFormatEnum.NO_NAME.value:
return self.reply_email
if sender_format == SenderFormatEnum.NAME_ONLY.value:
new_name = self.name
elif sender_format == SenderFormatEnum.AT_ONLY.value:
new_name = self.website_email.replace("@", " at ").strip()
elif sender_format == SenderFormatEnum.AT.value:
formatted_email = self.website_email.replace("@", " at ").strip()
new_name = (
(self.name + " - " + formatted_email)
if self.name and self.name != self.website_email.strip()
else formatted_email
)
else: # SenderFormatEnum.A.value
formatted_email = self.website_email.replace("@", "(a)").strip()
new_name = (
(self.name + " - " + formatted_email)
if self.name and self.name != self.website_email.strip()
else formatted_email
)
from app.email_utils import sl_formataddr
new_addr = sl_formataddr((new_name, self.reply_email)).strip()
return new_addr.strip()
def last_reply(self) -> "EmailLog":
"""return the most recent reply"""
return (
EmailLog.filter_by(contact_id=self.id, is_reply=True)
.order_by(desc(EmailLog.created_at))
.first()
)
def __repr__(self):
return f"<Contact {self.id} {self.website_email} {self.alias_id}>"
The provided code snippet includes necessary dependencies for implementing the `toggle_contact` function. Write a Python function `def toggle_contact(contact_id)` to solve the following problem:
Block/Unblock contact Input: contact_id: in url Output: 200
Here is the function:
def toggle_contact(contact_id):
"""
Block/Unblock contact
Input:
contact_id: in url
Output:
200
"""
user = g.user
contact = Contact.get(contact_id)
if not contact or contact.alias.user_id != user.id:
return jsonify(error="Forbidden"), 403
contact.block_forward = not contact.block_forward
Session.commit()
return jsonify(block_forward=contact.block_forward), 200 | Block/Unblock contact Input: contact_id: in url Output: 200 |
180,596 | import tldextract
from flask import jsonify, request, g
from sqlalchemy import desc
from app.alias_suffix import get_alias_suffixes
from app.api.base import api_bp, require_api_auth
from app.db import Session
from app.log import LOG
from app.models import AliasUsedOn, Alias, User
from app.utils import convert_to_id
def get_alias_suffixes(
user: User, alias_options: Optional[AliasOptions] = None
) -> [AliasSuffix]:
"""
Similar to as get_available_suffixes() but also return custom domain that doesn't have MX set up.
"""
user_custom_domains = user.verified_custom_domains()
alias_suffixes: [AliasSuffix] = []
# put custom domain first
# for each user domain, generate both the domain and a random suffix version
for custom_domain in user_custom_domains:
if custom_domain.random_prefix_generation:
suffix = (
f".{user.get_random_alias_suffix(custom_domain)}@{custom_domain.domain}"
)
alias_suffix = AliasSuffix(
is_custom=True,
suffix=suffix,
signed_suffix=signer.sign(suffix).decode(),
is_premium=False,
domain=custom_domain.domain,
mx_verified=custom_domain.verified,
)
if user.default_alias_custom_domain_id == custom_domain.id:
alias_suffixes.insert(0, alias_suffix)
else:
alias_suffixes.append(alias_suffix)
suffix = f"@{custom_domain.domain}"
alias_suffix = AliasSuffix(
is_custom=True,
suffix=suffix,
signed_suffix=signer.sign(suffix).decode(),
is_premium=False,
domain=custom_domain.domain,
mx_verified=custom_domain.verified,
)
# put the default domain to top
# only if random_prefix_generation isn't enabled
if (
user.default_alias_custom_domain_id == custom_domain.id
and not custom_domain.random_prefix_generation
):
alias_suffixes.insert(0, alias_suffix)
else:
alias_suffixes.append(alias_suffix)
# then SimpleLogin domain
sl_domains = user.get_sl_domains(alias_options=alias_options)
default_domain_found = False
for sl_domain in sl_domains:
prefix = (
"" if config.DISABLE_ALIAS_SUFFIX else f".{user.get_random_alias_suffix()}"
)
suffix = f"{prefix}@{sl_domain.domain}"
alias_suffix = AliasSuffix(
is_custom=False,
suffix=suffix,
signed_suffix=signer.sign(suffix).decode(),
is_premium=sl_domain.premium_only,
domain=sl_domain.domain,
mx_verified=True,
)
# No default or this is not the default
if (
user.default_alias_public_domain_id is None
or user.default_alias_public_domain_id != sl_domain.id
):
alias_suffixes.append(alias_suffix)
else:
default_domain_found = True
alias_suffixes.insert(0, alias_suffix)
if not default_domain_found:
domain_conditions = {"id": user.default_alias_public_domain_id, "hidden": False}
if not user.is_premium():
domain_conditions["premium_only"] = False
sl_domain = SLDomain.get_by(**domain_conditions)
if sl_domain:
prefix = (
""
if config.DISABLE_ALIAS_SUFFIX
else f".{user.get_random_alias_suffix()}"
)
suffix = f"{prefix}@{sl_domain.domain}"
alias_suffix = AliasSuffix(
is_custom=False,
suffix=suffix,
signed_suffix=signer.sign(suffix).decode(),
is_premium=sl_domain.premium_only,
domain=sl_domain.domain,
mx_verified=True,
)
alias_suffixes.insert(0, alias_suffix)
return alias_suffixes
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
LOG = _get_logger("SL")
class User(Base, ModelMixin, UserMixin, PasswordOracle):
__tablename__ = "users"
FLAG_FREE_DISABLE_CREATE_ALIAS = 1 << 0
FLAG_CREATED_FROM_PARTNER = 1 << 1
FLAG_FREE_OLD_ALIAS_LIMIT = 1 << 2
email = sa.Column(sa.String(256), unique=True, nullable=False)
name = sa.Column(sa.String(128), nullable=True)
is_admin = sa.Column(sa.Boolean, nullable=False, default=False)
alias_generator = sa.Column(
sa.Integer,
nullable=False,
default=AliasGeneratorEnum.word.value,
server_default=str(AliasGeneratorEnum.word.value),
)
notification = sa.Column(
sa.Boolean, default=True, nullable=False, server_default="1"
)
activated = sa.Column(sa.Boolean, default=False, nullable=False, index=True)
# an account can be disabled if having harmful behavior
disabled = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0")
profile_picture_id = sa.Column(sa.ForeignKey(File.id), nullable=True)
otp_secret = sa.Column(sa.String(16), nullable=True)
enable_otp = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
last_otp = sa.Column(sa.String(12), nullable=True, default=False)
# Fields for WebAuthn
fido_uuid = sa.Column(sa.String(), nullable=True, unique=True)
# the default domain that's used when user creates a new random alias
# default_alias_custom_domain_id XOR default_alias_public_domain_id
default_alias_custom_domain_id = sa.Column(
sa.ForeignKey("custom_domain.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
default_alias_public_domain_id = sa.Column(
sa.ForeignKey("public_domain.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
# some users could have lifetime premium
lifetime = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0")
paid_lifetime = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
lifetime_coupon_id = sa.Column(
sa.ForeignKey("lifetime_coupon.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
# user can use all premium features until this date
trial_end = sa.Column(
ArrowType, default=lambda: arrow.now().shift(days=7, hours=1), nullable=True
)
# the mailbox used when create random alias
# this field is nullable but in practice, it's always set
# it cannot be set to non-nullable though
# as this will create foreign key cycle between User and Mailbox
default_mailbox_id = sa.Column(
sa.ForeignKey("mailbox.id"), nullable=True, default=None
)
profile_picture = orm.relationship(File, foreign_keys=[profile_picture_id])
# Specify the format for sender address
# for the full list, see SenderFormatEnum
sender_format = sa.Column(
sa.Integer, default="0", nullable=False, server_default="0"
)
# to know whether user has explicitly chosen a sender format as opposed to those who use the default ones.
# users who haven't chosen a sender format and are using 1 or 3 format, their sender format will be set to 0
sender_format_updated_at = sa.Column(ArrowType, default=None)
replace_reverse_alias = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
referral_id = sa.Column(
sa.ForeignKey("referral.id", ondelete="SET NULL"),
nullable=True,
default=None,
index=True,
)
referral = orm.relationship("Referral", foreign_keys=[referral_id])
# whether intro has been shown to user
intro_shown = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
default_mailbox = orm.relationship("Mailbox", foreign_keys=[default_mailbox_id])
# user can set a more strict max_spam score to block spams more aggressively
max_spam_score = sa.Column(sa.Integer, nullable=True)
# newsletter is sent to this address
newsletter_alias_id = sa.Column(
sa.ForeignKey("alias.id", ondelete="SET NULL"),
nullable=True,
default=None,
index=True,
)
# whether to include the sender address in reverse-alias
include_sender_in_reverse_alias = sa.Column(
sa.Boolean, default=True, nullable=False, server_default="0"
)
# whether to use random string or random word as suffix
# Random word from dictionary file -> 0
# Completely random string -> 1
random_alias_suffix = sa.Column(
sa.Integer,
nullable=False,
default=AliasSuffixEnum.word.value,
server_default=str(AliasSuffixEnum.random_string.value),
)
# always expand the alias info, i.e. without needing to press "More"
expand_alias_info = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# ignore emails send from a mailbox to its alias. This can happen when replying all to a forwarded email
# can automatically re-includes the alias
ignore_loop_email = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# used for flask-login as an "alternative token"
# cf https://flask-login.readthedocs.io/en/latest/#alternative-tokens
alternative_id = sa.Column(sa.String(128), unique=True, nullable=True)
# by default, when an alias is automatically created, a note like "Created with ...." is created
# If this field is True, the note won't be created.
disable_automatic_alias_note = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# By default, the one-click unsubscribe disable the alias
# If set to true, it will block the sender instead
one_click_unsubscribe_block_sender = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# automatically include the website name when user creates an alias via the SimpleLogin icon in the email field
include_website_in_one_click_alias = sa.Column(
sa.Boolean,
# new user will have this option turned on automatically
default=True,
nullable=False,
# old user will have this option turned off
server_default="0",
)
_directory_quota = sa.Column(
"directory_quota", sa.Integer, default=50, nullable=False, server_default="50"
)
_subdomain_quota = sa.Column(
"subdomain_quota", sa.Integer, default=5, nullable=False, server_default="5"
)
# user can use import to import too many aliases
disable_import = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# user can use the phone feature
can_use_phone = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# in minutes
phone_quota = sa.Column(sa.Integer, nullable=True)
# Status code to return if is blocked
block_behaviour = sa.Column(
sa.Enum(BlockBehaviourEnum),
nullable=False,
server_default=BlockBehaviourEnum.return_2xx.name,
)
include_header_email_header = sa.Column(
sa.Boolean, default=True, nullable=False, server_default="1"
)
# bitwise flags. Allow for future expansion
flags = sa.Column(
sa.BigInteger,
default=FLAG_FREE_DISABLE_CREATE_ALIAS,
server_default="0",
nullable=False,
)
# Keep original unsub behaviour
unsub_behaviour = sa.Column(
IntEnumType(UnsubscribeBehaviourEnum),
default=UnsubscribeBehaviourEnum.PreserveOriginal,
server_default=str(UnsubscribeBehaviourEnum.DisableAlias.value),
nullable=False,
)
# Trigger hard deletion of the account at this time
delete_on = sa.Column(ArrowType, default=None)
__table_args__ = (
sa.Index(
"ix_users_activated_trial_end_lifetime", activated, trial_end, lifetime
),
sa.Index("ix_users_delete_on", delete_on),
)
def directory_quota(self):
return min(
self._directory_quota,
config.MAX_NB_DIRECTORY - Directory.filter_by(user_id=self.id).count(),
)
def subdomain_quota(self):
return min(
self._subdomain_quota,
config.MAX_NB_SUBDOMAIN
- CustomDomain.filter_by(user_id=self.id, is_sl_subdomain=True).count(),
)
def created_by_partner(self):
return User.FLAG_CREATED_FROM_PARTNER == (
self.flags & User.FLAG_CREATED_FROM_PARTNER
)
def subdomain_is_available():
return SLDomain.filter_by(can_use_subdomain=True).count() > 0
# implement flask-login "alternative token"
def get_id(self):
if self.alternative_id:
return self.alternative_id
else:
return str(self.id)
def create(cls, email, name="", password=None, from_partner=False, **kwargs):
email = sanitize_email(email)
user: User = super(User, cls).create(email=email, name=name[:100], **kwargs)
if password:
user.set_password(password)
Session.flush()
mb = Mailbox.create(user_id=user.id, email=user.email, verified=True)
Session.flush()
user.default_mailbox_id = mb.id
# generate an alternative_id if needed
if "alternative_id" not in kwargs:
user.alternative_id = str(uuid.uuid4())
# If the user is created from partner, do not notify
# nor give a trial
if from_partner:
user.flags = User.FLAG_CREATED_FROM_PARTNER
user.notification = False
user.trial_end = None
Job.create(
name=config.JOB_SEND_PROTON_WELCOME_1,
payload={"user_id": user.id},
run_at=arrow.now(),
)
Session.flush()
return user
# create a first alias mail to show user how to use when they login
alias = Alias.create_new(
user,
prefix="simplelogin-newsletter",
mailbox_id=mb.id,
note="This is your first alias. It's used to receive SimpleLogin communications "
"like new features announcements, newsletters.",
)
Session.flush()
user.newsletter_alias_id = alias.id
Session.flush()
if config.DISABLE_ONBOARDING:
LOG.d("Disable onboarding emails")
return user
# Schedule onboarding emails
Job.create(
name=config.JOB_ONBOARDING_1,
payload={"user_id": user.id},
run_at=arrow.now().shift(days=1),
)
Job.create(
name=config.JOB_ONBOARDING_2,
payload={"user_id": user.id},
run_at=arrow.now().shift(days=2),
)
Job.create(
name=config.JOB_ONBOARDING_4,
payload={"user_id": user.id},
run_at=arrow.now().shift(days=3),
)
Session.flush()
return user
def get_active_subscription(
self, include_partner_subscription: bool = True
) -> Optional[
Union[
Subscription
| AppleSubscription
| ManualSubscription
| CoinbaseSubscription
| PartnerSubscription
]
]:
sub: Subscription = self.get_paddle_subscription()
if sub:
return sub
apple_sub: AppleSubscription = AppleSubscription.get_by(user_id=self.id)
if apple_sub and apple_sub.is_valid():
return apple_sub
manual_sub: ManualSubscription = ManualSubscription.get_by(user_id=self.id)
if manual_sub and manual_sub.is_active():
return manual_sub
coinbase_subscription: CoinbaseSubscription = CoinbaseSubscription.get_by(
user_id=self.id
)
if coinbase_subscription and coinbase_subscription.is_active():
return coinbase_subscription
if include_partner_subscription:
partner_sub: PartnerSubscription = PartnerSubscription.find_by_user_id(
self.id
)
if partner_sub and partner_sub.is_active():
return partner_sub
return None
def get_active_subscription_end(
self, include_partner_subscription: bool = True
) -> Optional[arrow.Arrow]:
sub = self.get_active_subscription(
include_partner_subscription=include_partner_subscription
)
if isinstance(sub, Subscription):
return arrow.get(sub.next_bill_date)
if isinstance(sub, AppleSubscription):
return sub.expires_date
if isinstance(sub, ManualSubscription):
return sub.end_at
if isinstance(sub, CoinbaseSubscription):
return sub.end_at
return None
# region Billing
def lifetime_or_active_subscription(
self, include_partner_subscription: bool = True
) -> bool:
"""True if user has lifetime licence or active subscription"""
if self.lifetime:
return True
return self.get_active_subscription(include_partner_subscription) is not None
def is_paid(self) -> bool:
"""same as _lifetime_or_active_subscription but not include free manual subscription"""
sub = self.get_active_subscription()
if sub is None:
return False
if isinstance(sub, ManualSubscription) and sub.is_giveaway:
return False
return True
def is_active(self) -> bool:
if self.delete_on is None:
return True
return self.delete_on < arrow.now()
def in_trial(self):
"""return True if user does not have lifetime licence or an active subscription AND is in trial period"""
if self.lifetime_or_active_subscription():
return False
if self.trial_end and arrow.now() < self.trial_end:
return True
return False
def should_show_upgrade_button(self):
if self.lifetime_or_active_subscription():
return False
return True
def is_premium(self, include_partner_subscription: bool = True) -> bool:
"""
user is premium if they:
- have a lifetime deal or
- in trial period or
- active subscription
"""
if self.lifetime_or_active_subscription(include_partner_subscription):
return True
if self.trial_end and arrow.now() < self.trial_end:
return True
return False
def upgrade_channel(self) -> str:
"""Used on admin dashboard"""
# user can have multiple subscription channel
channels = []
if self.lifetime:
channels.append("Lifetime")
sub: Subscription = self.get_paddle_subscription()
if sub:
if sub.cancelled:
channels.append(
f"""Cancelled Paddle Subscription <a href="https://vendors.paddle.com/subscriptions/customers/manage/{sub.subscription_id}">{sub.subscription_id}</a> {sub.plan_name()} ends at {sub.next_bill_date}"""
)
else:
channels.append(
f"""Active Paddle Subscription <a href="https://vendors.paddle.com/subscriptions/customers/manage/{sub.subscription_id}">{sub.subscription_id}</a> {sub.plan_name()}, renews at {sub.next_bill_date}"""
)
apple_sub: AppleSubscription = AppleSubscription.get_by(user_id=self.id)
if apple_sub and apple_sub.is_valid():
channels.append(f"Apple Subscription {apple_sub.expires_date.humanize()}")
manual_sub: ManualSubscription = ManualSubscription.get_by(user_id=self.id)
if manual_sub and manual_sub.is_active():
mode = "Giveaway" if manual_sub.is_giveaway else "Paid"
channels.append(
f"Manual Subscription {manual_sub.comment} {mode} {manual_sub.end_at.humanize()}"
)
coinbase_subscription: CoinbaseSubscription = CoinbaseSubscription.get_by(
user_id=self.id
)
if coinbase_subscription and coinbase_subscription.is_active():
channels.append(
f"Coinbase Subscription ends {coinbase_subscription.end_at.humanize()}"
)
r = (
Session.query(PartnerSubscription, PartnerUser, Partner)
.filter(
PartnerSubscription.partner_user_id == PartnerUser.id,
PartnerUser.user_id == self.id,
Partner.id == PartnerUser.partner_id,
)
.first()
)
if r and r[0].is_active():
channels.append(
f"Subscription via {r[2].name} partner , ends {r[0].end_at.humanize()}"
)
return ".\n".join(channels)
# endregion
def max_alias_for_free_account(self) -> int:
if (
self.FLAG_FREE_OLD_ALIAS_LIMIT
== self.flags & self.FLAG_FREE_OLD_ALIAS_LIMIT
):
return config.MAX_NB_EMAIL_OLD_FREE_PLAN
else:
return config.MAX_NB_EMAIL_FREE_PLAN
def can_create_new_alias(self) -> bool:
"""
Whether user can create a new alias. User can't create a new alias if
- has more than 15 aliases in the free plan, *even in the free trial*
"""
if not self.is_active():
return False
if self.disabled:
return False
if self.lifetime_or_active_subscription():
return True
else:
return (
Alias.filter_by(user_id=self.id).count()
< self.max_alias_for_free_account()
)
def can_send_or_receive(self) -> bool:
if self.disabled:
LOG.i(f"User {self} is disabled. Cannot receive or send emails")
return False
if self.delete_on is not None:
LOG.i(
f"User {self} is scheduled to be deleted. Cannot receive or send emails"
)
return False
return True
def profile_picture_url(self):
if self.profile_picture_id:
return self.profile_picture.get_url()
else:
return url_for("static", filename="default-avatar.png")
def suggested_emails(self, website_name) -> (str, [str]):
"""return suggested email and other email choices"""
website_name = convert_to_id(website_name)
all_aliases = [
ge.email for ge in Alias.filter_by(user_id=self.id, enabled=True)
]
if self.can_create_new_alias():
suggested_alias = Alias.create_new(self, prefix=website_name).email
else:
# pick an email from the list of gen emails
suggested_alias = random.choice(all_aliases)
return (
suggested_alias,
list(set(all_aliases).difference({suggested_alias})),
)
def suggested_names(self) -> (str, [str]):
"""return suggested name and other name choices"""
other_name = convert_to_id(self.name)
return self.name, [other_name, "Anonymous", "whoami"]
def get_name_initial(self) -> str:
if not self.name:
return ""
names = self.name.split(" ")
return "".join([n[0].upper() for n in names if n])
def get_paddle_subscription(self) -> Optional["Subscription"]:
"""return *active* Paddle subscription
Return None if the subscription is already expired
TODO: support user unsubscribe and re-subscribe
"""
sub = Subscription.get_by(user_id=self.id)
if sub:
# grace period is 14 days
# sub is active until the next billing_date + PADDLE_SUBSCRIPTION_GRACE_DAYS
if (
sub.next_bill_date
>= arrow.now().shift(days=-PADDLE_SUBSCRIPTION_GRACE_DAYS).date()
):
return sub
# past subscription, user is considered not having a subscription = free plan
else:
return None
else:
return sub
def verified_custom_domains(self) -> List["CustomDomain"]:
return (
CustomDomain.filter_by(user_id=self.id, ownership_verified=True)
.order_by(CustomDomain.domain.asc())
.all()
)
def mailboxes(self) -> List["Mailbox"]:
"""list of mailbox that user own"""
mailboxes = []
for mailbox in Mailbox.filter_by(user_id=self.id, verified=True):
mailboxes.append(mailbox)
return mailboxes
def nb_directory(self):
return Directory.filter_by(user_id=self.id).count()
def has_custom_domain(self):
return CustomDomain.filter_by(user_id=self.id, verified=True).count() > 0
def custom_domains(self):
return CustomDomain.filter_by(user_id=self.id, verified=True).all()
def available_domains_for_random_alias(
self, alias_options: Optional[AliasOptions] = None
) -> List[Tuple[bool, str]]:
"""Return available domains for user to create random aliases
Each result record contains:
- whether the domain belongs to SimpleLogin
- the domain
"""
res = []
for domain in self.available_sl_domains(alias_options=alias_options):
res.append((True, domain))
for custom_domain in self.verified_custom_domains():
res.append((False, custom_domain.domain))
return res
def default_random_alias_domain(self) -> str:
"""return the domain used for the random alias"""
if self.default_alias_custom_domain_id:
custom_domain = CustomDomain.get(self.default_alias_custom_domain_id)
# sanity check
if (
not custom_domain
or not custom_domain.verified
or custom_domain.user_id != self.id
):
LOG.w("Problem with %s default random alias domain", self)
return config.FIRST_ALIAS_DOMAIN
return custom_domain.domain
if self.default_alias_public_domain_id:
sl_domain = SLDomain.get(self.default_alias_public_domain_id)
# sanity check
if not sl_domain:
LOG.e("Problem with %s public random alias domain", self)
return config.FIRST_ALIAS_DOMAIN
if sl_domain.premium_only and not self.is_premium():
LOG.w(
"%s is not premium and cannot use %s. Reset default random alias domain setting",
self,
sl_domain,
)
self.default_alias_custom_domain_id = None
self.default_alias_public_domain_id = None
Session.commit()
return config.FIRST_ALIAS_DOMAIN
return sl_domain.domain
return config.FIRST_ALIAS_DOMAIN
def fido_enabled(self) -> bool:
if self.fido_uuid is not None:
return True
return False
def two_factor_authentication_enabled(self) -> bool:
return self.enable_otp or self.fido_enabled()
def get_communication_email(self) -> (Optional[str], str, bool):
"""
Return
- the email that user uses to receive email communication. None if user unsubscribes from newsletter
- the unsubscribe URL
- whether the unsubscribe method is via sending email (mailto:) or Http POST
"""
if self.notification and self.activated and not self.disabled:
if self.newsletter_alias_id:
alias = Alias.get(self.newsletter_alias_id)
if alias.enabled:
unsub = UnsubscribeEncoder.encode(
UnsubscribeAction.DisableAlias, alias.id
)
return alias.email, unsub.link, unsub.via_email
# alias disabled -> user doesn't want to receive newsletter
else:
return None, "", False
else:
# do not handle http POST unsubscribe
if config.UNSUBSCRIBER:
# use * as suffix instead of = as for alias unsubscribe
return (
self.email,
UnsubscribeEncoder.encode_mailto(
UnsubscribeAction.UnsubscribeNewsletter, self.id
),
True,
)
return None, "", False
def available_sl_domains(
self, alias_options: Optional[AliasOptions] = None
) -> [str]:
"""
Return all SimpleLogin domains that user can use when creating a new alias, including:
- SimpleLogin public domains, available for all users (ALIAS_DOMAIN)
- SimpleLogin premium domains, only available for Premium accounts (PREMIUM_ALIAS_DOMAIN)
"""
return [
sl_domain.domain
for sl_domain in self.get_sl_domains(alias_options=alias_options)
]
def get_sl_domains(
self, alias_options: Optional[AliasOptions] = None
) -> list["SLDomain"]:
if alias_options is None:
alias_options = AliasOptions()
top_conds = [SLDomain.hidden == False] # noqa: E712
or_conds = [] # noqa:E711
if self.default_alias_public_domain_id is not None:
default_domain_conds = [SLDomain.id == self.default_alias_public_domain_id]
if not self.is_premium():
default_domain_conds.append(
SLDomain.premium_only == False # noqa: E712
)
or_conds.append(and_(*default_domain_conds).self_group())
if alias_options.show_partner_domains is not None:
partner_user = PartnerUser.filter_by(
user_id=self.id, partner_id=alias_options.show_partner_domains.id
).first()
if partner_user is not None:
partner_domain_cond = [SLDomain.partner_id == partner_user.partner_id]
if alias_options.show_partner_premium is None:
alias_options.show_partner_premium = self.is_premium()
if not alias_options.show_partner_premium:
partner_domain_cond.append(
SLDomain.premium_only == False # noqa: E712
)
or_conds.append(and_(*partner_domain_cond).self_group())
if alias_options.show_sl_domains:
sl_conds = [SLDomain.partner_id == None] # noqa: E711
if not self.is_premium():
sl_conds.append(SLDomain.premium_only == False) # noqa: E712
or_conds.append(and_(*sl_conds).self_group())
top_conds.append(or_(*or_conds))
query = Session.query(SLDomain).filter(*top_conds).order_by(SLDomain.order)
return query.all()
def available_alias_domains(
self, alias_options: Optional[AliasOptions] = None
) -> [str]:
"""return all domains that user can use when creating a new alias, including:
- SimpleLogin public domains, available for all users (ALIAS_DOMAIN)
- SimpleLogin premium domains, only available for Premium accounts (PREMIUM_ALIAS_DOMAIN)
- Verified custom domains
"""
domains = self.available_sl_domains(alias_options=alias_options)
for custom_domain in self.verified_custom_domains():
domains.append(custom_domain.domain)
# can have duplicate where a "root" user has a domain that's also listed in SL domains
return list(set(domains))
def should_show_app_page(self) -> bool:
"""whether to show the app page"""
return (
# when user has used the "Sign in with SL" button before
ClientUser.filter(ClientUser.user_id == self.id).count()
# or when user has created an app
+ Client.filter(Client.user_id == self.id).count()
> 0
)
def get_random_alias_suffix(self, custom_domain: Optional["CustomDomain"] = None):
"""Get random suffix for an alias based on user's preference.
Use a shorter suffix in case of custom domain
Returns:
str: the random suffix generated
"""
if self.random_alias_suffix == AliasSuffixEnum.random_string.value:
return random_string(config.ALIAS_RANDOM_SUFFIX_LENGTH, include_digits=True)
if custom_domain is None:
return random_words(1, 3)
return random_words(1)
def can_create_contacts(self) -> bool:
if self.is_premium():
return True
if self.flags & User.FLAG_FREE_DISABLE_CREATE_ALIAS == 0:
return True
return not config.DISABLE_CREATE_CONTACTS_FOR_FREE_USERS
def __repr__(self):
return f"<User {self.id} {self.name} {self.email}>"
class Alias(Base, ModelMixin):
__tablename__ = "alias"
FLAG_PARTNER_CREATED = 1 << 0
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, index=True
)
email = sa.Column(sa.String(128), unique=True, nullable=False)
# the name to use when user replies/sends from alias
name = sa.Column(sa.String(128), nullable=True, default=None)
enabled = sa.Column(sa.Boolean(), default=True, nullable=False)
flags = sa.Column(
sa.BigInteger(), default=0, server_default="0", nullable=False, index=True
)
custom_domain_id = sa.Column(
sa.ForeignKey("custom_domain.id", ondelete="cascade"), nullable=True, index=True
)
custom_domain = orm.relationship("CustomDomain", foreign_keys=[custom_domain_id])
# To know whether an alias is created "on the fly", i.e. via the custom domain catch-all feature
automatic_creation = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# to know whether an alias belongs to a directory
directory_id = sa.Column(
sa.ForeignKey("directory.id", ondelete="cascade"), nullable=True, index=True
)
note = sa.Column(sa.Text, default=None, nullable=True)
# an alias can be owned by another mailbox
mailbox_id = sa.Column(
sa.ForeignKey("mailbox.id", ondelete="cascade"), nullable=False, index=True
)
# prefix _ to avoid this object being used accidentally.
# To have the list of all mailboxes, should use AliasInfo instead
_mailboxes = orm.relationship("Mailbox", secondary="alias_mailbox", lazy="joined")
# If the mailbox has PGP-enabled, user can choose disable the PGP on the alias
# this is useful when some senders already support PGP
disable_pgp = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# a way to bypass the bounce automatic disable mechanism
cannot_be_disabled = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# when a mailbox wants to send an email on behalf of the alias via the reverse-alias
# several checks are performed to avoid email spoofing
# this option allow disabling these checks
disable_email_spoofing_check = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# to know whether an alias is added using a batch import
batch_import_id = sa.Column(
sa.ForeignKey("batch_import.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
# set in case of alias transfer.
original_owner_id = sa.Column(
sa.ForeignKey(User.id, ondelete="SET NULL"), nullable=True
)
# alias is pinned on top
pinned = sa.Column(sa.Boolean, nullable=False, default=False, server_default="0")
# used to transfer an alias to another user
transfer_token = sa.Column(sa.String(64), default=None, unique=True, nullable=True)
transfer_token_expiration = sa.Column(
ArrowType, default=arrow.utcnow, nullable=True
)
# have I been pwned
hibp_last_check = sa.Column(ArrowType, default=None, index=True)
hibp_breaches = orm.relationship("Hibp", secondary="alias_hibp")
# to use Postgres full text search. Only applied on "note" column for now
# this is a generated Postgres column
ts_vector = sa.Column(
TSVector(), sa.Computed("to_tsvector('english', note)", persisted=True)
)
last_email_log_id = sa.Column(sa.Integer, default=None, nullable=True)
__table_args__ = (
Index("ix_video___ts_vector__", ts_vector, postgresql_using="gin"),
# index on note column using pg_trgm
Index(
"note_pg_trgm_index",
"note",
postgresql_ops={"note": "gin_trgm_ops"},
postgresql_using="gin",
),
)
user = orm.relationship(User, foreign_keys=[user_id])
mailbox = orm.relationship("Mailbox", lazy="joined")
def mailboxes(self):
ret = [self.mailbox]
for m in self._mailboxes:
if m.id is not self.mailbox.id:
ret.append(m)
ret = [mb for mb in ret if mb.verified]
ret = sorted(ret, key=lambda mb: mb.email)
return ret
def authorized_addresses(self) -> [str]:
"""return addresses that can send on behalf of this alias, i.e. can send emails to this alias's reverse-aliases
Including its mailboxes and their authorized addresses
"""
mailboxes = self.mailboxes
ret = [mb.email for mb in mailboxes]
for mailbox in mailboxes:
for aa in mailbox.authorized_addresses:
ret.append(aa.email)
return ret
def mailbox_support_pgp(self) -> bool:
"""return True of one of the mailboxes support PGP"""
for mb in self.mailboxes:
if mb.pgp_enabled():
return True
return False
def pgp_enabled(self) -> bool:
if self.mailbox_support_pgp() and not self.disable_pgp:
return True
return False
def get_custom_domain(alias_address) -> Optional["CustomDomain"]:
alias_domain = validate_email(
alias_address, check_deliverability=False, allow_smtputf8=False
).domain
# handle the case a SLDomain is also a CustomDomain
if SLDomain.get_by(domain=alias_domain) is None:
custom_domain = CustomDomain.get_by(domain=alias_domain)
if custom_domain:
return custom_domain
def create(cls, **kw):
commit = kw.pop("commit", False)
flush = kw.pop("flush", False)
new_alias = cls(**kw)
user = User.get(new_alias.user_id)
if user.is_premium():
limits = config.ALIAS_CREATE_RATE_LIMIT_PAID
else:
limits = config.ALIAS_CREATE_RATE_LIMIT_FREE
# limits is array of (hits,days)
for limit in limits:
key = f"alias_create_{limit[1]}d:{user.id}"
rate_limiter.check_bucket_limit(key, limit[0], limit[1])
email = kw["email"]
# make sure email is lowercase and doesn't have any whitespace
email = sanitize_email(email)
# make sure alias is not in global trash, i.e. DeletedAlias table
if DeletedAlias.get_by(email=email):
raise AliasInTrashError
if DomainDeletedAlias.get_by(email=email):
raise AliasInTrashError
# detect whether alias should belong to a custom domain
if "custom_domain_id" not in kw:
custom_domain = Alias.get_custom_domain(email)
if custom_domain:
new_alias.custom_domain_id = custom_domain.id
Session.add(new_alias)
DailyMetric.get_or_create_today_metric().nb_alias += 1
if commit:
Session.commit()
if flush:
Session.flush()
return new_alias
def create_new(cls, user, prefix, note=None, mailbox_id=None):
prefix = prefix.lower().strip().replace(" ", "")
if not prefix:
raise Exception("alias prefix cannot be empty")
# find the right suffix - avoid infinite loop by running this at max 1000 times
for _ in range(1000):
suffix = user.get_random_alias_suffix()
email = f"{prefix}.{suffix}@{config.FIRST_ALIAS_DOMAIN}"
if available_sl_email(email):
break
return Alias.create(
user_id=user.id,
email=email,
note=note,
mailbox_id=mailbox_id or user.default_mailbox_id,
)
def delete(cls, obj_id):
raise Exception("should use delete_alias(alias,user) instead")
def create_new_random(
cls,
user,
scheme: int = AliasGeneratorEnum.word.value,
in_hex: bool = False,
note: str = None,
):
"""create a new random alias"""
custom_domain = None
random_email = None
if user.default_alias_custom_domain_id:
custom_domain = CustomDomain.get(user.default_alias_custom_domain_id)
random_email = generate_random_alias_email(
scheme=scheme, in_hex=in_hex, alias_domain=custom_domain.domain
)
elif user.default_alias_public_domain_id:
sl_domain: SLDomain = SLDomain.get(user.default_alias_public_domain_id)
if sl_domain.premium_only and not user.is_premium():
LOG.w("%s not premium, cannot use %s", user, sl_domain)
else:
random_email = generate_random_alias_email(
scheme=scheme, in_hex=in_hex, alias_domain=sl_domain.domain
)
if not random_email:
random_email = generate_random_alias_email(scheme=scheme, in_hex=in_hex)
alias = Alias.create(
user_id=user.id,
email=random_email,
mailbox_id=user.default_mailbox_id,
note=note,
)
if custom_domain:
alias.custom_domain_id = custom_domain.id
return alias
def mailbox_email(self):
if self.mailbox_id:
return self.mailbox.email
else:
return self.user.email
def __repr__(self):
return f"<Alias {self.id} {self.email}>"
class AliasUsedOn(Base, ModelMixin):
"""Used to know where an alias is created"""
__tablename__ = "alias_used_on"
__table_args__ = (
sa.UniqueConstraint("alias_id", "hostname", name="uq_alias_used"),
)
alias_id = sa.Column(
sa.ForeignKey(Alias.id, ondelete="cascade"), nullable=False, index=True
)
user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False)
alias = orm.relationship(Alias)
hostname = sa.Column(sa.String(1024), nullable=False)
def convert_to_id(s: str):
"""convert a string to id-like: remove space, remove special accent"""
s = s.lower()
s = unidecode(s)
s = s.replace(" ", "")
return s[:256]
The provided code snippet includes necessary dependencies for implementing the `options_v4` function. Write a Python function `def options_v4()` to solve the following problem:
Return what options user has when creating new alias. Same as v3 but return time-based signed-suffix in addition to suffix. To be used with /v2/alias/custom/new Input: a valid api-key in "Authentication" header and optional "hostname" in args Output: cf README can_create: bool suffixes: [[suffix, signed_suffix]] prefix_suggestion: str recommendation: Optional dict alias: str hostname: str
Here is the function:
def options_v4():
"""
Return what options user has when creating new alias.
Same as v3 but return time-based signed-suffix in addition to suffix. To be used with /v2/alias/custom/new
Input:
a valid api-key in "Authentication" header and
optional "hostname" in args
Output: cf README
can_create: bool
suffixes: [[suffix, signed_suffix]]
prefix_suggestion: str
recommendation: Optional dict
alias: str
hostname: str
"""
user = g.user
hostname = request.args.get("hostname")
ret = {
"can_create": user.can_create_new_alias(),
"suffixes": [],
"prefix_suggestion": "",
}
# recommendation alias if exist
if hostname:
# put the latest used alias first
q = (
Session.query(AliasUsedOn, Alias, User)
.filter(
AliasUsedOn.alias_id == Alias.id,
Alias.user_id == user.id,
AliasUsedOn.hostname == hostname,
)
.order_by(desc(AliasUsedOn.created_at))
)
r = q.first()
if r:
_, alias, _ = r
LOG.d("found alias %s %s %s", alias, hostname, user)
ret["recommendation"] = {"alias": alias.email, "hostname": hostname}
# custom alias suggestion and suffix
if hostname:
# keep only the domain name of hostname, ignore TLD and subdomain
# for ex www.groupon.com -> groupon
ext = tldextract.extract(hostname)
prefix_suggestion = ext.domain
prefix_suggestion = convert_to_id(prefix_suggestion)
ret["prefix_suggestion"] = prefix_suggestion
suffixes = get_alias_suffixes(user)
# custom domain should be put first
ret["suffixes"] = list([suffix.suffix, suffix.signed_suffix] for suffix in suffixes)
return jsonify(ret) | Return what options user has when creating new alias. Same as v3 but return time-based signed-suffix in addition to suffix. To be used with /v2/alias/custom/new Input: a valid api-key in "Authentication" header and optional "hostname" in args Output: cf README can_create: bool suffixes: [[suffix, signed_suffix]] prefix_suggestion: str recommendation: Optional dict alias: str hostname: str |
180,597 | import tldextract
from flask import jsonify, request, g
from sqlalchemy import desc
from app.alias_suffix import get_alias_suffixes
from app.api.base import api_bp, require_api_auth
from app.db import Session
from app.log import LOG
from app.models import AliasUsedOn, Alias, User
from app.utils import convert_to_id
def get_alias_suffixes(
user: User, alias_options: Optional[AliasOptions] = None
) -> [AliasSuffix]:
"""
Similar to as get_available_suffixes() but also return custom domain that doesn't have MX set up.
"""
user_custom_domains = user.verified_custom_domains()
alias_suffixes: [AliasSuffix] = []
# put custom domain first
# for each user domain, generate both the domain and a random suffix version
for custom_domain in user_custom_domains:
if custom_domain.random_prefix_generation:
suffix = (
f".{user.get_random_alias_suffix(custom_domain)}@{custom_domain.domain}"
)
alias_suffix = AliasSuffix(
is_custom=True,
suffix=suffix,
signed_suffix=signer.sign(suffix).decode(),
is_premium=False,
domain=custom_domain.domain,
mx_verified=custom_domain.verified,
)
if user.default_alias_custom_domain_id == custom_domain.id:
alias_suffixes.insert(0, alias_suffix)
else:
alias_suffixes.append(alias_suffix)
suffix = f"@{custom_domain.domain}"
alias_suffix = AliasSuffix(
is_custom=True,
suffix=suffix,
signed_suffix=signer.sign(suffix).decode(),
is_premium=False,
domain=custom_domain.domain,
mx_verified=custom_domain.verified,
)
# put the default domain to top
# only if random_prefix_generation isn't enabled
if (
user.default_alias_custom_domain_id == custom_domain.id
and not custom_domain.random_prefix_generation
):
alias_suffixes.insert(0, alias_suffix)
else:
alias_suffixes.append(alias_suffix)
# then SimpleLogin domain
sl_domains = user.get_sl_domains(alias_options=alias_options)
default_domain_found = False
for sl_domain in sl_domains:
prefix = (
"" if config.DISABLE_ALIAS_SUFFIX else f".{user.get_random_alias_suffix()}"
)
suffix = f"{prefix}@{sl_domain.domain}"
alias_suffix = AliasSuffix(
is_custom=False,
suffix=suffix,
signed_suffix=signer.sign(suffix).decode(),
is_premium=sl_domain.premium_only,
domain=sl_domain.domain,
mx_verified=True,
)
# No default or this is not the default
if (
user.default_alias_public_domain_id is None
or user.default_alias_public_domain_id != sl_domain.id
):
alias_suffixes.append(alias_suffix)
else:
default_domain_found = True
alias_suffixes.insert(0, alias_suffix)
if not default_domain_found:
domain_conditions = {"id": user.default_alias_public_domain_id, "hidden": False}
if not user.is_premium():
domain_conditions["premium_only"] = False
sl_domain = SLDomain.get_by(**domain_conditions)
if sl_domain:
prefix = (
""
if config.DISABLE_ALIAS_SUFFIX
else f".{user.get_random_alias_suffix()}"
)
suffix = f"{prefix}@{sl_domain.domain}"
alias_suffix = AliasSuffix(
is_custom=False,
suffix=suffix,
signed_suffix=signer.sign(suffix).decode(),
is_premium=sl_domain.premium_only,
domain=sl_domain.domain,
mx_verified=True,
)
alias_suffixes.insert(0, alias_suffix)
return alias_suffixes
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
LOG = _get_logger("SL")
class User(Base, ModelMixin, UserMixin, PasswordOracle):
__tablename__ = "users"
FLAG_FREE_DISABLE_CREATE_ALIAS = 1 << 0
FLAG_CREATED_FROM_PARTNER = 1 << 1
FLAG_FREE_OLD_ALIAS_LIMIT = 1 << 2
email = sa.Column(sa.String(256), unique=True, nullable=False)
name = sa.Column(sa.String(128), nullable=True)
is_admin = sa.Column(sa.Boolean, nullable=False, default=False)
alias_generator = sa.Column(
sa.Integer,
nullable=False,
default=AliasGeneratorEnum.word.value,
server_default=str(AliasGeneratorEnum.word.value),
)
notification = sa.Column(
sa.Boolean, default=True, nullable=False, server_default="1"
)
activated = sa.Column(sa.Boolean, default=False, nullable=False, index=True)
# an account can be disabled if having harmful behavior
disabled = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0")
profile_picture_id = sa.Column(sa.ForeignKey(File.id), nullable=True)
otp_secret = sa.Column(sa.String(16), nullable=True)
enable_otp = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
last_otp = sa.Column(sa.String(12), nullable=True, default=False)
# Fields for WebAuthn
fido_uuid = sa.Column(sa.String(), nullable=True, unique=True)
# the default domain that's used when user creates a new random alias
# default_alias_custom_domain_id XOR default_alias_public_domain_id
default_alias_custom_domain_id = sa.Column(
sa.ForeignKey("custom_domain.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
default_alias_public_domain_id = sa.Column(
sa.ForeignKey("public_domain.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
# some users could have lifetime premium
lifetime = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0")
paid_lifetime = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
lifetime_coupon_id = sa.Column(
sa.ForeignKey("lifetime_coupon.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
# user can use all premium features until this date
trial_end = sa.Column(
ArrowType, default=lambda: arrow.now().shift(days=7, hours=1), nullable=True
)
# the mailbox used when create random alias
# this field is nullable but in practice, it's always set
# it cannot be set to non-nullable though
# as this will create foreign key cycle between User and Mailbox
default_mailbox_id = sa.Column(
sa.ForeignKey("mailbox.id"), nullable=True, default=None
)
profile_picture = orm.relationship(File, foreign_keys=[profile_picture_id])
# Specify the format for sender address
# for the full list, see SenderFormatEnum
sender_format = sa.Column(
sa.Integer, default="0", nullable=False, server_default="0"
)
# to know whether user has explicitly chosen a sender format as opposed to those who use the default ones.
# users who haven't chosen a sender format and are using 1 or 3 format, their sender format will be set to 0
sender_format_updated_at = sa.Column(ArrowType, default=None)
replace_reverse_alias = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
referral_id = sa.Column(
sa.ForeignKey("referral.id", ondelete="SET NULL"),
nullable=True,
default=None,
index=True,
)
referral = orm.relationship("Referral", foreign_keys=[referral_id])
# whether intro has been shown to user
intro_shown = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
default_mailbox = orm.relationship("Mailbox", foreign_keys=[default_mailbox_id])
# user can set a more strict max_spam score to block spams more aggressively
max_spam_score = sa.Column(sa.Integer, nullable=True)
# newsletter is sent to this address
newsletter_alias_id = sa.Column(
sa.ForeignKey("alias.id", ondelete="SET NULL"),
nullable=True,
default=None,
index=True,
)
# whether to include the sender address in reverse-alias
include_sender_in_reverse_alias = sa.Column(
sa.Boolean, default=True, nullable=False, server_default="0"
)
# whether to use random string or random word as suffix
# Random word from dictionary file -> 0
# Completely random string -> 1
random_alias_suffix = sa.Column(
sa.Integer,
nullable=False,
default=AliasSuffixEnum.word.value,
server_default=str(AliasSuffixEnum.random_string.value),
)
# always expand the alias info, i.e. without needing to press "More"
expand_alias_info = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# ignore emails send from a mailbox to its alias. This can happen when replying all to a forwarded email
# can automatically re-includes the alias
ignore_loop_email = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# used for flask-login as an "alternative token"
# cf https://flask-login.readthedocs.io/en/latest/#alternative-tokens
alternative_id = sa.Column(sa.String(128), unique=True, nullable=True)
# by default, when an alias is automatically created, a note like "Created with ...." is created
# If this field is True, the note won't be created.
disable_automatic_alias_note = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# By default, the one-click unsubscribe disable the alias
# If set to true, it will block the sender instead
one_click_unsubscribe_block_sender = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# automatically include the website name when user creates an alias via the SimpleLogin icon in the email field
include_website_in_one_click_alias = sa.Column(
sa.Boolean,
# new user will have this option turned on automatically
default=True,
nullable=False,
# old user will have this option turned off
server_default="0",
)
_directory_quota = sa.Column(
"directory_quota", sa.Integer, default=50, nullable=False, server_default="50"
)
_subdomain_quota = sa.Column(
"subdomain_quota", sa.Integer, default=5, nullable=False, server_default="5"
)
# user can use import to import too many aliases
disable_import = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# user can use the phone feature
can_use_phone = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
# in minutes
phone_quota = sa.Column(sa.Integer, nullable=True)
# Status code to return if is blocked
block_behaviour = sa.Column(
sa.Enum(BlockBehaviourEnum),
nullable=False,
server_default=BlockBehaviourEnum.return_2xx.name,
)
include_header_email_header = sa.Column(
sa.Boolean, default=True, nullable=False, server_default="1"
)
# bitwise flags. Allow for future expansion
flags = sa.Column(
sa.BigInteger,
default=FLAG_FREE_DISABLE_CREATE_ALIAS,
server_default="0",
nullable=False,
)
# Keep original unsub behaviour
unsub_behaviour = sa.Column(
IntEnumType(UnsubscribeBehaviourEnum),
default=UnsubscribeBehaviourEnum.PreserveOriginal,
server_default=str(UnsubscribeBehaviourEnum.DisableAlias.value),
nullable=False,
)
# Trigger hard deletion of the account at this time
delete_on = sa.Column(ArrowType, default=None)
__table_args__ = (
sa.Index(
"ix_users_activated_trial_end_lifetime", activated, trial_end, lifetime
),
sa.Index("ix_users_delete_on", delete_on),
)
def directory_quota(self):
return min(
self._directory_quota,
config.MAX_NB_DIRECTORY - Directory.filter_by(user_id=self.id).count(),
)
def subdomain_quota(self):
return min(
self._subdomain_quota,
config.MAX_NB_SUBDOMAIN
- CustomDomain.filter_by(user_id=self.id, is_sl_subdomain=True).count(),
)
def created_by_partner(self):
return User.FLAG_CREATED_FROM_PARTNER == (
self.flags & User.FLAG_CREATED_FROM_PARTNER
)
def subdomain_is_available():
return SLDomain.filter_by(can_use_subdomain=True).count() > 0
# implement flask-login "alternative token"
def get_id(self):
if self.alternative_id:
return self.alternative_id
else:
return str(self.id)
def create(cls, email, name="", password=None, from_partner=False, **kwargs):
email = sanitize_email(email)
user: User = super(User, cls).create(email=email, name=name[:100], **kwargs)
if password:
user.set_password(password)
Session.flush()
mb = Mailbox.create(user_id=user.id, email=user.email, verified=True)
Session.flush()
user.default_mailbox_id = mb.id
# generate an alternative_id if needed
if "alternative_id" not in kwargs:
user.alternative_id = str(uuid.uuid4())
# If the user is created from partner, do not notify
# nor give a trial
if from_partner:
user.flags = User.FLAG_CREATED_FROM_PARTNER
user.notification = False
user.trial_end = None
Job.create(
name=config.JOB_SEND_PROTON_WELCOME_1,
payload={"user_id": user.id},
run_at=arrow.now(),
)
Session.flush()
return user
# create a first alias mail to show user how to use when they login
alias = Alias.create_new(
user,
prefix="simplelogin-newsletter",
mailbox_id=mb.id,
note="This is your first alias. It's used to receive SimpleLogin communications "
"like new features announcements, newsletters.",
)
Session.flush()
user.newsletter_alias_id = alias.id
Session.flush()
if config.DISABLE_ONBOARDING:
LOG.d("Disable onboarding emails")
return user
# Schedule onboarding emails
Job.create(
name=config.JOB_ONBOARDING_1,
payload={"user_id": user.id},
run_at=arrow.now().shift(days=1),
)
Job.create(
name=config.JOB_ONBOARDING_2,
payload={"user_id": user.id},
run_at=arrow.now().shift(days=2),
)
Job.create(
name=config.JOB_ONBOARDING_4,
payload={"user_id": user.id},
run_at=arrow.now().shift(days=3),
)
Session.flush()
return user
def get_active_subscription(
self, include_partner_subscription: bool = True
) -> Optional[
Union[
Subscription
| AppleSubscription
| ManualSubscription
| CoinbaseSubscription
| PartnerSubscription
]
]:
sub: Subscription = self.get_paddle_subscription()
if sub:
return sub
apple_sub: AppleSubscription = AppleSubscription.get_by(user_id=self.id)
if apple_sub and apple_sub.is_valid():
return apple_sub
manual_sub: ManualSubscription = ManualSubscription.get_by(user_id=self.id)
if manual_sub and manual_sub.is_active():
return manual_sub
coinbase_subscription: CoinbaseSubscription = CoinbaseSubscription.get_by(
user_id=self.id
)
if coinbase_subscription and coinbase_subscription.is_active():
return coinbase_subscription
if include_partner_subscription:
partner_sub: PartnerSubscription = PartnerSubscription.find_by_user_id(
self.id
)
if partner_sub and partner_sub.is_active():
return partner_sub
return None
def get_active_subscription_end(
self, include_partner_subscription: bool = True
) -> Optional[arrow.Arrow]:
sub = self.get_active_subscription(
include_partner_subscription=include_partner_subscription
)
if isinstance(sub, Subscription):
return arrow.get(sub.next_bill_date)
if isinstance(sub, AppleSubscription):
return sub.expires_date
if isinstance(sub, ManualSubscription):
return sub.end_at
if isinstance(sub, CoinbaseSubscription):
return sub.end_at
return None
# region Billing
def lifetime_or_active_subscription(
self, include_partner_subscription: bool = True
) -> bool:
"""True if user has lifetime licence or active subscription"""
if self.lifetime:
return True
return self.get_active_subscription(include_partner_subscription) is not None
def is_paid(self) -> bool:
"""same as _lifetime_or_active_subscription but not include free manual subscription"""
sub = self.get_active_subscription()
if sub is None:
return False
if isinstance(sub, ManualSubscription) and sub.is_giveaway:
return False
return True
def is_active(self) -> bool:
if self.delete_on is None:
return True
return self.delete_on < arrow.now()
def in_trial(self):
"""return True if user does not have lifetime licence or an active subscription AND is in trial period"""
if self.lifetime_or_active_subscription():
return False
if self.trial_end and arrow.now() < self.trial_end:
return True
return False
def should_show_upgrade_button(self):
if self.lifetime_or_active_subscription():
return False
return True
def is_premium(self, include_partner_subscription: bool = True) -> bool:
"""
user is premium if they:
- have a lifetime deal or
- in trial period or
- active subscription
"""
if self.lifetime_or_active_subscription(include_partner_subscription):
return True
if self.trial_end and arrow.now() < self.trial_end:
return True
return False
def upgrade_channel(self) -> str:
"""Used on admin dashboard"""
# user can have multiple subscription channel
channels = []
if self.lifetime:
channels.append("Lifetime")
sub: Subscription = self.get_paddle_subscription()
if sub:
if sub.cancelled:
channels.append(
f"""Cancelled Paddle Subscription <a href="https://vendors.paddle.com/subscriptions/customers/manage/{sub.subscription_id}">{sub.subscription_id}</a> {sub.plan_name()} ends at {sub.next_bill_date}"""
)
else:
channels.append(
f"""Active Paddle Subscription <a href="https://vendors.paddle.com/subscriptions/customers/manage/{sub.subscription_id}">{sub.subscription_id}</a> {sub.plan_name()}, renews at {sub.next_bill_date}"""
)
apple_sub: AppleSubscription = AppleSubscription.get_by(user_id=self.id)
if apple_sub and apple_sub.is_valid():
channels.append(f"Apple Subscription {apple_sub.expires_date.humanize()}")
manual_sub: ManualSubscription = ManualSubscription.get_by(user_id=self.id)
if manual_sub and manual_sub.is_active():
mode = "Giveaway" if manual_sub.is_giveaway else "Paid"
channels.append(
f"Manual Subscription {manual_sub.comment} {mode} {manual_sub.end_at.humanize()}"
)
coinbase_subscription: CoinbaseSubscription = CoinbaseSubscription.get_by(
user_id=self.id
)
if coinbase_subscription and coinbase_subscription.is_active():
channels.append(
f"Coinbase Subscription ends {coinbase_subscription.end_at.humanize()}"
)
r = (
Session.query(PartnerSubscription, PartnerUser, Partner)
.filter(
PartnerSubscription.partner_user_id == PartnerUser.id,
PartnerUser.user_id == self.id,
Partner.id == PartnerUser.partner_id,
)
.first()
)
if r and r[0].is_active():
channels.append(
f"Subscription via {r[2].name} partner , ends {r[0].end_at.humanize()}"
)
return ".\n".join(channels)
# endregion
def max_alias_for_free_account(self) -> int:
if (
self.FLAG_FREE_OLD_ALIAS_LIMIT
== self.flags & self.FLAG_FREE_OLD_ALIAS_LIMIT
):
return config.MAX_NB_EMAIL_OLD_FREE_PLAN
else:
return config.MAX_NB_EMAIL_FREE_PLAN
def can_create_new_alias(self) -> bool:
"""
Whether user can create a new alias. User can't create a new alias if
- has more than 15 aliases in the free plan, *even in the free trial*
"""
if not self.is_active():
return False
if self.disabled:
return False
if self.lifetime_or_active_subscription():
return True
else:
return (
Alias.filter_by(user_id=self.id).count()
< self.max_alias_for_free_account()
)
def can_send_or_receive(self) -> bool:
if self.disabled:
LOG.i(f"User {self} is disabled. Cannot receive or send emails")
return False
if self.delete_on is not None:
LOG.i(
f"User {self} is scheduled to be deleted. Cannot receive or send emails"
)
return False
return True
def profile_picture_url(self):
if self.profile_picture_id:
return self.profile_picture.get_url()
else:
return url_for("static", filename="default-avatar.png")
def suggested_emails(self, website_name) -> (str, [str]):
"""return suggested email and other email choices"""
website_name = convert_to_id(website_name)
all_aliases = [
ge.email for ge in Alias.filter_by(user_id=self.id, enabled=True)
]
if self.can_create_new_alias():
suggested_alias = Alias.create_new(self, prefix=website_name).email
else:
# pick an email from the list of gen emails
suggested_alias = random.choice(all_aliases)
return (
suggested_alias,
list(set(all_aliases).difference({suggested_alias})),
)
def suggested_names(self) -> (str, [str]):
"""return suggested name and other name choices"""
other_name = convert_to_id(self.name)
return self.name, [other_name, "Anonymous", "whoami"]
def get_name_initial(self) -> str:
if not self.name:
return ""
names = self.name.split(" ")
return "".join([n[0].upper() for n in names if n])
def get_paddle_subscription(self) -> Optional["Subscription"]:
"""return *active* Paddle subscription
Return None if the subscription is already expired
TODO: support user unsubscribe and re-subscribe
"""
sub = Subscription.get_by(user_id=self.id)
if sub:
# grace period is 14 days
# sub is active until the next billing_date + PADDLE_SUBSCRIPTION_GRACE_DAYS
if (
sub.next_bill_date
>= arrow.now().shift(days=-PADDLE_SUBSCRIPTION_GRACE_DAYS).date()
):
return sub
# past subscription, user is considered not having a subscription = free plan
else:
return None
else:
return sub
def verified_custom_domains(self) -> List["CustomDomain"]:
return (
CustomDomain.filter_by(user_id=self.id, ownership_verified=True)
.order_by(CustomDomain.domain.asc())
.all()
)
def mailboxes(self) -> List["Mailbox"]:
"""list of mailbox that user own"""
mailboxes = []
for mailbox in Mailbox.filter_by(user_id=self.id, verified=True):
mailboxes.append(mailbox)
return mailboxes
def nb_directory(self):
return Directory.filter_by(user_id=self.id).count()
def has_custom_domain(self):
return CustomDomain.filter_by(user_id=self.id, verified=True).count() > 0
def custom_domains(self):
return CustomDomain.filter_by(user_id=self.id, verified=True).all()
def available_domains_for_random_alias(
self, alias_options: Optional[AliasOptions] = None
) -> List[Tuple[bool, str]]:
"""Return available domains for user to create random aliases
Each result record contains:
- whether the domain belongs to SimpleLogin
- the domain
"""
res = []
for domain in self.available_sl_domains(alias_options=alias_options):
res.append((True, domain))
for custom_domain in self.verified_custom_domains():
res.append((False, custom_domain.domain))
return res
def default_random_alias_domain(self) -> str:
"""return the domain used for the random alias"""
if self.default_alias_custom_domain_id:
custom_domain = CustomDomain.get(self.default_alias_custom_domain_id)
# sanity check
if (
not custom_domain
or not custom_domain.verified
or custom_domain.user_id != self.id
):
LOG.w("Problem with %s default random alias domain", self)
return config.FIRST_ALIAS_DOMAIN
return custom_domain.domain
if self.default_alias_public_domain_id:
sl_domain = SLDomain.get(self.default_alias_public_domain_id)
# sanity check
if not sl_domain:
LOG.e("Problem with %s public random alias domain", self)
return config.FIRST_ALIAS_DOMAIN
if sl_domain.premium_only and not self.is_premium():
LOG.w(
"%s is not premium and cannot use %s. Reset default random alias domain setting",
self,
sl_domain,
)
self.default_alias_custom_domain_id = None
self.default_alias_public_domain_id = None
Session.commit()
return config.FIRST_ALIAS_DOMAIN
return sl_domain.domain
return config.FIRST_ALIAS_DOMAIN
def fido_enabled(self) -> bool:
if self.fido_uuid is not None:
return True
return False
def two_factor_authentication_enabled(self) -> bool:
return self.enable_otp or self.fido_enabled()
def get_communication_email(self) -> (Optional[str], str, bool):
"""
Return
- the email that user uses to receive email communication. None if user unsubscribes from newsletter
- the unsubscribe URL
- whether the unsubscribe method is via sending email (mailto:) or Http POST
"""
if self.notification and self.activated and not self.disabled:
if self.newsletter_alias_id:
alias = Alias.get(self.newsletter_alias_id)
if alias.enabled:
unsub = UnsubscribeEncoder.encode(
UnsubscribeAction.DisableAlias, alias.id
)
return alias.email, unsub.link, unsub.via_email
# alias disabled -> user doesn't want to receive newsletter
else:
return None, "", False
else:
# do not handle http POST unsubscribe
if config.UNSUBSCRIBER:
# use * as suffix instead of = as for alias unsubscribe
return (
self.email,
UnsubscribeEncoder.encode_mailto(
UnsubscribeAction.UnsubscribeNewsletter, self.id
),
True,
)
return None, "", False
def available_sl_domains(
self, alias_options: Optional[AliasOptions] = None
) -> [str]:
"""
Return all SimpleLogin domains that user can use when creating a new alias, including:
- SimpleLogin public domains, available for all users (ALIAS_DOMAIN)
- SimpleLogin premium domains, only available for Premium accounts (PREMIUM_ALIAS_DOMAIN)
"""
return [
sl_domain.domain
for sl_domain in self.get_sl_domains(alias_options=alias_options)
]
def get_sl_domains(
self, alias_options: Optional[AliasOptions] = None
) -> list["SLDomain"]:
if alias_options is None:
alias_options = AliasOptions()
top_conds = [SLDomain.hidden == False] # noqa: E712
or_conds = [] # noqa:E711
if self.default_alias_public_domain_id is not None:
default_domain_conds = [SLDomain.id == self.default_alias_public_domain_id]
if not self.is_premium():
default_domain_conds.append(
SLDomain.premium_only == False # noqa: E712
)
or_conds.append(and_(*default_domain_conds).self_group())
if alias_options.show_partner_domains is not None:
partner_user = PartnerUser.filter_by(
user_id=self.id, partner_id=alias_options.show_partner_domains.id
).first()
if partner_user is not None:
partner_domain_cond = [SLDomain.partner_id == partner_user.partner_id]
if alias_options.show_partner_premium is None:
alias_options.show_partner_premium = self.is_premium()
if not alias_options.show_partner_premium:
partner_domain_cond.append(
SLDomain.premium_only == False # noqa: E712
)
or_conds.append(and_(*partner_domain_cond).self_group())
if alias_options.show_sl_domains:
sl_conds = [SLDomain.partner_id == None] # noqa: E711
if not self.is_premium():
sl_conds.append(SLDomain.premium_only == False) # noqa: E712
or_conds.append(and_(*sl_conds).self_group())
top_conds.append(or_(*or_conds))
query = Session.query(SLDomain).filter(*top_conds).order_by(SLDomain.order)
return query.all()
def available_alias_domains(
self, alias_options: Optional[AliasOptions] = None
) -> [str]:
"""return all domains that user can use when creating a new alias, including:
- SimpleLogin public domains, available for all users (ALIAS_DOMAIN)
- SimpleLogin premium domains, only available for Premium accounts (PREMIUM_ALIAS_DOMAIN)
- Verified custom domains
"""
domains = self.available_sl_domains(alias_options=alias_options)
for custom_domain in self.verified_custom_domains():
domains.append(custom_domain.domain)
# can have duplicate where a "root" user has a domain that's also listed in SL domains
return list(set(domains))
def should_show_app_page(self) -> bool:
"""whether to show the app page"""
return (
# when user has used the "Sign in with SL" button before
ClientUser.filter(ClientUser.user_id == self.id).count()
# or when user has created an app
+ Client.filter(Client.user_id == self.id).count()
> 0
)
def get_random_alias_suffix(self, custom_domain: Optional["CustomDomain"] = None):
"""Get random suffix for an alias based on user's preference.
Use a shorter suffix in case of custom domain
Returns:
str: the random suffix generated
"""
if self.random_alias_suffix == AliasSuffixEnum.random_string.value:
return random_string(config.ALIAS_RANDOM_SUFFIX_LENGTH, include_digits=True)
if custom_domain is None:
return random_words(1, 3)
return random_words(1)
def can_create_contacts(self) -> bool:
if self.is_premium():
return True
if self.flags & User.FLAG_FREE_DISABLE_CREATE_ALIAS == 0:
return True
return not config.DISABLE_CREATE_CONTACTS_FOR_FREE_USERS
def __repr__(self):
return f"<User {self.id} {self.name} {self.email}>"
class Alias(Base, ModelMixin):
__tablename__ = "alias"
FLAG_PARTNER_CREATED = 1 << 0
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, index=True
)
email = sa.Column(sa.String(128), unique=True, nullable=False)
# the name to use when user replies/sends from alias
name = sa.Column(sa.String(128), nullable=True, default=None)
enabled = sa.Column(sa.Boolean(), default=True, nullable=False)
flags = sa.Column(
sa.BigInteger(), default=0, server_default="0", nullable=False, index=True
)
custom_domain_id = sa.Column(
sa.ForeignKey("custom_domain.id", ondelete="cascade"), nullable=True, index=True
)
custom_domain = orm.relationship("CustomDomain", foreign_keys=[custom_domain_id])
# To know whether an alias is created "on the fly", i.e. via the custom domain catch-all feature
automatic_creation = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# to know whether an alias belongs to a directory
directory_id = sa.Column(
sa.ForeignKey("directory.id", ondelete="cascade"), nullable=True, index=True
)
note = sa.Column(sa.Text, default=None, nullable=True)
# an alias can be owned by another mailbox
mailbox_id = sa.Column(
sa.ForeignKey("mailbox.id", ondelete="cascade"), nullable=False, index=True
)
# prefix _ to avoid this object being used accidentally.
# To have the list of all mailboxes, should use AliasInfo instead
_mailboxes = orm.relationship("Mailbox", secondary="alias_mailbox", lazy="joined")
# If the mailbox has PGP-enabled, user can choose disable the PGP on the alias
# this is useful when some senders already support PGP
disable_pgp = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# a way to bypass the bounce automatic disable mechanism
cannot_be_disabled = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# when a mailbox wants to send an email on behalf of the alias via the reverse-alias
# several checks are performed to avoid email spoofing
# this option allow disabling these checks
disable_email_spoofing_check = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# to know whether an alias is added using a batch import
batch_import_id = sa.Column(
sa.ForeignKey("batch_import.id", ondelete="SET NULL"),
nullable=True,
default=None,
)
# set in case of alias transfer.
original_owner_id = sa.Column(
sa.ForeignKey(User.id, ondelete="SET NULL"), nullable=True
)
# alias is pinned on top
pinned = sa.Column(sa.Boolean, nullable=False, default=False, server_default="0")
# used to transfer an alias to another user
transfer_token = sa.Column(sa.String(64), default=None, unique=True, nullable=True)
transfer_token_expiration = sa.Column(
ArrowType, default=arrow.utcnow, nullable=True
)
# have I been pwned
hibp_last_check = sa.Column(ArrowType, default=None, index=True)
hibp_breaches = orm.relationship("Hibp", secondary="alias_hibp")
# to use Postgres full text search. Only applied on "note" column for now
# this is a generated Postgres column
ts_vector = sa.Column(
TSVector(), sa.Computed("to_tsvector('english', note)", persisted=True)
)
last_email_log_id = sa.Column(sa.Integer, default=None, nullable=True)
__table_args__ = (
Index("ix_video___ts_vector__", ts_vector, postgresql_using="gin"),
# index on note column using pg_trgm
Index(
"note_pg_trgm_index",
"note",
postgresql_ops={"note": "gin_trgm_ops"},
postgresql_using="gin",
),
)
user = orm.relationship(User, foreign_keys=[user_id])
mailbox = orm.relationship("Mailbox", lazy="joined")
def mailboxes(self):
ret = [self.mailbox]
for m in self._mailboxes:
if m.id is not self.mailbox.id:
ret.append(m)
ret = [mb for mb in ret if mb.verified]
ret = sorted(ret, key=lambda mb: mb.email)
return ret
def authorized_addresses(self) -> [str]:
"""return addresses that can send on behalf of this alias, i.e. can send emails to this alias's reverse-aliases
Including its mailboxes and their authorized addresses
"""
mailboxes = self.mailboxes
ret = [mb.email for mb in mailboxes]
for mailbox in mailboxes:
for aa in mailbox.authorized_addresses:
ret.append(aa.email)
return ret
def mailbox_support_pgp(self) -> bool:
"""return True of one of the mailboxes support PGP"""
for mb in self.mailboxes:
if mb.pgp_enabled():
return True
return False
def pgp_enabled(self) -> bool:
if self.mailbox_support_pgp() and not self.disable_pgp:
return True
return False
def get_custom_domain(alias_address) -> Optional["CustomDomain"]:
alias_domain = validate_email(
alias_address, check_deliverability=False, allow_smtputf8=False
).domain
# handle the case a SLDomain is also a CustomDomain
if SLDomain.get_by(domain=alias_domain) is None:
custom_domain = CustomDomain.get_by(domain=alias_domain)
if custom_domain:
return custom_domain
def create(cls, **kw):
commit = kw.pop("commit", False)
flush = kw.pop("flush", False)
new_alias = cls(**kw)
user = User.get(new_alias.user_id)
if user.is_premium():
limits = config.ALIAS_CREATE_RATE_LIMIT_PAID
else:
limits = config.ALIAS_CREATE_RATE_LIMIT_FREE
# limits is array of (hits,days)
for limit in limits:
key = f"alias_create_{limit[1]}d:{user.id}"
rate_limiter.check_bucket_limit(key, limit[0], limit[1])
email = kw["email"]
# make sure email is lowercase and doesn't have any whitespace
email = sanitize_email(email)
# make sure alias is not in global trash, i.e. DeletedAlias table
if DeletedAlias.get_by(email=email):
raise AliasInTrashError
if DomainDeletedAlias.get_by(email=email):
raise AliasInTrashError
# detect whether alias should belong to a custom domain
if "custom_domain_id" not in kw:
custom_domain = Alias.get_custom_domain(email)
if custom_domain:
new_alias.custom_domain_id = custom_domain.id
Session.add(new_alias)
DailyMetric.get_or_create_today_metric().nb_alias += 1
if commit:
Session.commit()
if flush:
Session.flush()
return new_alias
def create_new(cls, user, prefix, note=None, mailbox_id=None):
prefix = prefix.lower().strip().replace(" ", "")
if not prefix:
raise Exception("alias prefix cannot be empty")
# find the right suffix - avoid infinite loop by running this at max 1000 times
for _ in range(1000):
suffix = user.get_random_alias_suffix()
email = f"{prefix}.{suffix}@{config.FIRST_ALIAS_DOMAIN}"
if available_sl_email(email):
break
return Alias.create(
user_id=user.id,
email=email,
note=note,
mailbox_id=mailbox_id or user.default_mailbox_id,
)
def delete(cls, obj_id):
raise Exception("should use delete_alias(alias,user) instead")
def create_new_random(
cls,
user,
scheme: int = AliasGeneratorEnum.word.value,
in_hex: bool = False,
note: str = None,
):
"""create a new random alias"""
custom_domain = None
random_email = None
if user.default_alias_custom_domain_id:
custom_domain = CustomDomain.get(user.default_alias_custom_domain_id)
random_email = generate_random_alias_email(
scheme=scheme, in_hex=in_hex, alias_domain=custom_domain.domain
)
elif user.default_alias_public_domain_id:
sl_domain: SLDomain = SLDomain.get(user.default_alias_public_domain_id)
if sl_domain.premium_only and not user.is_premium():
LOG.w("%s not premium, cannot use %s", user, sl_domain)
else:
random_email = generate_random_alias_email(
scheme=scheme, in_hex=in_hex, alias_domain=sl_domain.domain
)
if not random_email:
random_email = generate_random_alias_email(scheme=scheme, in_hex=in_hex)
alias = Alias.create(
user_id=user.id,
email=random_email,
mailbox_id=user.default_mailbox_id,
note=note,
)
if custom_domain:
alias.custom_domain_id = custom_domain.id
return alias
def mailbox_email(self):
if self.mailbox_id:
return self.mailbox.email
else:
return self.user.email
def __repr__(self):
return f"<Alias {self.id} {self.email}>"
class AliasUsedOn(Base, ModelMixin):
"""Used to know where an alias is created"""
__tablename__ = "alias_used_on"
__table_args__ = (
sa.UniqueConstraint("alias_id", "hostname", name="uq_alias_used"),
)
alias_id = sa.Column(
sa.ForeignKey(Alias.id, ondelete="cascade"), nullable=False, index=True
)
user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False)
alias = orm.relationship(Alias)
hostname = sa.Column(sa.String(1024), nullable=False)
def convert_to_id(s: str):
"""convert a string to id-like: remove space, remove special accent"""
s = s.lower()
s = unidecode(s)
s = s.replace(" ", "")
return s[:256]
The provided code snippet includes necessary dependencies for implementing the `options_v5` function. Write a Python function `def options_v5()` to solve the following problem:
Return what options user has when creating new alias. Same as v4 but uses a better format. To be used with /v2/alias/custom/new Input: a valid api-key in "Authentication" header and optional "hostname" in args Output: cf README can_create: bool suffixes: [ { suffix: "suffix", signed_suffix: "signed_suffix", is_custom: true, is_premium: false } ] prefix_suggestion: str recommendation: Optional dict alias: str hostname: str
Here is the function:
def options_v5():
"""
Return what options user has when creating new alias.
Same as v4 but uses a better format. To be used with /v2/alias/custom/new
Input:
a valid api-key in "Authentication" header and
optional "hostname" in args
Output: cf README
can_create: bool
suffixes: [
{
suffix: "suffix",
signed_suffix: "signed_suffix",
is_custom: true,
is_premium: false
}
]
prefix_suggestion: str
recommendation: Optional dict
alias: str
hostname: str
"""
user = g.user
hostname = request.args.get("hostname")
ret = {
"can_create": user.can_create_new_alias(),
"suffixes": [],
"prefix_suggestion": "",
}
# recommendation alias if exist
if hostname:
# put the latest used alias first
q = (
Session.query(AliasUsedOn, Alias, User)
.filter(
AliasUsedOn.alias_id == Alias.id,
Alias.user_id == user.id,
AliasUsedOn.hostname == hostname,
)
.order_by(desc(AliasUsedOn.created_at))
)
r = q.first()
if r:
_, alias, _ = r
LOG.d("found alias %s %s %s", alias, hostname, user)
ret["recommendation"] = {"alias": alias.email, "hostname": hostname}
# custom alias suggestion and suffix
if hostname:
# keep only the domain name of hostname, ignore TLD and subdomain
# for ex www.groupon.com -> groupon
ext = tldextract.extract(hostname)
prefix_suggestion = ext.domain
prefix_suggestion = convert_to_id(prefix_suggestion)
ret["prefix_suggestion"] = prefix_suggestion
suffixes = get_alias_suffixes(user)
# custom domain should be put first
ret["suffixes"] = [
{
"suffix": suffix.suffix,
"signed_suffix": suffix.signed_suffix,
"is_custom": suffix.is_custom,
"is_premium": suffix.is_premium,
}
for suffix in suffixes
]
return jsonify(ret) | Return what options user has when creating new alias. Same as v4 but uses a better format. To be used with /v2/alias/custom/new Input: a valid api-key in "Authentication" header and optional "hostname" in args Output: cf README can_create: bool suffixes: [ { suffix: "suffix", signed_suffix: "signed_suffix", is_custom: true, is_premium: false } ] prefix_suggestion: str recommendation: Optional dict alias: str hostname: str |
180,598 | from flask import jsonify, g, request
from sqlalchemy_utils.types.arrow import arrow
from app.api.base import api_bp, require_api_auth
from app.db import Session
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
The provided code snippet includes necessary dependencies for implementing the `enter_sudo` function. Write a Python function `def enter_sudo()` to solve the following problem:
Enter sudo mode Input - password: user password to validate request to enter sudo mode
Here is the function:
def enter_sudo():
"""
Enter sudo mode
Input
- password: user password to validate request to enter sudo mode
"""
user = g.user
data = request.get_json() or {}
if "password" not in data:
return jsonify(error="Invalid password"), 403
if not user.check_password(data["password"]):
return jsonify(error="Invalid password"), 403
g.api_key.sudo_mode_at = arrow.now()
Session.commit()
return jsonify(ok=True) | Enter sudo mode Input - password: user password to validate request to enter sudo mode |
180,599 | import base64
import dataclasses
from io import BytesIO
from typing import Optional
from flask import jsonify, g, request, make_response
from app import s3, config
from app.api.base import api_bp, require_api_auth
from app.config import SESSION_COOKIE_NAME
from app.dashboard.views.index import get_stats
from app.db import Session
from app.models import ApiKey, File, PartnerUser, User
from app.proton.utils import get_proton_partner
from app.session import logout_session
from app.utils import random_string
def user_to_dict(user: User) -> dict:
ret = {
"name": user.name or "",
"is_premium": user.is_premium(),
"email": user.email,
"in_trial": user.in_trial(),
"max_alias_free_plan": user.max_alias_for_free_account(),
"connected_proton_address": None,
"can_create_reverse_alias": user.can_create_contacts(),
}
if config.CONNECT_WITH_PROTON:
ret["connected_proton_address"] = get_connected_proton_address(user)
if user.profile_picture_id:
ret["profile_picture_url"] = user.profile_picture.get_url()
else:
ret["profile_picture_url"] = None
return ret
The provided code snippet includes necessary dependencies for implementing the `user_info` function. Write a Python function `def user_info()` to solve the following problem:
Return user info given the api-key Output as json - name - is_premium - email - in_trial - max_alias_free - is_connected_with_proton - can_create_reverse_alias
Here is the function:
def user_info():
"""
Return user info given the api-key
Output as json
- name
- is_premium
- email
- in_trial
- max_alias_free
- is_connected_with_proton
- can_create_reverse_alias
"""
user = g.user
return jsonify(user_to_dict(user)) | Return user info given the api-key Output as json - name - is_premium - email - in_trial - max_alias_free - is_connected_with_proton - can_create_reverse_alias |
180,600 | import base64
import dataclasses
from io import BytesIO
from typing import Optional
from flask import jsonify, g, request, make_response
from app import s3, config
from app.api.base import api_bp, require_api_auth
from app.config import SESSION_COOKIE_NAME
from app.dashboard.views.index import get_stats
from app.db import Session
from app.models import ApiKey, File, PartnerUser, User
from app.proton.utils import get_proton_partner
from app.session import logout_session
from app.utils import random_string
def user_to_dict(user: User) -> dict:
ret = {
"name": user.name or "",
"is_premium": user.is_premium(),
"email": user.email,
"in_trial": user.in_trial(),
"max_alias_free_plan": user.max_alias_for_free_account(),
"connected_proton_address": None,
"can_create_reverse_alias": user.can_create_contacts(),
}
if config.CONNECT_WITH_PROTON:
ret["connected_proton_address"] = get_connected_proton_address(user)
if user.profile_picture_id:
ret["profile_picture_url"] = user.profile_picture.get_url()
else:
ret["profile_picture_url"] = None
return ret
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
class File(Base, ModelMixin):
__tablename__ = "file"
path = sa.Column(sa.String(128), unique=True, nullable=False)
user_id = sa.Column(sa.ForeignKey("users.id", ondelete="cascade"), nullable=True)
def get_url(self, expires_in=3600):
return s3.get_url(self.path, expires_in)
def __repr__(self):
return f"<File {self.path}>"
def random_string(length=10, include_digits=False):
"""Generate a random string of fixed length"""
letters = string.ascii_lowercase
if include_digits:
letters += string.digits
return "".join(secrets.choice(letters) for _ in range(length))
The provided code snippet includes necessary dependencies for implementing the `update_user_info` function. Write a Python function `def update_user_info()` to solve the following problem:
Input - profile_picture (optional): base64 of the profile picture. Set to null to remove the profile picture - name (optional)
Here is the function:
def update_user_info():
"""
Input
- profile_picture (optional): base64 of the profile picture. Set to null to remove the profile picture
- name (optional)
"""
user = g.user
data = request.get_json() or {}
if "profile_picture" in data:
if data["profile_picture"] is None:
if user.profile_picture_id:
file = user.profile_picture
user.profile_picture_id = None
Session.flush()
if file:
File.delete(file.id)
s3.delete(file.path)
Session.flush()
else:
raw_data = base64.decodebytes(data["profile_picture"].encode())
file_path = random_string(30)
file = File.create(user_id=user.id, path=file_path)
Session.flush()
s3.upload_from_bytesio(file_path, BytesIO(raw_data))
user.profile_picture_id = file.id
Session.flush()
if "name" in data:
user.name = data["name"]
Session.commit()
return jsonify(user_to_dict(user)) | Input - profile_picture (optional): base64 of the profile picture. Set to null to remove the profile picture - name (optional) |
180,601 | import base64
import dataclasses
from io import BytesIO
from typing import Optional
from flask import jsonify, g, request, make_response
from app import s3, config
from app.api.base import api_bp, require_api_auth
from app.config import SESSION_COOKIE_NAME
from app.dashboard.views.index import get_stats
from app.db import Session
from app.models import ApiKey, File, PartnerUser, User
from app.proton.utils import get_proton_partner
from app.session import logout_session
from app.utils import random_string
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
class ApiKey(Base, ModelMixin):
"""used in browser extension to identify user"""
__tablename__ = "api_key"
user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False)
code = sa.Column(sa.String(128), unique=True, nullable=False)
name = sa.Column(sa.String(128), nullable=True)
last_used = sa.Column(ArrowType, default=None)
times = sa.Column(sa.Integer, default=0, nullable=False)
sudo_mode_at = sa.Column(ArrowType, default=None)
user = orm.relationship(User)
def create(cls, user_id, name=None, **kwargs):
code = random_string(60)
if cls.get_by(code=code):
code = str(uuid.uuid4())
return super().create(user_id=user_id, name=name, code=code, **kwargs)
def delete_all(cls, user_id):
Session.query(cls).filter(cls.user_id == user_id).delete()
The provided code snippet includes necessary dependencies for implementing the `create_api_key` function. Write a Python function `def create_api_key()` to solve the following problem:
Used to create a new api key Input: - device Output: - api_key
Here is the function:
def create_api_key():
"""Used to create a new api key
Input:
- device
Output:
- api_key
"""
data = request.get_json()
if not data:
return jsonify(error="request body cannot be empty"), 400
device = data.get("device")
api_key = ApiKey.create(user_id=g.user.id, name=device)
Session.commit()
return jsonify(api_key=api_key.code), 201 | Used to create a new api key Input: - device Output: - api_key |
180,602 | import base64
import dataclasses
from io import BytesIO
from typing import Optional
from flask import jsonify, g, request, make_response
from app import s3, config
from app.api.base import api_bp, require_api_auth
from app.config import SESSION_COOKIE_NAME
from app.dashboard.views.index import get_stats
from app.db import Session
from app.models import ApiKey, File, PartnerUser, User
from app.proton.utils import get_proton_partner
from app.session import logout_session
from app.utils import random_string
SESSION_COOKIE_NAME = "slapp"
def logout_session():
logout_user()
purge_fn = getattr(current_app.session_interface, "purge_session", None)
if callable(purge_fn):
purge_fn(session)
The provided code snippet includes necessary dependencies for implementing the `logout` function. Write a Python function `def logout()` to solve the following problem:
Log user out on the web, i.e. remove the cookie Output: - 200
Here is the function:
def logout():
"""
Log user out on the web, i.e. remove the cookie
Output:
- 200
"""
logout_session()
response = make_response(jsonify(msg="User is logged out"), 200)
response.delete_cookie(SESSION_COOKIE_NAME)
return response | Log user out on the web, i.e. remove the cookie Output: - 200 |
180,603 | import base64
import dataclasses
from io import BytesIO
from typing import Optional
from flask import jsonify, g, request, make_response
from app import s3, config
from app.api.base import api_bp, require_api_auth
from app.config import SESSION_COOKIE_NAME
from app.dashboard.views.index import get_stats
from app.db import Session
from app.models import ApiKey, File, PartnerUser, User
from app.proton.utils import get_proton_partner
from app.session import logout_session
from app.utils import random_string
def get_stats(user: User) -> Stats:
nb_alias = Alias.filter_by(user_id=user.id).count()
nb_forward = (
Session.query(EmailLog)
.filter_by(user_id=user.id, is_reply=False, blocked=False, bounced=False)
.count()
)
nb_reply = (
Session.query(EmailLog)
.filter_by(user_id=user.id, is_reply=True, blocked=False, bounced=False)
.count()
)
nb_block = (
Session.query(EmailLog)
.filter_by(user_id=user.id, is_reply=False, blocked=True, bounced=False)
.count()
)
return Stats(
nb_alias=nb_alias, nb_forward=nb_forward, nb_reply=nb_reply, nb_block=nb_block
)
ALIAS_LIMIT,
methods=["POST"],
exempt_when=lambda: request.form.get("form-name") != "create-random-email",
)
)
The provided code snippet includes necessary dependencies for implementing the `user_stats` function. Write a Python function `def user_stats()` to solve the following problem:
Return stats Output as json - nb_alias - nb_forward - nb_reply - nb_block
Here is the function:
def user_stats():
"""
Return stats
Output as json
- nb_alias
- nb_forward
- nb_reply
- nb_block
"""
user = g.user
stats = get_stats(user)
return jsonify(dataclasses.asdict(stats)) | Return stats Output as json - nb_alias - nb_forward - nb_reply - nb_block |
180,604 | import arrow
from flask import jsonify, g, request
from app.api.base import api_bp, require_api_auth
from app.db import Session
from app.log import LOG
from app.models import (
User,
AliasGeneratorEnum,
SLDomain,
CustomDomain,
SenderFormatEnum,
AliasSuffixEnum,
)
from app.proton.utils import perform_proton_account_unlink
def setting_to_dict(user: User):
ret = {
"notification": user.notification,
"alias_generator": "word"
if user.alias_generator == AliasGeneratorEnum.word.value
else "uuid",
"random_alias_default_domain": user.default_random_alias_domain(),
# return the default sender format (AT) in case user uses a non-supported sender format
"sender_format": SenderFormatEnum.get_name(user.sender_format)
or SenderFormatEnum.AT.name,
"random_alias_suffix": AliasSuffixEnum.get_name(user.random_alias_suffix),
}
return ret
The provided code snippet includes necessary dependencies for implementing the `get_setting` function. Write a Python function `def get_setting()` to solve the following problem:
Return user setting
Here is the function:
def get_setting():
"""
Return user setting
"""
user = g.user
return jsonify(setting_to_dict(user)) | Return user setting |
180,605 | import arrow
from flask import jsonify, g, request
from app.api.base import api_bp, require_api_auth
from app.db import Session
from app.log import LOG
from app.models import (
User,
AliasGeneratorEnum,
SLDomain,
CustomDomain,
SenderFormatEnum,
AliasSuffixEnum,
)
from app.proton.utils import perform_proton_account_unlink
def setting_to_dict(user: User):
ret = {
"notification": user.notification,
"alias_generator": "word"
if user.alias_generator == AliasGeneratorEnum.word.value
else "uuid",
"random_alias_default_domain": user.default_random_alias_domain(),
# return the default sender format (AT) in case user uses a non-supported sender format
"sender_format": SenderFormatEnum.get_name(user.sender_format)
or SenderFormatEnum.AT.name,
"random_alias_suffix": AliasSuffixEnum.get_name(user.random_alias_suffix),
}
return ret
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
LOG = _get_logger("SL")
class SenderFormatEnum(EnumE):
AT = 0 # John Wick - john at wick.com
A = 2 # John Wick - john(a)wick.com
NAME_ONLY = 5 # John Wick
AT_ONLY = 6 # john at wick.com
NO_NAME = 7
class AliasGeneratorEnum(EnumE):
word = 1 # aliases are generated based on random words
uuid = 2 # aliases are generated based on uuid
class AliasSuffixEnum(EnumE):
word = 0 # Random word from dictionary file
random_string = 1 # Completely random string
class CustomDomain(Base, ModelMixin):
__tablename__ = "custom_domain"
user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False)
domain = sa.Column(sa.String(128), unique=True, nullable=False)
# default name to use when user replies/sends from alias
name = sa.Column(sa.String(128), nullable=True, default=None)
# mx verified
verified = sa.Column(sa.Boolean, nullable=False, default=False)
dkim_verified = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
spf_verified = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
dmarc_verified = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
_mailboxes = orm.relationship("Mailbox", secondary="domain_mailbox", lazy="joined")
# an alias is created automatically the first time it receives an email
catch_all = sa.Column(sa.Boolean, nullable=False, default=False, server_default="0")
# option to generate random prefix version automatically
random_prefix_generation = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# incremented when a check is failed on the domain
# alert when the number exceeds a threshold
# used in check_custom_domain()
nb_failed_checks = sa.Column(
sa.Integer, default=0, server_default="0", nullable=False
)
# only domain has the ownership verified can go the next DNS step
# MX verified domains before this change don't have to do the TXT check
# and therefore have ownership_verified=True
ownership_verified = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# randomly generated TXT value for verifying domain ownership
# the TXT record should be sl-verification=txt_token
ownership_txt_token = sa.Column(sa.String(128), nullable=True)
# if the domain is SimpleLogin subdomain, no need for the ownership, SPF, DKIM, DMARC check
is_sl_subdomain = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
__table_args__ = (
Index(
"ix_unique_domain", # Index name
"domain", # Columns which are part of the index
unique=True,
postgresql_where=Column("ownership_verified"),
), # The condition
)
user = orm.relationship(User, foreign_keys=[user_id], backref="custom_domains")
def mailboxes(self):
if self._mailboxes:
return self._mailboxes
else:
return [self.user.default_mailbox]
def nb_alias(self):
return Alias.filter_by(custom_domain_id=self.id).count()
def get_trash_url(self):
return config.URL + f"/dashboard/domains/{self.id}/trash"
def get_ownership_dns_txt_value(self):
return f"sl-verification={self.ownership_txt_token}"
def create(cls, **kwargs):
domain = kwargs.get("domain")
kwargs["domain"] = domain.replace("\n", "")
if DeletedSubdomain.get_by(domain=domain):
raise SubdomainInTrashError
domain: CustomDomain = super(CustomDomain, cls).create(**kwargs)
# generate a domain ownership txt token
if not domain.ownership_txt_token:
domain.ownership_txt_token = random_string(30)
Session.commit()
if domain.is_sl_subdomain:
user = domain.user
user._subdomain_quota -= 1
Session.flush()
return domain
def delete(cls, obj_id):
obj: CustomDomain = cls.get(obj_id)
if obj.is_sl_subdomain:
DeletedSubdomain.create(domain=obj.domain)
return super(CustomDomain, cls).delete(obj_id)
def auto_create_rules(self):
return sorted(self._auto_create_rules, key=lambda rule: rule.order)
def __repr__(self):
return f"<Custom Domain {self.domain}>"
class SLDomain(Base, ModelMixin):
"""SimpleLogin domains"""
__tablename__ = "public_domain"
domain = sa.Column(sa.String(128), unique=True, nullable=False)
# only available for premium accounts
premium_only = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
# if True, the domain can be used for the subdomain feature
can_use_subdomain = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
partner_id = sa.Column(
sa.ForeignKey(Partner.id, ondelete="cascade"),
nullable=True,
default=None,
server_default="NULL",
)
# if enabled, do not show this domain when user creates a custom alias
hidden = sa.Column(sa.Boolean, nullable=False, default=False, server_default="0")
# the order in which the domains are shown when user creates a custom alias
order = sa.Column(sa.Integer, nullable=False, default=0, server_default="0")
use_as_reverse_alias = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
def __repr__(self):
return f"<SLDomain {self.domain} {'Premium' if self.premium_only else 'Free'}"
The provided code snippet includes necessary dependencies for implementing the `update_setting` function. Write a Python function `def update_setting()` to solve the following problem:
Update user setting Input: - notification: bool - alias_generator: word|uuid - random_alias_default_domain: str
Here is the function:
def update_setting():
"""
Update user setting
Input:
- notification: bool
- alias_generator: word|uuid
- random_alias_default_domain: str
"""
user = g.user
data = request.get_json() or {}
if "notification" in data:
user.notification = data["notification"]
if "alias_generator" in data:
alias_generator = data["alias_generator"]
if alias_generator not in ["word", "uuid"]:
return jsonify(error="Invalid alias_generator"), 400
if alias_generator == "word":
user.alias_generator = AliasGeneratorEnum.word.value
else:
user.alias_generator = AliasGeneratorEnum.uuid.value
if "sender_format" in data:
sender_format = data["sender_format"]
if not SenderFormatEnum.has_name(sender_format):
return jsonify(error="Invalid sender_format"), 400
user.sender_format = SenderFormatEnum.get_value(sender_format)
user.sender_format_updated_at = arrow.now()
if "random_alias_suffix" in data:
random_alias_suffix = data["random_alias_suffix"]
if not AliasSuffixEnum.has_name(random_alias_suffix):
return jsonify(error="Invalid random_alias_suffix"), 400
user.random_alias_suffix = AliasSuffixEnum.get_value(random_alias_suffix)
if "random_alias_default_domain" in data:
default_domain = data["random_alias_default_domain"]
sl_domain: SLDomain = SLDomain.get_by(domain=default_domain)
if sl_domain:
if sl_domain.premium_only and not user.is_premium():
return jsonify(error="You cannot use this domain"), 400
user.default_alias_public_domain_id = sl_domain.id
user.default_alias_custom_domain_id = None
else:
custom_domain = CustomDomain.get_by(domain=default_domain)
if not custom_domain:
return jsonify(error="invalid domain"), 400
# sanity check
if custom_domain.user_id != user.id or not custom_domain.verified:
LOG.w("%s cannot use domain %s", user, default_domain)
return jsonify(error="invalid domain"), 400
else:
user.default_alias_custom_domain_id = custom_domain.id
user.default_alias_public_domain_id = None
Session.commit()
return jsonify(setting_to_dict(user)) | Update user setting Input: - notification: bool - alias_generator: word|uuid - random_alias_default_domain: str |
180,606 | import arrow
from flask import jsonify, g, request
from app.api.base import api_bp, require_api_auth
from app.db import Session
from app.log import LOG
from app.models import (
User,
AliasGeneratorEnum,
SLDomain,
CustomDomain,
SenderFormatEnum,
AliasSuffixEnum,
)
from app.proton.utils import perform_proton_account_unlink
The provided code snippet includes necessary dependencies for implementing the `get_available_domains_for_random_alias` function. Write a Python function `def get_available_domains_for_random_alias()` to solve the following problem:
Available domains for random alias
Here is the function:
def get_available_domains_for_random_alias():
"""
Available domains for random alias
"""
user = g.user
ret = [
(is_sl, domain) for is_sl, domain in user.available_domains_for_random_alias()
]
return jsonify(ret) | Available domains for random alias |
180,607 | import arrow
from flask import jsonify, g, request
from app.api.base import api_bp, require_api_auth
from app.db import Session
from app.log import LOG
from app.models import (
User,
AliasGeneratorEnum,
SLDomain,
CustomDomain,
SenderFormatEnum,
AliasSuffixEnum,
)
from app.proton.utils import perform_proton_account_unlink
The provided code snippet includes necessary dependencies for implementing the `get_available_domains_for_random_alias_v2` function. Write a Python function `def get_available_domains_for_random_alias_v2()` to solve the following problem:
Available domains for random alias
Here is the function:
def get_available_domains_for_random_alias_v2():
"""
Available domains for random alias
"""
user = g.user
ret = [
{"domain": domain, "is_custom": not is_sl}
for is_sl, domain in user.available_domains_for_random_alias()
]
return jsonify(ret) | Available domains for random alias |
180,608 | import arrow
from flask import jsonify, g, request
from app.api.base import api_bp, require_api_auth
from app.db import Session
from app.log import LOG
from app.models import (
User,
AliasGeneratorEnum,
SLDomain,
CustomDomain,
SenderFormatEnum,
AliasSuffixEnum,
)
from app.proton.utils import perform_proton_account_unlink
def perform_proton_account_unlink(current_user: User):
def unlink_proton_account():
user = g.user
perform_proton_account_unlink(user)
return jsonify({"ok": True}) | null |
180,609 | import arrow
from flask import g
from flask import jsonify
from app.api.base import api_bp, require_api_auth
from app.models import (
PhoneReservation,
PhoneMessage,
)
class PhoneReservation(Base, ModelMixin):
__tablename__ = "phone_reservation"
number_id = sa.Column(
sa.ForeignKey(PhoneNumber.id, ondelete="cascade"), nullable=False
)
user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False)
number = orm.relationship(PhoneNumber)
start = sa.Column(ArrowType, nullable=False)
end = sa.Column(ArrowType, nullable=False)
class PhoneMessage(Base, ModelMixin):
__tablename__ = "phone_message"
number_id = sa.Column(
sa.ForeignKey(PhoneNumber.id, ondelete="cascade"), nullable=False
)
from_number = sa.Column(sa.String(128), nullable=False)
body = sa.Column(sa.Text)
number = orm.relationship(PhoneNumber)
The provided code snippet includes necessary dependencies for implementing the `phone_messages` function. Write a Python function `def phone_messages(reservation_id)` to solve the following problem:
Return messages during this reservation Output: - messages: list of alias: - id - from_number - body - created_at: e.g. 5 minutes ago
Here is the function:
def phone_messages(reservation_id):
"""
Return messages during this reservation
Output:
- messages: list of alias:
- id
- from_number
- body
- created_at: e.g. 5 minutes ago
"""
user = g.user
reservation: PhoneReservation = PhoneReservation.get(reservation_id)
if not reservation or reservation.user_id != user.id:
return jsonify(error="Invalid reservation"), 400
phone_number = reservation.number
messages = PhoneMessage.filter(
PhoneMessage.number_id == phone_number.id,
PhoneMessage.created_at > reservation.start,
PhoneMessage.created_at < reservation.end,
).all()
return (
jsonify(
messages=[
{
"id": message.id,
"from_number": message.from_number,
"body": message.body,
"created_at": message.created_at.humanize(),
}
for message in messages
],
ended=reservation.end < arrow.now(),
),
200,
) | Return messages during this reservation Output: - messages: list of alias: - id - from_number - body - created_at: e.g. 5 minutes ago |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.