id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
180,710 | from app import config
from typing import Optional, List, Tuple
import dns.resolver
def _get_dns_resolver():
my_resolver = dns.resolver.Resolver()
my_resolver.nameservers = config.NAMESERVERS
return my_resolver
The provided code snippet includes necessary dependencies for implementing the `get_cname_record` function. Write a Python function `def get_cname_record(hostname) -> Optional[str]` to solve the following problem:
Return the CNAME record if exists for a domain, WITHOUT the trailing period at the end
Here is the function:
def get_cname_record(hostname) -> Optional[str]:
"""Return the CNAME record if exists for a domain, WITHOUT the trailing period at the end"""
try:
answers = _get_dns_resolver().resolve(hostname, "CNAME", search=True)
except Exception:
return None
for a in answers:
ret = a.to_text()
return ret[:-1]
return None | Return the CNAME record if exists for a domain, WITHOUT the trailing period at the end |
180,711 | import os
from io import BytesIO
from typing import Optional
import boto3
import requests
from app import config
from app.log import LOG
def _get_s3client():
def download_email(path: str) -> Optional[str]:
if config.LOCAL_FILE_UPLOAD:
file_path = os.path.join(config.UPLOAD_DIR, path)
with open(file_path, "rb") as f:
return f.read()
resp = _get_s3client().get_object(
Bucket=config.BUCKET,
Key=path,
)
if not resp or "Body" not in resp:
return None
return resp["Body"].read | null |
180,712 | import os
from io import BytesIO
from typing import Optional
import boto3
import requests
from app import config
from app.log import LOG
def _get_s3client():
global _s3_client
if _s3_client is None:
args = {
"aws_access_key_id": config.AWS_ACCESS_KEY_ID,
"aws_secret_access_key": config.AWS_SECRET_ACCESS_KEY,
"region_name": config.AWS_REGION,
}
if config.AWS_ENDPOINT_URL:
args["endpoint_url"] = config.AWS_ENDPOINT_URL
_s3_client = boto3.client("s3", **args)
return _s3_client
LOG = _get_logger("SL")
def create_bucket_if_not_exists():
s3client = _get_s3client()
buckets = s3client.list_buckets()
for bucket in buckets["Buckets"]:
if bucket["Name"] == config.BUCKET:
LOG.i("Bucket already exists")
return
s3client.create_bucket(Bucket=config.BUCKET)
LOG.i(f"Bucket {config.BUCKET} created") | null |
180,713 | from flask import render_template
from flask_login import login_required
from app.discover.base import discover_bp
from app.models import Client
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
def index():
clients = Client.filter_by(approved=True).all()
return render_template("discover/index.html", clients=clients) | null |
180,714 | from abc import ABC, abstractmethod
from dataclasses import dataclass
from enum import Enum
from typing import Optional
from arrow import Arrow
from newrelic import agent
from sqlalchemy import or_
from app.db import Session
from app.email_utils import send_welcome_email
from app.utils import sanitize_email, canonicalize_email
from app.errors import (
AccountAlreadyLinkedToAnotherPartnerException,
AccountIsUsingAliasAsEmail,
AccountAlreadyLinkedToAnotherUserException,
)
from app.log import LOG
from app.models import (
PartnerSubscription,
Partner,
PartnerUser,
User,
Alias,
)
from app.utils import random_string
class SLPlan:
type: SLPlanType
expiration: Optional[Arrow]
def set_plan_for_partner_user(partner_user: PartnerUser, plan: SLPlan):
sub = PartnerSubscription.get_by(partner_user_id=partner_user.id)
if plan.type == SLPlanType.Free:
if sub is not None:
LOG.i(
f"Deleting partner_subscription [user_id={partner_user.user_id}] [partner_id={partner_user.partner_id}]"
)
PartnerSubscription.delete(sub.id)
agent.record_custom_event("PlanChange", {"plan": "free"})
else:
if sub is None:
LOG.i(
f"Creating partner_subscription [user_id={partner_user.user_id}] [partner_id={partner_user.partner_id}]"
)
PartnerSubscription.create(
partner_user_id=partner_user.id,
end_at=plan.expiration,
)
agent.record_custom_event("PlanChange", {"plan": "premium", "type": "new"})
else:
if sub.end_at != plan.expiration:
LOG.i(
f"Updating partner_subscription [user_id={partner_user.user_id}] [partner_id={partner_user.partner_id}]"
)
agent.record_custom_event(
"PlanChange", {"plan": "premium", "type": "extension"}
)
sub.end_at = plan.expiration
Session.commit()
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 Partner(Base, ModelMixin):
__tablename__ = "partner"
name = sa.Column(sa.String(128), unique=True, nullable=False)
contact_email = sa.Column(sa.String(128), unique=True, nullable=False)
def find_by_token(token: str) -> Optional[Partner]:
hmaced = PartnerApiToken.hmac_token(token)
res = (
Session.query(Partner, PartnerApiToken)
.filter(
and_(
PartnerApiToken.token == hmaced,
Partner.id == PartnerApiToken.partner_id,
)
)
.first()
)
if res:
partner, partner_api_token = res
return partner
return None
class PartnerUser(Base, ModelMixin):
__tablename__ = "partner_user"
user_id = sa.Column(
sa.ForeignKey("users.id", ondelete="cascade"),
unique=True,
nullable=False,
index=True,
)
partner_id = sa.Column(
sa.ForeignKey("partner.id", ondelete="cascade"), nullable=False, index=True
)
external_user_id = sa.Column(sa.String(128), unique=False, nullable=False)
partner_email = sa.Column(sa.String(255), unique=False, nullable=True)
user = orm.relationship(User, foreign_keys=[user_id])
partner = orm.relationship(Partner, foreign_keys=[partner_id])
__table_args__ = (
sa.UniqueConstraint(
"partner_id", "external_user_id", name="uq_partner_id_external_user_id"
),
)
def set_plan_for_user(user: User, plan: SLPlan, partner: Partner):
partner_user = PartnerUser.get_by(partner_id=partner.id, user_id=user.id)
if partner_user is None:
return
return set_plan_for_partner_user(partner_user, plan) | null |
180,715 | from abc import ABC, abstractmethod
from dataclasses import dataclass
from enum import Enum
from typing import Optional
from arrow import Arrow
from newrelic import agent
from sqlalchemy import or_
from app.db import Session
from app.email_utils import send_welcome_email
from app.utils import sanitize_email, canonicalize_email
from app.errors import (
AccountAlreadyLinkedToAnotherPartnerException,
AccountIsUsingAliasAsEmail,
AccountAlreadyLinkedToAnotherUserException,
)
from app.log import LOG
from app.models import (
PartnerSubscription,
Partner,
PartnerUser,
User,
Alias,
)
from app.utils import random_string
class PartnerLinkRequest:
name: str
email: str
external_user_id: str
plan: SLPlan
from_partner: bool
class LinkResult:
user: User
strategy: str
def set_plan_for_partner_user(partner_user: PartnerUser, plan: SLPlan):
sub = PartnerSubscription.get_by(partner_user_id=partner_user.id)
if plan.type == SLPlanType.Free:
if sub is not None:
LOG.i(
f"Deleting partner_subscription [user_id={partner_user.user_id}] [partner_id={partner_user.partner_id}]"
)
PartnerSubscription.delete(sub.id)
agent.record_custom_event("PlanChange", {"plan": "free"})
else:
if sub is None:
LOG.i(
f"Creating partner_subscription [user_id={partner_user.user_id}] [partner_id={partner_user.partner_id}]"
)
PartnerSubscription.create(
partner_user_id=partner_user.id,
end_at=plan.expiration,
)
agent.record_custom_event("PlanChange", {"plan": "premium", "type": "new"})
else:
if sub.end_at != plan.expiration:
LOG.i(
f"Updating partner_subscription [user_id={partner_user.user_id}] [partner_id={partner_user.partner_id}]"
)
agent.record_custom_event(
"PlanChange", {"plan": "premium", "type": "extension"}
)
sub.end_at = plan.expiration
Session.commit()
def get_login_strategy(
link_request: PartnerLinkRequest, user: Optional[User], partner: Partner
) -> ClientMergeStrategy:
if user is None:
# We couldn't find any SimpleLogin user with the requested e-mail
return NewUserStrategy(link_request, user, partner)
# Check if user is already linked with another partner_user
other_partner_user = PartnerUser.get_by(partner_id=partner.id, user_id=user.id)
if other_partner_user is not None:
return LinkedWithAnotherPartnerUserStrategy(link_request, user, partner)
# There is a SimpleLogin user with the partner_user's e-mail
return ExistingUnlinkedUserStrategy(link_request, user, partner)
def check_alias(email: str) -> bool:
alias = Alias.get_by(email=email)
if alias is not None:
raise AccountIsUsingAliasAsEmail()
def canonicalize_email(email_address: str) -> str:
email_address = sanitize_email(email_address)
parts = email_address.split("@")
if len(parts) != 2:
return ""
domain = parts[1]
if domain not in ("gmail.com", "protonmail.com", "proton.me", "pm.me"):
return email_address
first = parts[0]
try:
plus_idx = first.index("+")
first = first[:plus_idx]
except ValueError:
# No + in the email
pass
first = first.replace(".", "")
return f"{first}@{parts[1]}".lower().strip()
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", "")
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 Partner(Base, ModelMixin):
__tablename__ = "partner"
name = sa.Column(sa.String(128), unique=True, nullable=False)
contact_email = sa.Column(sa.String(128), unique=True, nullable=False)
def find_by_token(token: str) -> Optional[Partner]:
hmaced = PartnerApiToken.hmac_token(token)
res = (
Session.query(Partner, PartnerApiToken)
.filter(
and_(
PartnerApiToken.token == hmaced,
Partner.id == PartnerApiToken.partner_id,
)
)
.first()
)
if res:
partner, partner_api_token = res
return partner
return None
class PartnerUser(Base, ModelMixin):
__tablename__ = "partner_user"
user_id = sa.Column(
sa.ForeignKey("users.id", ondelete="cascade"),
unique=True,
nullable=False,
index=True,
)
partner_id = sa.Column(
sa.ForeignKey("partner.id", ondelete="cascade"), nullable=False, index=True
)
external_user_id = sa.Column(sa.String(128), unique=False, nullable=False)
partner_email = sa.Column(sa.String(255), unique=False, nullable=True)
user = orm.relationship(User, foreign_keys=[user_id])
partner = orm.relationship(Partner, foreign_keys=[partner_id])
__table_args__ = (
sa.UniqueConstraint(
"partner_id", "external_user_id", name="uq_partner_id_external_user_id"
),
)
def process_login_case(
link_request: PartnerLinkRequest, partner: Partner
) -> LinkResult:
# Sanitize email just in case
link_request.email = sanitize_email(link_request.email)
# Try to find a SimpleLogin user registered with that partner user id
partner_user = PartnerUser.get_by(
partner_id=partner.id, external_user_id=link_request.external_user_id
)
if partner_user is None:
canonical_email = canonicalize_email(link_request.email)
# We didn't find any SimpleLogin user registered with that partner user id
# Make sure they aren't using an alias as their link email
check_alias(link_request.email)
check_alias(canonical_email)
# Try to find it using the partner's e-mail address
users = User.filter(
or_(User.email == link_request.email, User.email == canonical_email)
).all()
if len(users) > 1:
user = [user for user in users if user.email == canonical_email][0]
elif len(users) == 1:
user = users[0]
else:
user = None
return get_login_strategy(link_request, user, partner).process()
else:
# We found the SL user registered with that partner user id
# We're done
set_plan_for_partner_user(partner_user, link_request.plan)
# It's the same user. No need to do anything
return LinkResult(
user=partner_user.user,
strategy="Link",
) | null |
180,716 | from abc import ABC, abstractmethod
from dataclasses import dataclass
from enum import Enum
from typing import Optional
from arrow import Arrow
from newrelic import agent
from sqlalchemy import or_
from app.db import Session
from app.email_utils import send_welcome_email
from app.utils import sanitize_email, canonicalize_email
from app.errors import (
AccountAlreadyLinkedToAnotherPartnerException,
AccountIsUsingAliasAsEmail,
AccountAlreadyLinkedToAnotherUserException,
)
from app.log import LOG
from app.models import (
PartnerSubscription,
Partner,
PartnerUser,
User,
Alias,
)
from app.utils import random_string
class PartnerLinkRequest:
name: str
email: str
external_user_id: str
plan: SLPlan
from_partner: bool
class LinkResult:
user: User
strategy: str
def set_plan_for_partner_user(partner_user: PartnerUser, plan: SLPlan):
sub = PartnerSubscription.get_by(partner_user_id=partner_user.id)
if plan.type == SLPlanType.Free:
if sub is not None:
LOG.i(
f"Deleting partner_subscription [user_id={partner_user.user_id}] [partner_id={partner_user.partner_id}]"
)
PartnerSubscription.delete(sub.id)
agent.record_custom_event("PlanChange", {"plan": "free"})
else:
if sub is None:
LOG.i(
f"Creating partner_subscription [user_id={partner_user.user_id}] [partner_id={partner_user.partner_id}]"
)
PartnerSubscription.create(
partner_user_id=partner_user.id,
end_at=plan.expiration,
)
agent.record_custom_event("PlanChange", {"plan": "premium", "type": "new"})
else:
if sub.end_at != plan.expiration:
LOG.i(
f"Updating partner_subscription [user_id={partner_user.user_id}] [partner_id={partner_user.partner_id}]"
)
agent.record_custom_event(
"PlanChange", {"plan": "premium", "type": "extension"}
)
sub.end_at = plan.expiration
Session.commit()
def link_user(
link_request: PartnerLinkRequest, current_user: User, partner: Partner
) -> LinkResult:
# Sanitize email just in case
link_request.email = sanitize_email(link_request.email)
# If it was scheduled to be deleted. Unschedule it.
current_user.delete_on = None
partner_user = ensure_partner_user_exists_for_user(
link_request, current_user, partner
)
set_plan_for_partner_user(partner_user, link_request.plan)
agent.record_custom_event("AccountLinked", {"partner": partner.name})
Session.commit()
return LinkResult(
user=current_user,
strategy="Link",
)
def switch_already_linked_user(
link_request: PartnerLinkRequest, partner_user: PartnerUser, current_user: User
):
# Find if the user has another link and unlink it
other_partner_user = PartnerUser.get_by(
user_id=current_user.id,
partner_id=partner_user.partner_id,
)
if other_partner_user is not None:
LOG.i(
f"Deleting previous partner_user:{other_partner_user.id} from user:{current_user.id}"
)
PartnerUser.delete(other_partner_user.id)
LOG.i(f"Linking partner_user:{partner_user.id} to user:{current_user.id}")
# Link this partner_user to the current user
partner_user.user_id = current_user.id
# Set plan
set_plan_for_partner_user(partner_user, link_request.plan)
Session.commit()
return LinkResult(
user=current_user,
strategy="Link",
)
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", "")
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 Partner(Base, ModelMixin):
__tablename__ = "partner"
name = sa.Column(sa.String(128), unique=True, nullable=False)
contact_email = sa.Column(sa.String(128), unique=True, nullable=False)
def find_by_token(token: str) -> Optional[Partner]:
hmaced = PartnerApiToken.hmac_token(token)
res = (
Session.query(Partner, PartnerApiToken)
.filter(
and_(
PartnerApiToken.token == hmaced,
Partner.id == PartnerApiToken.partner_id,
)
)
.first()
)
if res:
partner, partner_api_token = res
return partner
return None
class PartnerUser(Base, ModelMixin):
__tablename__ = "partner_user"
user_id = sa.Column(
sa.ForeignKey("users.id", ondelete="cascade"),
unique=True,
nullable=False,
index=True,
)
partner_id = sa.Column(
sa.ForeignKey("partner.id", ondelete="cascade"), nullable=False, index=True
)
external_user_id = sa.Column(sa.String(128), unique=False, nullable=False)
partner_email = sa.Column(sa.String(255), unique=False, nullable=True)
user = orm.relationship(User, foreign_keys=[user_id])
partner = orm.relationship(Partner, foreign_keys=[partner_id])
__table_args__ = (
sa.UniqueConstraint(
"partner_id", "external_user_id", name="uq_partner_id_external_user_id"
),
)
def process_link_case(
link_request: PartnerLinkRequest,
current_user: User,
partner: Partner,
) -> LinkResult:
# Sanitize email just in case
link_request.email = sanitize_email(link_request.email)
# Try to find a SimpleLogin user linked with this Partner account
partner_user = PartnerUser.get_by(
partner_id=partner.id, external_user_id=link_request.external_user_id
)
if partner_user is None:
# There is no SL user linked with the partner. Proceed with linking
return link_user(link_request, current_user, partner)
# There is a SL user registered with the partner. Check if is the current one
if partner_user.user_id == current_user.id:
# Update plan
set_plan_for_partner_user(partner_user, link_request.plan)
# It's the same user. No need to do anything
return LinkResult(
user=current_user,
strategy="Link",
)
else:
return switch_already_linked_user(link_request, partner_user, current_user) | null |
180,717 | from typing import Dict
from urllib.parse import urlparse
from flask import request, render_template, redirect, flash, url_for
from flask_login import current_user
from app.alias_suffix import get_alias_suffixes, check_suffix_signature
from app.alias_utils import check_alias_prefix
from app.config import EMAIL_DOMAIN
from app.db import Session
from app.jose_utils import make_id_token
from app.log import LOG
from app.models import (
Client,
AuthorizationCode,
ClientUser,
Alias,
RedirectUri,
OauthToken,
DeletedAlias,
DomainDeletedAlias,
)
from app.oauth.base import oauth_bp
from app.oauth_models import (
get_response_types,
ResponseType,
Scope,
SUPPORTED_OPENID_FLOWS,
SUPPORTED_OPENID_FLOWS_STR,
response_types_to_str,
)
from app.utils import random_string, encode_url
def get_fragment(response_mode, response_types):
# should all params appended the url using fragment (#) or query
fragment = False
if response_mode and response_mode == "fragment":
fragment = True
# if response_types contain "token" => implicit flow => should use fragment
# except if client sets explicitly response_mode
if not response_mode:
if ResponseType.TOKEN in response_types:
fragment = True
return fragment
def construct_redirect_args(
client, client_user, nonce, redirect_uri, response_types, scope, state
) -> dict:
redirect_args = {}
if state:
redirect_args["state"] = state
else:
LOG.w("more security reason, state should be added. client %s", client)
if scope:
redirect_args["scope"] = scope
auth_code = None
if ResponseType.CODE in response_types:
auth_code = AuthorizationCode.create(
client_id=client.id,
user_id=current_user.id,
code=random_string(),
scope=scope,
redirect_uri=redirect_uri,
response_type=response_types_to_str(response_types),
nonce=nonce,
)
redirect_args["code"] = auth_code.code
oauth_token = None
if ResponseType.TOKEN in response_types:
# create access-token
oauth_token = OauthToken.create(
client_id=client.id,
user_id=current_user.id,
scope=scope,
redirect_uri=redirect_uri,
access_token=generate_access_token(),
response_type=response_types_to_str(response_types),
)
Session.add(oauth_token)
redirect_args["access_token"] = oauth_token.access_token
if ResponseType.ID_TOKEN in response_types:
redirect_args["id_token"] = make_id_token(
client_user,
nonce,
oauth_token.access_token if oauth_token else None,
auth_code.code if auth_code else None,
)
Session.commit()
return redirect_args
def construct_url(url, args: Dict[str, str], fragment: bool = False):
for i, (k, v) in enumerate(args.items()):
# make sure to escape v
v = encode_url(v)
if i == 0:
if fragment:
url += f"#{k}={v}"
else:
url += f"?{k}={v}"
else:
url += f"&{k}={v}"
return url
def get_host_name_and_scheme(url: str) -> (str, str):
"""http://localhost:7777?a=b -> (localhost, http)"""
url_comp = urlparse(url)
return url_comp.hostname, url_comp.scheme
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 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 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
EMAIL_DOMAIN = os.environ["EMAIL_DOMAIN"].lower()
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
LOG = _get_logger("SL")
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 RedirectUri(Base, ModelMixin):
"""Valid redirect uris for a client"""
__tablename__ = "redirect_uri"
client_id = sa.Column(sa.ForeignKey(Client.id, ondelete="cascade"), nullable=False)
uri = sa.Column(sa.String(1024), nullable=False)
client = orm.relationship(Client, backref="redirect_uris")
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 ClientUser(Base, ModelMixin):
__tablename__ = "client_user"
__table_args__ = (
sa.UniqueConstraint("user_id", "client_id", name="uq_client_user"),
)
user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False)
client_id = sa.Column(sa.ForeignKey(Client.id, ondelete="cascade"), nullable=False)
# Null means client has access to user original email
alias_id = sa.Column(
sa.ForeignKey(Alias.id, ondelete="cascade"), nullable=True, index=True
)
# user can decide to send to client another name
name = sa.Column(
sa.String(128), nullable=True, default=None, server_default=text("NULL")
)
# user can decide to send to client a default avatar
default_avatar = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
alias = orm.relationship(Alias, backref="client_users")
user = orm.relationship(User)
client = orm.relationship(Client)
def get_email(self):
return self.alias.email if self.alias_id else self.user.email
def get_user_name(self):
if self.name:
return self.name
else:
return self.user.name
def get_user_info(self) -> dict:
"""return user info according to client scope
Return dict with key being scope name. For now all the fields are the same for all clients:
{
"client": "Demo",
"email": "test-avk5l@mail-tester.com",
"email_verified": true,
"id": 1,
"name": "Son GM",
"avatar_url": "http://s3..."
}
"""
res = {
"id": self.id,
"client": self.client.name,
"email_verified": True,
"sub": str(self.id),
}
for scope in self.client.get_scopes():
if scope == Scope.NAME:
if self.name:
res[Scope.NAME.value] = self.name or ""
else:
res[Scope.NAME.value] = self.user.name or ""
elif scope == Scope.AVATAR_URL:
if self.user.profile_picture_id:
if self.default_avatar:
res[Scope.AVATAR_URL.value] = (
config.URL + "/static/default-avatar.png"
)
else:
res[Scope.AVATAR_URL.value] = self.user.profile_picture.get_url(
config.AVATAR_URL_EXPIRATION
)
else:
res[Scope.AVATAR_URL.value] = None
elif scope == Scope.EMAIL:
# Use generated email
if self.alias_id:
LOG.d(
"Use gen email for user %s, client %s", self.user, self.client
)
res[Scope.EMAIL.value] = self.alias.email
# Use user original email
else:
res[Scope.EMAIL.value] = self.user.email
return res
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 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 Scope(enum.Enum):
EMAIL = "email"
NAME = "name"
OPENID = "openid"
AVATAR_URL = "avatar_url"
class ResponseType(enum.Enum):
CODE = "code"
TOKEN = "token"
ID_TOKEN = "id_token"
SUPPORTED_OPENID_FLOWS = [
{ResponseType.CODE},
{ResponseType.TOKEN},
{ResponseType.ID_TOKEN},
{ResponseType.ID_TOKEN, ResponseType.TOKEN},
{ResponseType.ID_TOKEN, ResponseType.CODE},
]
SUPPORTED_OPENID_FLOWS_STR = "code|token|id_token|id_token,token|id_token,code"
def get_response_types(request: flask.Request) -> Set[ResponseType]:
response_type_strs = _split_arg(request.args.getlist("response_type"))
return set([ResponseType(r) for r in response_type_strs if r])
The provided code snippet includes necessary dependencies for implementing the `authorize` function. Write a Python function `def authorize()` to solve the following problem:
Redirected from client when user clicks on "Login with Server". This is a GET request with the following field in url - client_id - (optional) state - response_type: must be code
Here is the function:
def authorize():
"""
Redirected from client when user clicks on "Login with Server".
This is a GET request with the following field in url
- client_id
- (optional) state
- response_type: must be code
"""
oauth_client_id = request.args.get("client_id")
state = request.args.get("state")
scope = request.args.get("scope")
redirect_uri = request.args.get("redirect_uri")
response_mode = request.args.get("response_mode")
nonce = request.args.get("nonce")
try:
response_types: [ResponseType] = get_response_types(request)
except ValueError:
return (
"response_type must be code, token, id_token or certain combination of these."
" Please see /.well-known/openid-configuration to see what response_type are supported ",
400,
)
if set(response_types) not in SUPPORTED_OPENID_FLOWS:
return (
f"SimpleLogin only support the following OIDC flows: {SUPPORTED_OPENID_FLOWS_STR}",
400,
)
if not redirect_uri:
LOG.d("no redirect uri")
return "redirect_uri must be set", 400
client = Client.get_by(oauth_client_id=oauth_client_id)
if not client:
return redirect(url_for("auth.login"))
# allow localhost by default
# allow any redirect_uri if the app isn't approved
hostname, scheme = get_host_name_and_scheme(redirect_uri)
if hostname != "localhost" and hostname != "127.0.0.1":
# support custom scheme for mobile app
if scheme == "http":
flash("The external client must use HTTPS", "error")
return redirect(url_for("dashboard.index"))
# check if redirect_uri is valid
if not RedirectUri.get_by(client_id=client.id, uri=redirect_uri):
flash("The external client is using an invalid URL", "error")
return redirect(url_for("dashboard.index"))
# redirect from client website
if request.method == "GET":
if current_user.is_authenticated:
suggested_email, other_emails, email_suffix = None, [], None
suggested_name, other_names = None, []
# user has already allowed this client
client_user: ClientUser = ClientUser.get_by(
client_id=client.id, user_id=current_user.id
)
user_info = {}
if client_user:
LOG.d("user %s has already allowed client %s", current_user, client)
user_info = client_user.get_user_info()
# redirect user to the client page
redirect_args = construct_redirect_args(
client,
client_user,
nonce,
redirect_uri,
response_types,
scope,
state,
)
fragment = get_fragment(response_mode, response_types)
# construct redirect_uri with redirect_args
return redirect(construct_url(redirect_uri, redirect_args, fragment))
else:
suggested_email, other_emails = current_user.suggested_emails(
client.name
)
suggested_name, other_names = current_user.suggested_names()
user_custom_domains = [
cd.domain for cd in current_user.verified_custom_domains()
]
suffixes = get_alias_suffixes(current_user)
return render_template(
"oauth/authorize.html",
Scope=Scope,
EMAIL_DOMAIN=EMAIL_DOMAIN,
**locals(),
)
else:
# after user logs in, redirect user back to this page
return render_template(
"oauth/authorize_nonlogin_user.html",
client=client,
next=request.url,
Scope=Scope,
)
else: # POST - user allows or denies
if not current_user.is_authenticated or not current_user.is_active():
LOG.i(
"Attempt to validate a OAUth allow request by an unauthenticated user"
)
return redirect(url_for("auth.login", next=request.url))
if request.form.get("button") == "deny":
LOG.d("User %s denies Client %s", current_user, client)
final_redirect_uri = f"{redirect_uri}?error=deny&state={state}"
return redirect(final_redirect_uri)
LOG.d("User %s allows Client %s", current_user, client)
client_user = ClientUser.get_by(client_id=client.id, user_id=current_user.id)
# user has already allowed this client, user cannot change information
if client_user:
LOG.d("user %s has already allowed client %s", current_user, client)
else:
alias_prefix = request.form.get("prefix")
signed_suffix = request.form.get("suffix")
alias = None
# user creates a new alias, not using suggested alias
if alias_prefix:
# should never happen as this is checked on the front-end
if not current_user.can_create_new_alias():
raise Exception(f"User {current_user} cannot create custom email")
alias_prefix = alias_prefix.strip().lower().replace(" ", "")
if not check_alias_prefix(alias_prefix):
flash(
"Only lowercase letters, numbers, dashes (-), dots (.) and underscores (_) "
"are currently supported for alias prefix. Cannot be more than 40 letters",
"error",
)
return redirect(request.url)
# 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", current_user)
flash("Alias creation time is expired, please retry", "warning")
return redirect(request.url)
except Exception:
LOG.w("Alias suffix is tampered, user %s", current_user)
flash("Unknown error, refresh the page", "error")
return redirect(request.url)
user_custom_domains = [
cd.domain for cd in current_user.verified_custom_domains()
]
from app.alias_suffix import verify_prefix_suffix
if verify_prefix_suffix(current_user, alias_prefix, alias_suffix):
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.e("alias %s already used, very rare!", full_alias)
flash(f"Alias {full_alias} already used", "error")
return redirect(request.url)
else:
alias = Alias.create(
user_id=current_user.id,
email=full_alias,
mailbox_id=current_user.default_mailbox_id,
)
Session.flush()
flash(f"Alias {full_alias} has been created", "success")
# only happen if the request has been "hacked"
else:
flash("something went wrong", "warning")
return redirect(request.url)
# User chooses one of the suggestions
else:
chosen_email = request.form.get("suggested-email")
# todo: add some checks on chosen_email
if chosen_email != current_user.email:
alias = Alias.get_by(email=chosen_email)
if not alias:
alias = Alias.create(
email=chosen_email,
user_id=current_user.id,
mailbox_id=current_user.default_mailbox_id,
)
Session.flush()
suggested_name = request.form.get("suggested-name")
custom_name = request.form.get("custom-name")
use_default_avatar = request.form.get("avatar-choice") == "default"
client_user = ClientUser.create(
client_id=client.id, user_id=current_user.id
)
if alias:
client_user.alias_id = alias.id
if custom_name:
client_user.name = custom_name
elif suggested_name != current_user.name:
client_user.name = suggested_name
if use_default_avatar:
# use default avatar
LOG.d("use default avatar for user %s client %s", current_user, client)
client_user.default_avatar = True
Session.flush()
LOG.d("create client-user for client %s, user %s", client, current_user)
redirect_args = construct_redirect_args(
client, client_user, nonce, redirect_uri, response_types, scope, state
)
fragment = get_fragment(response_mode, response_types)
# construct redirect_uri with redirect_args
return redirect(construct_url(redirect_uri, redirect_args, fragment)) | Redirected from client when user clicks on "Login with Server". This is a GET request with the following field in url - client_id - (optional) state - response_type: must be code |
180,718 | from flask import request, jsonify
from flask_cors import cross_origin
from app.db import Session
from app.log import LOG
from app.models import OauthToken, ClientUser
from app.oauth.base import oauth_bp
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
LOG = _get_logger("SL")
class OauthToken(Base, ModelMixin):
__tablename__ = "oauth_token"
access_token = sa.Column(sa.String(128), unique=True)
client_id = sa.Column(sa.ForeignKey(Client.id, ondelete="cascade"), nullable=False)
user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False)
scope = sa.Column(sa.String(128))
redirect_uri = sa.Column(sa.String(1024))
# what is the input response_type, e.g. "token", "token,id_token", ...
response_type = sa.Column(sa.String(128))
user = orm.relationship(User)
client = orm.relationship(Client)
expired = sa.Column(ArrowType, nullable=False, default=_expiration_1h)
def is_expired(self):
return self.expired < arrow.now()
class ClientUser(Base, ModelMixin):
__tablename__ = "client_user"
__table_args__ = (
sa.UniqueConstraint("user_id", "client_id", name="uq_client_user"),
)
user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False)
client_id = sa.Column(sa.ForeignKey(Client.id, ondelete="cascade"), nullable=False)
# Null means client has access to user original email
alias_id = sa.Column(
sa.ForeignKey(Alias.id, ondelete="cascade"), nullable=True, index=True
)
# user can decide to send to client another name
name = sa.Column(
sa.String(128), nullable=True, default=None, server_default=text("NULL")
)
# user can decide to send to client a default avatar
default_avatar = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
alias = orm.relationship(Alias, backref="client_users")
user = orm.relationship(User)
client = orm.relationship(Client)
def get_email(self):
return self.alias.email if self.alias_id else self.user.email
def get_user_name(self):
if self.name:
return self.name
else:
return self.user.name
def get_user_info(self) -> dict:
"""return user info according to client scope
Return dict with key being scope name. For now all the fields are the same for all clients:
{
"client": "Demo",
"email": "test-avk5l@mail-tester.com",
"email_verified": true,
"id": 1,
"name": "Son GM",
"avatar_url": "http://s3..."
}
"""
res = {
"id": self.id,
"client": self.client.name,
"email_verified": True,
"sub": str(self.id),
}
for scope in self.client.get_scopes():
if scope == Scope.NAME:
if self.name:
res[Scope.NAME.value] = self.name or ""
else:
res[Scope.NAME.value] = self.user.name or ""
elif scope == Scope.AVATAR_URL:
if self.user.profile_picture_id:
if self.default_avatar:
res[Scope.AVATAR_URL.value] = (
config.URL + "/static/default-avatar.png"
)
else:
res[Scope.AVATAR_URL.value] = self.user.profile_picture.get_url(
config.AVATAR_URL_EXPIRATION
)
else:
res[Scope.AVATAR_URL.value] = None
elif scope == Scope.EMAIL:
# Use generated email
if self.alias_id:
LOG.d(
"Use gen email for user %s, client %s", self.user, self.client
)
res[Scope.EMAIL.value] = self.alias.email
# Use user original email
else:
res[Scope.EMAIL.value] = self.user.email
return res
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:
Call by client to get user information Usually bearer token is used.
Here is the function:
def user_info():
"""
Call by client to get user information
Usually bearer token is used.
"""
if "AUTHORIZATION" in request.headers:
access_token = request.headers["AUTHORIZATION"].replace("Bearer ", "")
else:
access_token = request.args.get("access_token")
oauth_token: OauthToken = OauthToken.get_by(access_token=access_token)
if not oauth_token:
return jsonify(error="Invalid access token"), 400
elif oauth_token.is_expired():
LOG.d("delete oauth token %s", oauth_token)
OauthToken.delete(oauth_token.id)
Session.commit()
return jsonify(error="Expired access token"), 400
client_user = ClientUser.get_or_create(
client_id=oauth_token.client_id, user_id=oauth_token.user_id
)
return jsonify(client_user.get_user_info()) | Call by client to get user information Usually bearer token is used. |
180,719 | from flask import request, jsonify
from flask_cors import cross_origin
from app.db import Session
from app.jose_utils import make_id_token
from app.log import LOG
from app.models import Client, AuthorizationCode, OauthToken, ClientUser
from app.oauth.base import oauth_bp
from app.oauth.views.authorize import generate_access_token
from app.oauth_models import Scope, get_response_types_from_str, ResponseType
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
def make_id_token(
client_user: ClientUser,
nonce: Optional[str] = None,
access_token: Optional[str] = None,
code: Optional[str] = None,
):
"""Make id_token for OpenID Connect
According to RFC 7519, these claims are mandatory:
- iss
- sub
- aud
- exp
- iat
"""
claims = {
"iss": URL,
"sub": str(client_user.id),
"aud": client_user.client.oauth_client_id,
"exp": arrow.now().shift(hours=1).timestamp,
"iat": arrow.now().timestamp,
"auth_time": arrow.now().timestamp,
}
if nonce:
claims["nonce"] = nonce
if access_token:
claims["at_hash"] = id_token_hash(access_token)
if code:
claims["c_hash"] = id_token_hash(code)
claims = {**claims, **client_user.get_user_info()}
jwt_token = jwt.JWT(
header={"alg": "RS256", "kid": _key._public_params()["kid"]}, claims=claims
)
jwt_token.make_signed_token(_key)
return jwt_token.serialize()
LOG = _get_logger("SL")
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 AuthorizationCode(Base, ModelMixin):
__tablename__ = "authorization_code"
code = sa.Column(sa.String(128), unique=True, nullable=False)
client_id = sa.Column(sa.ForeignKey(Client.id, ondelete="cascade"), nullable=False)
user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False)
scope = sa.Column(sa.String(128))
redirect_uri = sa.Column(sa.String(1024))
# what is the input response_type, e.g. "code", "code,id_token", ...
response_type = sa.Column(sa.String(128))
nonce = sa.Column(sa.Text, nullable=True, default=None, server_default=text("NULL"))
user = orm.relationship(User, lazy=False)
client = orm.relationship(Client, lazy=False)
expired = sa.Column(ArrowType, nullable=False, default=_expiration_5m)
def is_expired(self):
return self.expired < arrow.now()
class OauthToken(Base, ModelMixin):
__tablename__ = "oauth_token"
access_token = sa.Column(sa.String(128), unique=True)
client_id = sa.Column(sa.ForeignKey(Client.id, ondelete="cascade"), nullable=False)
user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False)
scope = sa.Column(sa.String(128))
redirect_uri = sa.Column(sa.String(1024))
# what is the input response_type, e.g. "token", "token,id_token", ...
response_type = sa.Column(sa.String(128))
user = orm.relationship(User)
client = orm.relationship(Client)
expired = sa.Column(ArrowType, nullable=False, default=_expiration_1h)
def is_expired(self):
return self.expired < arrow.now()
class ClientUser(Base, ModelMixin):
__tablename__ = "client_user"
__table_args__ = (
sa.UniqueConstraint("user_id", "client_id", name="uq_client_user"),
)
user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False)
client_id = sa.Column(sa.ForeignKey(Client.id, ondelete="cascade"), nullable=False)
# Null means client has access to user original email
alias_id = sa.Column(
sa.ForeignKey(Alias.id, ondelete="cascade"), nullable=True, index=True
)
# user can decide to send to client another name
name = sa.Column(
sa.String(128), nullable=True, default=None, server_default=text("NULL")
)
# user can decide to send to client a default avatar
default_avatar = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
alias = orm.relationship(Alias, backref="client_users")
user = orm.relationship(User)
client = orm.relationship(Client)
def get_email(self):
return self.alias.email if self.alias_id else self.user.email
def get_user_name(self):
if self.name:
return self.name
else:
return self.user.name
def get_user_info(self) -> dict:
"""return user info according to client scope
Return dict with key being scope name. For now all the fields are the same for all clients:
{
"client": "Demo",
"email": "test-avk5l@mail-tester.com",
"email_verified": true,
"id": 1,
"name": "Son GM",
"avatar_url": "http://s3..."
}
"""
res = {
"id": self.id,
"client": self.client.name,
"email_verified": True,
"sub": str(self.id),
}
for scope in self.client.get_scopes():
if scope == Scope.NAME:
if self.name:
res[Scope.NAME.value] = self.name or ""
else:
res[Scope.NAME.value] = self.user.name or ""
elif scope == Scope.AVATAR_URL:
if self.user.profile_picture_id:
if self.default_avatar:
res[Scope.AVATAR_URL.value] = (
config.URL + "/static/default-avatar.png"
)
else:
res[Scope.AVATAR_URL.value] = self.user.profile_picture.get_url(
config.AVATAR_URL_EXPIRATION
)
else:
res[Scope.AVATAR_URL.value] = None
elif scope == Scope.EMAIL:
# Use generated email
if self.alias_id:
LOG.d(
"Use gen email for user %s, client %s", self.user, self.client
)
res[Scope.EMAIL.value] = self.alias.email
# Use user original email
else:
res[Scope.EMAIL.value] = self.user.email
return res
def generate_access_token() -> str:
"""generate an access-token that does not exist before"""
access_token = random_string(40)
if not OauthToken.get_by(access_token=access_token):
return access_token
# Rerun the function
LOG.w("access token already exists, generate a new one")
return generate_access_token()
class Scope(enum.Enum):
EMAIL = "email"
NAME = "name"
OPENID = "openid"
AVATAR_URL = "avatar_url"
class ResponseType(enum.Enum):
CODE = "code"
TOKEN = "token"
ID_TOKEN = "id_token"
def get_response_types_from_str(response_type_str) -> Set[ResponseType]:
response_type_strs = _split_arg(response_type_str)
return set([ResponseType(r) for r in response_type_strs if r])
The provided code snippet includes necessary dependencies for implementing the `token` function. Write a Python function `def token()` to solve the following problem:
Calls by client to exchange the access token given the authorization code. The client authentications using Basic Authentication. The form contains the following data: - grant_type: must be "authorization_code" - code: the code obtained in previous step
Here is the function:
def token():
"""
Calls by client to exchange the access token given the authorization code.
The client authentications using Basic Authentication.
The form contains the following data:
- grant_type: must be "authorization_code"
- code: the code obtained in previous step
"""
# Basic authentication
oauth_client_id = (
request.authorization and request.authorization.username
) or request.form.get("client_id")
oauth_client_secret = (
request.authorization and request.authorization.password
) or request.form.get("client_secret")
client = Client.filter_by(
oauth_client_id=oauth_client_id, oauth_client_secret=oauth_client_secret
).first()
if not client:
return jsonify(error="wrong client-id or client-secret"), 400
# Get code from form data
grant_type = request.form.get("grant_type")
code = request.form.get("code")
# sanity check
if grant_type != "authorization_code":
return jsonify(error="grant_type must be authorization_code"), 400
auth_code: AuthorizationCode = AuthorizationCode.filter_by(code=code).first()
if not auth_code:
return jsonify(error=f"no such authorization code {code}"), 400
elif auth_code.is_expired():
AuthorizationCode.delete(auth_code.id)
Session.commit()
LOG.d("delete expired authorization code:%s", auth_code)
return jsonify(error=f"{code} already expired"), 400
if auth_code.client_id != client.id:
return jsonify(error="are you sure this code belongs to you?"), 400
LOG.d("Create Oauth token for user %s, client %s", auth_code.user, auth_code.client)
# Create token
oauth_token = OauthToken.create(
client_id=auth_code.client_id,
user_id=auth_code.user_id,
scope=auth_code.scope,
redirect_uri=auth_code.redirect_uri,
access_token=generate_access_token(),
response_type=auth_code.response_type,
)
client_user: ClientUser = ClientUser.get_by(
client_id=auth_code.client_id, user_id=auth_code.user_id
)
user_data = client_user.get_user_info()
res = {
"access_token": oauth_token.access_token,
"token_type": "Bearer",
"expires_in": 3600,
"scope": auth_code.scope,
"user": user_data, # todo: remove this
}
if oauth_token.scope and Scope.OPENID.value in oauth_token.scope:
res["id_token"] = make_id_token(client_user)
# Also return id_token if the initial flow is "code,id_token"
# cf https://medium.com/@darutk/diagrams-of-all-the-openid-connect-flows-6968e3990660
response_types = get_response_types_from_str(auth_code.response_type)
if ResponseType.ID_TOKEN in response_types or auth_code.scope == "openid":
res["id_token"] = make_id_token(client_user, nonce=auth_code.nonce)
# Auth code can be used only once
AuthorizationCode.delete(auth_code.id)
Session.commit()
return jsonify(res) | Calls by client to exchange the access token given the authorization code. The client authentications using Basic Authentication. The form contains the following data: - grant_type: must be "authorization_code" - code: the code obtained in previous step |
180,720 | from flask import make_response, redirect, url_for, flash
from flask_login import current_user
from .base import internal_bp
def set_enable_proton_cookie():
if current_user.is_authenticated:
redirect_url = url_for("dashboard.setting", _anchor="connect-with-proton")
else:
redirect_url = url_for("auth.login")
response = make_response(redirect(redirect_url))
flash("You can now connect your Proton and your SimpleLogin account", "success")
return response | null |
180,721 | from flask import session, redirect, url_for, flash
from app.internal.base import internal_bp
def exit_sudo_mode():
session["sudo_time"] = 0
flash("Exited sudo mode", "info")
return redirect(url_for("dashboard.index")) | null |
180,722 | import logging
import sys
import time
import coloredlogs
from app.config import (
COLOR_LOG,
)
_log_format = (
"%(asctime)s - %(name)s - %(levelname)s - %(process)d - "
'"%(pathname)s:%(lineno)d" - %(funcName)s() - %(message_id)s - %(message)s'
)
class EmailHandlerFilter(logging.Filter):
"""automatically add message-id to keep track of an email processing"""
def filter(self, record):
message_id = self.get_message_id()
record.message_id = message_id if message_id else ""
return True
def get_message_id(self):
return _MESSAGE_ID
def _get_console_handler():
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(_log_formatter)
console_handler.formatter.converter = time.gmtime
return console_handler
logging.Logger.d = logging.Logger.debug
logging.Logger.i = logging.Logger.info
logging.Logger.w = logging.Logger.warning
logging.Logger.e = logging.Logger.exception
COLOR_LOG = "COLOR_LOG" in os.environ
def _get_logger(name) -> logging.Logger:
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
# leave the handlers level at NOTSET so the level checking is only handled by the logger
logger.addHandler(_get_console_handler())
logger.addFilter(EmailHandlerFilter())
# no propagation to avoid propagating to root logger
logger.propagate = False
if COLOR_LOG:
coloredlogs.install(level="DEBUG", logger=logger, fmt=_log_format)
return logger | null |
180,723 | import json
import secrets
import uuid
import webauthn
from flask import render_template, flash, redirect, url_for, session
from flask_login import login_required, current_user
from flask_wtf import FlaskForm
from wtforms import StringField, HiddenField, validators
from app.config import RP_ID, URL
from app.dashboard.base import dashboard_bp
from app.dashboard.views.enter_sudo import sudo_required
from app.db import Session
from app.log import LOG
from app.models import Fido, RecoveryCode
class FidoTokenForm(FlaskForm):
URL = os.environ["URL"]
RP_ID = urlparse(URL).hostname
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
LOG = _get_logger("SL")
class Fido(Base, ModelMixin):
class RecoveryCode(Base, ModelMixin):
def _hash_code(cls, code: str) -> str:
def generate(cls, user):
def find_by_user_code(cls, user: User, code: str):
def empty(cls, user):
def fido_setup():
if current_user.fido_uuid is not None:
fidos = Fido.filter_by(uuid=current_user.fido_uuid).all()
else:
fidos = []
fido_token_form = FidoTokenForm()
# Handling POST requests
if fido_token_form.validate_on_submit():
try:
sk_assertion = json.loads(fido_token_form.sk_assertion.data)
except Exception:
flash("Key registration failed. Error: Invalid Payload", "warning")
return redirect(url_for("dashboard.index"))
fido_uuid = session["fido_uuid"]
challenge = session["fido_challenge"]
fido_reg_response = webauthn.WebAuthnRegistrationResponse(
RP_ID,
URL,
sk_assertion,
challenge,
trusted_attestation_cert_required=False,
none_attestation_permitted=True,
)
try:
fido_credential = fido_reg_response.verify()
except Exception as e:
LOG.w(f"An error occurred in WebAuthn registration process: {e}")
flash("Key registration failed.", "warning")
return redirect(url_for("dashboard.index"))
if current_user.fido_uuid is None:
current_user.fido_uuid = fido_uuid
Session.flush()
Fido.create(
credential_id=str(fido_credential.credential_id, "utf-8"),
uuid=fido_uuid,
public_key=str(fido_credential.public_key, "utf-8"),
sign_count=fido_credential.sign_count,
name=fido_token_form.key_name.data,
user_id=current_user.id,
)
Session.commit()
LOG.d(
f"credential_id={str(fido_credential.credential_id, 'utf-8')} added for {fido_uuid}"
)
flash("Security key has been activated", "success")
recovery_codes = RecoveryCode.generate(current_user)
return render_template(
"dashboard/recovery_code.html", recovery_codes=recovery_codes
)
# Prepare information for key registration process
fido_uuid = (
str(uuid.uuid4()) if current_user.fido_uuid is None else current_user.fido_uuid
)
challenge = secrets.token_urlsafe(32)
credential_create_options = webauthn.WebAuthnMakeCredentialOptions(
challenge,
"SimpleLogin",
RP_ID,
fido_uuid,
current_user.email,
current_user.name if current_user.name else current_user.email,
False,
attestation="none",
user_verification="discouraged",
)
# Don't think this one should be used, but it's not configurable by arguments
# https://www.w3.org/TR/webauthn/#sctn-location-extension
registration_dict = credential_create_options.registration_dict
del registration_dict["extensions"]["webauthn.loc"]
# Prevent user from adding duplicated keys
for fido in fidos:
registration_dict["excludeCredentials"].append(
{
"type": "public-key",
"id": fido.credential_id,
"transports": ["usb", "nfc", "ble", "internal"],
}
)
session["fido_uuid"] = fido_uuid
session["fido_challenge"] = challenge.rstrip("=")
return render_template(
"dashboard/fido_setup.html",
fido_token_form=fido_token_form,
credential_create_options=registration_dict,
) | null |
180,724 | from functools import wraps
from time import time
from flask import render_template, flash, redirect, url_for, session, request
from flask_login import login_required, current_user
from flask_wtf import FlaskForm
from wtforms import PasswordField, validators
from app.config import CONNECT_WITH_PROTON, OIDC_CLIENT_ID, CONNECT_WITH_OIDC_ICON
from app.dashboard.base import dashboard_bp
from app.extensions import limiter
from app.log import LOG
from app.models import PartnerUser, SocialAuth
from app.proton.utils import get_proton_partner
from app.utils import sanitize_next_url
class LoginForm(FlaskForm):
password = PasswordField("Password", validators=[validators.DataRequired()])
CONNECT_WITH_OIDC_ICON = os.environ.get("CONNECT_WITH_OIDC_ICON")
OIDC_CLIENT_ID = os.environ.get("OIDC_CLIENT_ID")
CONNECT_WITH_PROTON = "CONNECT_WITH_PROTON" in os.environ
LOG = _get_logger("SL")
class SocialAuth(Base, ModelMixin):
"""Store how user authenticates with social login"""
__tablename__ = "social_auth"
user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False)
# name of the social login used, could be facebook, google or github
social = sa.Column(sa.String(128), nullable=False)
__table_args__ = (sa.UniqueConstraint("user_id", "social", name="uq_social_auth"),)
class PartnerUser(Base, ModelMixin):
__tablename__ = "partner_user"
user_id = sa.Column(
sa.ForeignKey("users.id", ondelete="cascade"),
unique=True,
nullable=False,
index=True,
)
partner_id = sa.Column(
sa.ForeignKey("partner.id", ondelete="cascade"), nullable=False, index=True
)
external_user_id = sa.Column(sa.String(128), unique=False, nullable=False)
partner_email = sa.Column(sa.String(255), unique=False, nullable=True)
user = orm.relationship(User, foreign_keys=[user_id])
partner = orm.relationship(Partner, foreign_keys=[partner_id])
__table_args__ = (
sa.UniqueConstraint(
"partner_id", "external_user_id", name="uq_partner_id_external_user_id"
),
)
def get_proton_partner() -> Partner:
global _PROTON_PARTNER
if _PROTON_PARTNER is None:
partner = Partner.get_by(name=PROTON_PARTNER_NAME)
if partner is None:
raise ProtonPartnerNotSetUp
Session.expunge(partner)
_PROTON_PARTNER = partner
return _PROTON_PARTNER
def sanitize_next_url(url: Optional[str]) -> Optional[str]:
return NextUrlSanitizer.sanitize(url, ALLOWED_REDIRECT_DOMAINS)
def enter_sudo():
password_check_form = LoginForm()
if password_check_form.validate_on_submit():
password = password_check_form.password.data
if current_user.check_password(password):
session["sudo_time"] = int(time())
# User comes to sudo page from another page
next_url = sanitize_next_url(request.args.get("next"))
if next_url:
LOG.d("redirect user to %s", next_url)
return redirect(next_url)
else:
LOG.d("redirect user to dashboard")
return redirect(url_for("dashboard.index"))
else:
flash("Incorrect password", "warning")
proton_enabled = CONNECT_WITH_PROTON
if proton_enabled:
# Only for users that have the account linked
partner_user = PartnerUser.get_by(user_id=current_user.id)
if not partner_user or partner_user.partner_id != get_proton_partner().id:
proton_enabled = False
oidc_enabled = OIDC_CLIENT_ID is not None
if oidc_enabled:
oidc_enabled = (
SocialAuth.get_by(user_id=current_user.id, social="oidc") is not None
)
return render_template(
"dashboard/enter_sudo.html",
password_check_form=password_check_form,
next=request.args.get("next"),
connect_with_proton=proton_enabled,
connect_with_oidc=oidc_enabled,
connect_with_oidc_icon=CONNECT_WITH_OIDC_ICON,
) | null |
180,725 | from functools import wraps
from time import time
from flask import render_template, flash, redirect, url_for, session, request
from flask_login import login_required, current_user
from flask_wtf import FlaskForm
from wtforms import PasswordField, validators
from app.config import CONNECT_WITH_PROTON, OIDC_CLIENT_ID, CONNECT_WITH_OIDC_ICON
from app.dashboard.base import dashboard_bp
from app.extensions import limiter
from app.log import LOG
from app.models import PartnerUser, SocialAuth
from app.proton.utils import get_proton_partner
from app.utils import sanitize_next_url
_SUDO_GAP = 900
def sudo_required(f):
@wraps(f)
def wrap(*args, **kwargs):
if (
"sudo_time" not in session
or (time() - int(session["sudo_time"])) > _SUDO_GAP
):
return redirect(url_for("dashboard.enter_sudo", next=request.path))
return f(*args, **kwargs)
return wrap | null |
180,726 | from flask import render_template, request, redirect, url_for, flash
from flask_login import login_required, current_user
from flask_wtf import FlaskForm
from wtforms import (
StringField,
validators,
SelectMultipleField,
BooleanField,
IntegerField,
)
from app import parallel_limiter
from app.config import (
EMAIL_DOMAIN,
ALIAS_DOMAINS,
MAX_NB_DIRECTORY,
BOUNCE_PREFIX_FOR_REPLY_PHASE,
)
from app.dashboard.base import dashboard_bp
from app.db import Session
from app.errors import DirectoryInTrashError
from app.models import Directory, Mailbox, DirectoryMailbox
class NewDirForm(FlaskForm):
name = StringField(
"name", validators=[validators.DataRequired(), validators.Length(min=3)]
)
class ToggleDirForm(FlaskForm):
directory_id = IntegerField(validators=[validators.DataRequired()])
directory_enabled = BooleanField(validators=[])
class UpdateDirForm(FlaskForm):
directory_id = IntegerField(validators=[validators.DataRequired()])
mailbox_ids = SelectMultipleField(
validators=[validators.DataRequired()], validate_choice=False, choices=[]
)
class DeleteDirForm(FlaskForm):
directory_id = IntegerField(validators=[validators.DataRequired()])
EMAIL_DOMAIN = os.environ["EMAIL_DOMAIN"].lower()
BOUNCE_PREFIX_FOR_REPLY_PHASE = (
os.environ.get("BOUNCE_PREFIX_FOR_REPLY_PHASE") or "bounce_reply"
)
MAX_NB_DIRECTORY = 50
ALIAS_DOMAINS = [d.lower().strip() for d in ALIAS_DOMAINS]
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
class DirectoryInTrashError(SLException):
"""raised when a directory is deleted before"""
pass
class Directory(Base, ModelMixin):
__tablename__ = "directory"
user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False)
name = sa.Column(sa.String(128), unique=True, nullable=False)
# when a directory is disabled, new alias can't be created on the fly
disabled = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0")
user = orm.relationship(User, backref="directories")
_mailboxes = orm.relationship(
"Mailbox", secondary="directory_mailbox", lazy="joined"
)
def mailboxes(self):
if self._mailboxes:
return self._mailboxes
else:
return [self.user.default_mailbox]
def nb_alias(self):
return Alias.filter_by(directory_id=self.id).count()
def create(cls, *args, **kwargs):
name = kwargs.get("name")
if DeletedDirectory.get_by(name=name):
raise DirectoryInTrashError
directory = super(Directory, cls).create(*args, **kwargs)
Session.flush()
user = directory.user
user._directory_quota -= 1
Session.flush()
return directory
def delete(cls, obj_id):
obj: Directory = cls.get(obj_id)
user = obj.user
# Put all aliases belonging to this directory to global or domain trash
for alias in Alias.filter_by(directory_id=obj_id):
from app import alias_utils
alias_utils.delete_alias(alias, user)
DeletedDirectory.create(name=obj.name)
cls.filter(cls.id == obj_id).delete()
Session.commit()
def __repr__(self):
return f"<Directory {self.name}>"
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 DirectoryMailbox(Base, ModelMixin):
__tablename__ = "directory_mailbox"
__table_args__ = (
sa.UniqueConstraint("directory_id", "mailbox_id", name="uq_directory_mailbox"),
)
directory_id = sa.Column(
sa.ForeignKey(Directory.id, ondelete="cascade"), nullable=False
)
mailbox_id = sa.Column(
sa.ForeignKey(Mailbox.id, ondelete="cascade"), nullable=False
)
def directory():
dirs = (
Directory.filter_by(user_id=current_user.id)
.order_by(Directory.created_at.desc())
.all()
)
mailboxes = current_user.mailboxes()
new_dir_form = NewDirForm()
toggle_dir_form = ToggleDirForm()
update_dir_form = UpdateDirForm()
update_dir_form.mailbox_ids.choices = [
(str(mailbox.id), str(mailbox.id)) for mailbox in mailboxes
]
delete_dir_form = DeleteDirForm()
if request.method == "POST":
if request.form.get("form-name") == "delete":
if not delete_dir_form.validate():
flash("Invalid request", "warning")
return redirect(url_for("dashboard.directory"))
dir_obj = Directory.get(delete_dir_form.directory_id.data)
if not dir_obj:
flash("Unknown error. Refresh the page", "warning")
return redirect(url_for("dashboard.directory"))
elif dir_obj.user_id != current_user.id:
flash("You cannot delete this directory", "warning")
return redirect(url_for("dashboard.directory"))
name = dir_obj.name
Directory.delete(dir_obj.id)
Session.commit()
flash(f"Directory {name} has been deleted", "success")
return redirect(url_for("dashboard.directory"))
if request.form.get("form-name") == "toggle-directory":
if not toggle_dir_form.validate():
flash("Invalid request", "warning")
return redirect(url_for("dashboard.directory"))
dir_id = toggle_dir_form.directory_id.data
dir_obj = Directory.get(dir_id)
if not dir_obj or dir_obj.user_id != current_user.id:
flash("Unknown error. Refresh the page", "warning")
return redirect(url_for("dashboard.directory"))
if toggle_dir_form.directory_enabled.data:
dir_obj.disabled = False
flash(f"On-the-fly is enabled for {dir_obj.name}", "success")
else:
dir_obj.disabled = True
flash(f"On-the-fly is disabled for {dir_obj.name}", "warning")
Session.commit()
return redirect(url_for("dashboard.directory"))
elif request.form.get("form-name") == "update":
if not update_dir_form.validate():
flash("Invalid request", "warning")
return redirect(url_for("dashboard.directory"))
dir_id = update_dir_form.directory_id.data
dir_obj = Directory.get(dir_id)
if not dir_obj or dir_obj.user_id != current_user.id:
flash("Unknown error. Refresh the page", "warning")
return redirect(url_for("dashboard.directory"))
mailbox_ids = update_dir_form.mailbox_ids.data
# check if mailbox is not tempered with
mailboxes = []
for mailbox_id in mailbox_ids:
mailbox = Mailbox.get(mailbox_id)
if (
not mailbox
or mailbox.user_id != current_user.id
or not mailbox.verified
):
flash("Something went wrong, please retry", "warning")
return redirect(url_for("dashboard.directory"))
mailboxes.append(mailbox)
if not mailboxes:
flash("You must select at least 1 mailbox", "warning")
return redirect(url_for("dashboard.directory"))
# first remove all existing directory-mailboxes links
DirectoryMailbox.filter_by(directory_id=dir_obj.id).delete()
Session.flush()
for mailbox in mailboxes:
DirectoryMailbox.create(directory_id=dir_obj.id, mailbox_id=mailbox.id)
Session.commit()
flash(f"Directory {dir_obj.name} has been updated", "success")
return redirect(url_for("dashboard.directory"))
elif request.form.get("form-name") == "create":
if not current_user.is_premium():
flash("Only premium plan can add directory", "warning")
return redirect(url_for("dashboard.directory"))
if current_user.directory_quota <= 0:
flash(
f"You cannot have more than {MAX_NB_DIRECTORY} directories",
"warning",
)
return redirect(url_for("dashboard.directory"))
if new_dir_form.validate():
new_dir_name = new_dir_form.name.data.lower()
if Directory.get_by(name=new_dir_name):
flash(f"{new_dir_name} already used", "warning")
elif new_dir_name in (
"reply",
"ra",
"bounces",
"bounce",
"transactional",
BOUNCE_PREFIX_FOR_REPLY_PHASE,
):
flash(
"this directory name is reserved, please choose another name",
"warning",
)
else:
try:
new_dir = Directory.create(
name=new_dir_name, user_id=current_user.id
)
except DirectoryInTrashError:
flash(
f"{new_dir_name} has been used before and cannot be reused",
"error",
)
else:
Session.commit()
mailbox_ids = request.form.getlist("mailbox_ids")
if mailbox_ids:
# check if mailbox is not tempered with
mailboxes = []
for mailbox_id in mailbox_ids:
mailbox = Mailbox.get(mailbox_id)
if (
not mailbox
or mailbox.user_id != current_user.id
or not mailbox.verified
):
flash(
"Something went wrong, please retry", "warning"
)
return redirect(url_for("dashboard.directory"))
mailboxes.append(mailbox)
for mailbox in mailboxes:
DirectoryMailbox.create(
directory_id=new_dir.id, mailbox_id=mailbox.id
)
Session.commit()
flash(f"Directory {new_dir.name} is created", "success")
return redirect(url_for("dashboard.directory"))
return render_template(
"dashboard/directory.html",
dirs=dirs,
toggle_dir_form=toggle_dir_form,
update_dir_form=update_dir_form,
delete_dir_form=delete_dir_form,
new_dir_form=new_dir_form,
mailboxes=mailboxes,
EMAIL_DOMAIN=EMAIL_DOMAIN,
ALIAS_DOMAINS=ALIAS_DOMAINS,
) | null |
180,727 | import pyotp
from flask import render_template, flash, redirect, url_for
from flask_login import login_required, current_user
from flask_wtf import FlaskForm
from wtforms import StringField, validators
from app.dashboard.base import dashboard_bp
from app.dashboard.views.enter_sudo import sudo_required
from app.db import Session
from app.log import LOG
from app.models import RecoveryCode
class OtpTokenForm(FlaskForm):
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
LOG = _get_logger("SL")
class RecoveryCode(Base, ModelMixin):
def _hash_code(cls, code: str) -> str:
def generate(cls, user):
def find_by_user_code(cls, user: User, code: str):
def empty(cls, user):
def mfa_setup():
if current_user.enable_otp:
flash("you have already enabled MFA", "warning")
return redirect(url_for("dashboard.index"))
otp_token_form = OtpTokenForm()
if not current_user.otp_secret:
LOG.d("Generate otp_secret for user %s", current_user)
current_user.otp_secret = pyotp.random_base32()
Session.commit()
totp = pyotp.TOTP(current_user.otp_secret)
if otp_token_form.validate_on_submit():
token = otp_token_form.token.data.replace(" ", "")
if totp.verify(token) and current_user.last_otp != token:
current_user.enable_otp = True
current_user.last_otp = token
Session.commit()
flash("MFA has been activated", "success")
recovery_codes = RecoveryCode.generate(current_user)
return render_template(
"dashboard/recovery_code.html", recovery_codes=recovery_codes
)
else:
flash("Incorrect token", "warning")
otp_uri = pyotp.totp.TOTP(current_user.otp_secret).provisioning_uri(
name=current_user.email, issuer_name="SimpleLogin"
)
return render_template(
"dashboard/mfa_setup.html", otp_token_form=otp_token_form, otp_uri=otp_uri
) | null |
180,728 | import arrow
from coinbase_commerce import Client
from flask import render_template, flash, redirect, url_for
from flask_login import login_required, current_user
from app.config import (
PADDLE_VENDOR_ID,
PADDLE_MONTHLY_PRODUCT_ID,
PADDLE_YEARLY_PRODUCT_ID,
URL,
COINBASE_YEARLY_PRICE,
COINBASE_API_KEY,
)
from app.dashboard.base import dashboard_bp
from app.extensions import limiter
from app.log import LOG
from app.models import (
AppleSubscription,
Subscription,
ManualSubscription,
CoinbaseSubscription,
PartnerUser,
PartnerSubscription,
)
from app.proton.utils import get_proton_partner
URL = os.environ["URL"]
try:
PADDLE_VENDOR_ID = int(os.environ["PADDLE_VENDOR_ID"])
PADDLE_MONTHLY_PRODUCT_ID = int(os.environ["PADDLE_MONTHLY_PRODUCT_ID"])
PADDLE_YEARLY_PRODUCT_ID = int(os.environ["PADDLE_YEARLY_PRODUCT_ID"])
except (KeyError, ValueError):
print("Paddle param not set")
PADDLE_VENDOR_ID = -1
PADDLE_MONTHLY_PRODUCT_ID = -1
PADDLE_YEARLY_PRODUCT_ID = -1
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}>"
class ManualSubscription(Base, ModelMixin):
"""
For users who use other forms of payment and therefore not pass by Paddle
"""
__tablename__ = "manual_subscription"
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, unique=True
)
# an reminder is sent several days before the subscription ends
end_at = sa.Column(ArrowType, nullable=False)
# for storing note about this subscription
comment = sa.Column(sa.Text, nullable=True)
# manual subscription are also used for Premium giveaways
is_giveaway = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
user = orm.relationship(User)
def is_active(self):
return self.end_at > arrow.now()
class CoinbaseSubscription(Base, ModelMixin):
"""
For subscriptions using Coinbase Commerce
"""
__tablename__ = "coinbase_subscription"
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, unique=True
)
# an reminder is sent several days before the subscription ends
end_at = sa.Column(ArrowType, nullable=False)
# the Coinbase code
code = sa.Column(sa.String(64), nullable=True)
user = orm.relationship(User)
def is_active(self):
return self.end_at > arrow.now()
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)
class PartnerUser(Base, ModelMixin):
__tablename__ = "partner_user"
user_id = sa.Column(
sa.ForeignKey("users.id", ondelete="cascade"),
unique=True,
nullable=False,
index=True,
)
partner_id = sa.Column(
sa.ForeignKey("partner.id", ondelete="cascade"), nullable=False, index=True
)
external_user_id = sa.Column(sa.String(128), unique=False, nullable=False)
partner_email = sa.Column(sa.String(255), unique=False, nullable=True)
user = orm.relationship(User, foreign_keys=[user_id])
partner = orm.relationship(Partner, foreign_keys=[partner_id])
__table_args__ = (
sa.UniqueConstraint(
"partner_id", "external_user_id", name="uq_partner_id_external_user_id"
),
)
class PartnerSubscription(Base, ModelMixin):
"""
For users who have a subscription via a partner
"""
__tablename__ = "partner_subscription"
partner_user_id = sa.Column(
sa.ForeignKey(PartnerUser.id, ondelete="cascade"), nullable=False, unique=True
)
# when the partner subscription ends
end_at = sa.Column(ArrowType, nullable=False, index=True)
partner_user = orm.relationship(PartnerUser)
def find_by_user_id(cls, user_id: int) -> Optional[PartnerSubscription]:
res = (
Session.query(PartnerSubscription, PartnerUser)
.filter(
and_(
PartnerUser.user_id == user_id,
PartnerSubscription.partner_user_id == PartnerUser.id,
)
)
.first()
)
if res:
subscription, partner_user = res
return subscription
return None
def is_active(self):
return self.end_at > arrow.now().shift(days=-_PARTNER_SUBSCRIPTION_GRACE_DAYS)
def get_proton_partner() -> Partner:
global _PROTON_PARTNER
if _PROTON_PARTNER is None:
partner = Partner.get_by(name=PROTON_PARTNER_NAME)
if partner is None:
raise ProtonPartnerNotSetUp
Session.expunge(partner)
_PROTON_PARTNER = partner
return _PROTON_PARTNER
def pricing():
if current_user.lifetime:
flash("You already have a lifetime subscription", "error")
return redirect(url_for("dashboard.index"))
paddle_sub: Subscription = current_user.get_paddle_subscription()
# user who has canceled can re-subscribe
if paddle_sub and not paddle_sub.cancelled:
flash("You already have an active subscription", "error")
return redirect(url_for("dashboard.index"))
now = arrow.now()
manual_sub: ManualSubscription = ManualSubscription.filter(
ManualSubscription.user_id == current_user.id, ManualSubscription.end_at > now
).first()
coinbase_sub = CoinbaseSubscription.filter(
CoinbaseSubscription.user_id == current_user.id,
CoinbaseSubscription.end_at > now,
).first()
apple_sub: AppleSubscription = AppleSubscription.get_by(user_id=current_user.id)
if apple_sub and apple_sub.is_valid():
flash("Please make sure to cancel your subscription on Apple first", "warning")
proton_upgrade = False
partner_user = PartnerUser.get_by(user_id=current_user.id)
if partner_user:
partner_sub = PartnerSubscription.get_by(partner_user_id=partner_user.id)
if partner_sub and partner_sub.is_active():
flash(
f"You already have a subscription provided by {partner_user.partner.name}",
"error",
)
return redirect(url_for("dashboard.index"))
proton_upgrade = partner_user.partner_id == get_proton_partner().id
return render_template(
"dashboard/pricing.html",
PADDLE_VENDOR_ID=PADDLE_VENDOR_ID,
PADDLE_MONTHLY_PRODUCT_ID=PADDLE_MONTHLY_PRODUCT_ID,
PADDLE_YEARLY_PRODUCT_ID=PADDLE_YEARLY_PRODUCT_ID,
success_url=URL + "/dashboard/subscription_success",
manual_sub=manual_sub,
coinbase_sub=coinbase_sub,
now=now,
proton_upgrade=proton_upgrade,
) | null |
180,729 | import arrow
from coinbase_commerce import Client
from flask import render_template, flash, redirect, url_for
from flask_login import login_required, current_user
from app.config import (
PADDLE_VENDOR_ID,
PADDLE_MONTHLY_PRODUCT_ID,
PADDLE_YEARLY_PRODUCT_ID,
URL,
COINBASE_YEARLY_PRICE,
COINBASE_API_KEY,
)
from app.dashboard.base import dashboard_bp
from app.extensions import limiter
from app.log import LOG
from app.models import (
AppleSubscription,
Subscription,
ManualSubscription,
CoinbaseSubscription,
PartnerUser,
PartnerSubscription,
)
from app.proton.utils import get_proton_partner
def subscription_success():
return render_template(
"dashboard/thank-you.html",
) | null |
180,730 | import arrow
from coinbase_commerce import Client
from flask import render_template, flash, redirect, url_for
from flask_login import login_required, current_user
from app.config import (
PADDLE_VENDOR_ID,
PADDLE_MONTHLY_PRODUCT_ID,
PADDLE_YEARLY_PRODUCT_ID,
URL,
COINBASE_YEARLY_PRICE,
COINBASE_API_KEY,
)
from app.dashboard.base import dashboard_bp
from app.extensions import limiter
from app.log import LOG
from app.models import (
AppleSubscription,
Subscription,
ManualSubscription,
CoinbaseSubscription,
PartnerUser,
PartnerSubscription,
)
from app.proton.utils import get_proton_partner
COINBASE_API_KEY = os.environ.get("COINBASE_API_KEY")
try:
COINBASE_YEARLY_PRICE = float(os.environ["COINBASE_YEARLY_PRICE"])
except Exception:
COINBASE_YEARLY_PRICE = 30.00
LOG = _get_logger("SL")
def coinbase_checkout_route():
client = Client(api_key=COINBASE_API_KEY)
charge = client.charge.create(
name="1 Year SimpleLogin Premium Subscription",
local_price={"amount": str(COINBASE_YEARLY_PRICE), "currency": "USD"},
pricing_type="fixed_price",
metadata={"user_id": current_user.id},
)
LOG.d("Create coinbase charge %s", charge)
return redirect(charge["hosted_url"]) | null |
180,731 | import arrow
from flask import render_template, flash, redirect, url_for, request
from flask_login import login_required, current_user
from flask_wtf import FlaskForm
from wtforms import StringField, validators
from app import parallel_limiter
from app.config import PADDLE_VENDOR_ID, PADDLE_COUPON_ID
from app.dashboard.base import dashboard_bp
from app.db import Session
from app.log import LOG
from app.models import (
ManualSubscription,
Coupon,
Subscription,
AppleSubscription,
CoinbaseSubscription,
LifetimeCoupon,
)
class CouponForm(FlaskForm):
code = StringField("Coupon Code", validators=[validators.DataRequired()])
try:
PADDLE_VENDOR_ID = int(os.environ["PADDLE_VENDOR_ID"])
PADDLE_MONTHLY_PRODUCT_ID = int(os.environ["PADDLE_MONTHLY_PRODUCT_ID"])
PADDLE_YEARLY_PRODUCT_ID = int(os.environ["PADDLE_YEARLY_PRODUCT_ID"])
except (KeyError, ValueError):
print("Paddle param not set")
PADDLE_VENDOR_ID = -1
PADDLE_MONTHLY_PRODUCT_ID = -1
PADDLE_YEARLY_PRODUCT_ID = -1
PADDLE_COUPON_ID = os.environ.get("PADDLE_COUPON_ID")
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
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}>"
class ManualSubscription(Base, ModelMixin):
"""
For users who use other forms of payment and therefore not pass by Paddle
"""
__tablename__ = "manual_subscription"
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, unique=True
)
# an reminder is sent several days before the subscription ends
end_at = sa.Column(ArrowType, nullable=False)
# for storing note about this subscription
comment = sa.Column(sa.Text, nullable=True)
# manual subscription are also used for Premium giveaways
is_giveaway = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
user = orm.relationship(User)
def is_active(self):
return self.end_at > arrow.now()
class CoinbaseSubscription(Base, ModelMixin):
"""
For subscriptions using Coinbase Commerce
"""
__tablename__ = "coinbase_subscription"
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, unique=True
)
# an reminder is sent several days before the subscription ends
end_at = sa.Column(ArrowType, nullable=False)
# the Coinbase code
code = sa.Column(sa.String(64), nullable=True)
user = orm.relationship(User)
def is_active(self):
return self.end_at > arrow.now()
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)
class LifetimeCoupon(Base, ModelMixin):
__tablename__ = "lifetime_coupon"
code = sa.Column(sa.String(128), nullable=False, unique=True)
nb_used = sa.Column(sa.Integer, nullable=False)
paid = sa.Column(sa.Boolean, default=False, server_default="0", nullable=False)
comment = sa.Column(sa.Text, nullable=True)
class Coupon(Base, ModelMixin):
__tablename__ = "coupon"
code = sa.Column(sa.String(128), nullable=False, unique=True)
# by default a coupon is for 1 year
nb_year = sa.Column(sa.Integer, nullable=False, server_default="1", default=1)
# whether the coupon has been used
used = sa.Column(sa.Boolean, default=False, server_default="0", nullable=False)
# the user who uses the code
# non-null when the coupon is used
used_by_user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=True
)
is_giveaway = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
comment = sa.Column(sa.Text, nullable=True)
# a coupon can have an expiration
expires_date = sa.Column(ArrowType, nullable=True)
def coupon_route():
coupon_form = CouponForm()
if coupon_form.validate_on_submit():
code = coupon_form.code.data
if LifetimeCoupon.get_by(code=code):
LOG.d("redirect %s to lifetime page instead", current_user)
flash("Redirect to the lifetime coupon page instead", "success")
return redirect(url_for("dashboard.lifetime_licence"))
# handle case user already has an active subscription via another channel (Paddle, Apple, etc)
can_use_coupon = True
if current_user.lifetime:
can_use_coupon = False
sub: Subscription = current_user.get_paddle_subscription()
if sub:
can_use_coupon = False
apple_sub: AppleSubscription = AppleSubscription.get_by(user_id=current_user.id)
if apple_sub and apple_sub.is_valid():
can_use_coupon = False
coinbase_subscription: CoinbaseSubscription = CoinbaseSubscription.get_by(
user_id=current_user.id
)
if coinbase_subscription and coinbase_subscription.is_active():
can_use_coupon = False
if coupon_form.validate_on_submit():
code = coupon_form.code.data
coupon: Coupon = Coupon.get_by(code=code)
if coupon and not coupon.used:
if coupon.expires_date and coupon.expires_date < arrow.now():
flash(
f"The coupon was expired on {coupon.expires_date.humanize()}",
"error",
)
return redirect(request.url)
updated = (
Session.query(Coupon)
.filter_by(code=code, used=False)
.update({"used_by_user_id": current_user.id, "used": True})
)
if updated != 1:
flash("Coupon is not valid", "error")
return redirect(request.url)
manual_sub: ManualSubscription = ManualSubscription.get_by(
user_id=current_user.id
)
if manual_sub:
# renew existing subscription
if manual_sub.end_at > arrow.now():
manual_sub.end_at = manual_sub.end_at.shift(years=coupon.nb_year)
else:
manual_sub.end_at = arrow.now().shift(years=coupon.nb_year, days=1)
Session.commit()
flash(
f"Your current subscription is extended to {manual_sub.end_at.humanize()}",
"success",
)
else:
ManualSubscription.create(
user_id=current_user.id,
end_at=arrow.now().shift(years=coupon.nb_year, days=1),
comment="using coupon code",
is_giveaway=coupon.is_giveaway,
commit=True,
)
flash(
"Your account has been upgraded to Premium, thanks for your support!",
"success",
)
return redirect(url_for("dashboard.index"))
else:
flash(f"Code *{code}* expired or invalid", "warning")
return render_template(
"dashboard/coupon.html",
coupon_form=coupon_form,
PADDLE_VENDOR_ID=PADDLE_VENDOR_ID,
PADDLE_COUPON_ID=PADDLE_COUPON_ID,
can_use_coupon=can_use_coupon,
# a coupon is only valid until this date
# this is to avoid using the coupon to renew an account forever
max_coupon_date=arrow.now().shift(years=1, days=-1),
) | null |
180,732 | import base64
import binascii
import json
import arrow
from flask import render_template, request, redirect, url_for, flash
from flask_login import login_required, current_user
from flask_wtf import FlaskForm
from itsdangerous import TimestampSigner
from wtforms import validators, IntegerField
from wtforms.fields.html5 import EmailField
from app import parallel_limiter
from app.config import MAILBOX_SECRET, URL, JOB_DELETE_MAILBOX
from app.dashboard.base import dashboard_bp
from app.db import Session
from app.email_utils import (
email_can_be_used_as_mailbox,
mailbox_already_used,
render,
send_email,
)
from app.email_validation import is_valid_email
from app.log import LOG
from app.models import Mailbox, Job
from app.utils import CSRFValidationForm
class NewMailboxForm(FlaskForm):
email = EmailField(
"email", validators=[validators.DataRequired(), validators.Email()]
)
class DeleteMailboxForm(FlaskForm):
mailbox_id = IntegerField(
validators=[validators.DataRequired()],
)
transfer_mailbox_id = IntegerField()
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,
),
)
JOB_DELETE_MAILBOX = "delete-mailbox"
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
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}>"
class CSRFValidationForm(FlaskForm):
pass
def mailbox_route():
mailboxes = (
Mailbox.filter_by(user_id=current_user.id)
.order_by(Mailbox.created_at.desc())
.all()
)
new_mailbox_form = NewMailboxForm()
csrf_form = CSRFValidationForm()
delete_mailbox_form = DeleteMailboxForm()
if request.method == "POST":
if request.form.get("form-name") == "delete":
if not delete_mailbox_form.validate():
flash("Invalid request", "warning")
return redirect(request.url)
mailbox = Mailbox.get(delete_mailbox_form.mailbox_id.data)
if not mailbox or mailbox.user_id != current_user.id:
flash("Invalid mailbox. Refresh the page", "warning")
return redirect(url_for("dashboard.mailbox_route"))
if mailbox.id == current_user.default_mailbox_id:
flash("You cannot delete default mailbox", "error")
return redirect(url_for("dashboard.mailbox_route"))
transfer_mailbox_id = delete_mailbox_form.transfer_mailbox_id.data
if transfer_mailbox_id and transfer_mailbox_id > 0:
transfer_mailbox = Mailbox.get(transfer_mailbox_id)
if not transfer_mailbox or transfer_mailbox.user_id != current_user.id:
flash(
"You must transfer the aliases to a mailbox you own.", "error"
)
return redirect(url_for("dashboard.mailbox_route"))
if transfer_mailbox.id == mailbox.id:
flash(
"You can not transfer the aliases to the mailbox you want to delete.",
"error",
)
return redirect(url_for("dashboard.mailbox_route"))
if not transfer_mailbox.verified:
flash("Your new mailbox is not verified", "error")
return redirect(url_for("dashboard.mailbox_route"))
# Schedule delete account job
LOG.w(
f"schedule delete mailbox job for {mailbox.id} with transfer to mailbox {transfer_mailbox_id}"
)
Job.create(
name=JOB_DELETE_MAILBOX,
payload={
"mailbox_id": mailbox.id,
"transfer_mailbox_id": transfer_mailbox_id
if transfer_mailbox_id > 0
else None,
},
run_at=arrow.now(),
commit=True,
)
flash(
f"Mailbox {mailbox.email} scheduled for deletion."
f"You will receive a confirmation email when the deletion is finished",
"success",
)
return redirect(url_for("dashboard.mailbox_route"))
if request.form.get("form-name") == "set-default":
if not csrf_form.validate():
flash("Invalid request", "warning")
return redirect(request.url)
mailbox_id = request.form.get("mailbox_id")
mailbox = Mailbox.get(mailbox_id)
if not mailbox or mailbox.user_id != current_user.id:
flash("Unknown error. Refresh the page", "warning")
return redirect(url_for("dashboard.mailbox_route"))
if mailbox.id == current_user.default_mailbox_id:
flash("This mailbox is already default one", "error")
return redirect(url_for("dashboard.mailbox_route"))
if not mailbox.verified:
flash("Cannot set unverified mailbox as default", "error")
return redirect(url_for("dashboard.mailbox_route"))
current_user.default_mailbox_id = mailbox.id
Session.commit()
flash(f"Mailbox {mailbox.email} is set as Default Mailbox", "success")
return redirect(url_for("dashboard.mailbox_route"))
elif request.form.get("form-name") == "create":
if not current_user.is_premium():
flash("Only premium plan can add additional mailbox", "warning")
return redirect(url_for("dashboard.mailbox_route"))
if new_mailbox_form.validate():
mailbox_email = (
new_mailbox_form.email.data.lower().strip().replace(" ", "")
)
if not is_valid_email(mailbox_email):
flash(f"{mailbox_email} invalid", "error")
elif mailbox_already_used(mailbox_email, current_user):
flash(f"{mailbox_email} already used", "error")
elif not email_can_be_used_as_mailbox(mailbox_email):
flash(f"You cannot use {mailbox_email}.", "error")
else:
new_mailbox = Mailbox.create(
email=mailbox_email, user_id=current_user.id
)
Session.commit()
send_verification_email(current_user, new_mailbox)
flash(
f"You are going to receive an email to confirm {mailbox_email}.",
"success",
)
return redirect(
url_for(
"dashboard.mailbox_detail_route",
mailbox_id=new_mailbox.id,
)
)
return render_template(
"dashboard/mailbox.html",
mailboxes=mailboxes,
new_mailbox_form=new_mailbox_form,
delete_mailbox_form=delete_mailbox_form,
csrf_form=csrf_form,
) | null |
180,733 | import base64
import binascii
import json
import arrow
from flask import render_template, request, redirect, url_for, flash
from flask_login import login_required, current_user
from flask_wtf import FlaskForm
from itsdangerous import TimestampSigner
from wtforms import validators, IntegerField
from wtforms.fields.html5 import EmailField
from app import parallel_limiter
from app.config import MAILBOX_SECRET, URL, JOB_DELETE_MAILBOX
from app.dashboard.base import dashboard_bp
from app.db import Session
from app.email_utils import (
email_can_be_used_as_mailbox,
mailbox_already_used,
render,
send_email,
)
from app.email_validation import is_valid_email
from app.log import LOG
from app.models import Mailbox, Job
from app.utils import CSRFValidationForm
MAILBOX_SECRET = FLASK_SECRET + "mailbox"
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
LOG = _get_logger("SL")
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 mailbox_verify():
s = TimestampSigner(MAILBOX_SECRET)
mailbox_verify_request = request.args.get("mailbox_id")
try:
mailbox_raw_data = s.unsign(mailbox_verify_request, max_age=900)
except Exception:
flash("Invalid link. Please delete and re-add your mailbox", "error")
return redirect(url_for("dashboard.mailbox_route"))
try:
decoded_data = base64.urlsafe_b64decode(mailbox_raw_data)
except binascii.Error:
flash("Invalid link. Please delete and re-add your mailbox", "error")
return redirect(url_for("dashboard.mailbox_route"))
mailbox_data = json.loads(decoded_data)
if not isinstance(mailbox_data, list) or len(mailbox_data) != 2:
flash("Invalid link. Please delete and re-add your mailbox", "error")
return redirect(url_for("dashboard.mailbox_route"))
mailbox_id = mailbox_data[0]
mailbox = Mailbox.get(mailbox_id)
if not mailbox:
flash("Invalid link", "error")
return redirect(url_for("dashboard.mailbox_route"))
mailbox_email = mailbox_data[1]
if mailbox_email != mailbox.email:
flash("Invalid link", "error")
return redirect(url_for("dashboard.mailbox_route"))
mailbox.verified = True
Session.commit()
LOG.d("Mailbox %s is verified", mailbox)
return render_template("dashboard/mailbox_validation.html", mailbox=mailbox) | null |
180,734 | import json
import urllib.parse
from typing import Union
import requests
from flask import render_template, request, flash, url_for, redirect, g
from flask_login import login_required, current_user
from werkzeug.datastructures import FileStorage
from app.config import ZENDESK_HOST, ZENDESK_API_TOKEN
from app.dashboard.base import dashboard_bp
from app.extensions import limiter
from app.log import LOG
def create_zendesk_request(email: str, content: str, files: [FileStorage]) -> bool:
tokens = []
for file in files:
if not file.filename:
continue
token = upload_file_to_zendesk_and_get_upload_token(email, file)
if token is None:
return False
tokens.append(token)
data = {
"request": {
"subject": "Ticket created for user {}".format(current_user.id),
"comment": {"type": "Comment", "body": content, "uploads": tokens},
"requester": {
"name": "SimpleLogin user {}".format(current_user.id),
"email": email,
},
}
}
url = "https://{}/api/v2/requests.json".format(ZENDESK_HOST)
headers = {"content-type": "application/json"}
auth = (f"{email}/token", ZENDESK_API_TOKEN)
response = requests.post(url, data=json.dumps(data), headers=headers, auth=auth)
if not check_zendesk_response_status(response.status_code):
return False
return True
"2/hour",
methods=["POST"],
deduct_when=lambda r: hasattr(g, "deduct_limit") and g.deduct_limit,
ZENDESK_HOST = os.environ.get("ZENDESK_HOST")
def support_route():
if not ZENDESK_HOST:
flash("Support isn't enabled", "error")
return redirect(url_for("dashboard.index"))
if request.method == "POST":
content = request.form.get("ticket_content")
email = request.form.get("ticket_email")
if not content:
flash("Please add a description", "error")
return render_template("dashboard/support.html", ticket_email=email)
if not email:
flash("Please provide an email address", "error")
return render_template("dashboard/support.html", ticket_content=content)
if not create_zendesk_request(
email, content, request.files.getlist("ticket_files")
):
flash(
"Cannot create a Zendesk ticket, sorry for the inconvenience! Please retry later.",
"error",
)
return render_template(
"dashboard/support.html", ticket_email=email, ticket_content=content
)
# only enable rate limiting for successful Zendesk ticket creation
g.deduct_limit = True
flash(
"Support ticket is created. You will receive an email about its status.",
"success",
)
return redirect(url_for("dashboard.index"))
return render_template("dashboard/support.html", ticket_email=current_user.email) | null |
180,735 | import base64
import hmac
import secrets
import arrow
from flask import render_template, redirect, url_for, flash, request
from flask_login import login_required, current_user
from app import config
from app.alias_utils import transfer_alias
from app.dashboard.base import dashboard_bp
from app.dashboard.views.enter_sudo import sudo_required
from app.db import Session
from app.extensions import limiter
from app.log import LOG
from app.models import (
Alias,
)
from app.models import Mailbox
from app.utils import CSRFValidationForm
def hmac_alias_transfer_token(transfer_token: str) -> str:
alias_hmac = hmac.new(
config.ALIAS_TRANSFER_TOKEN_SECRET.encode("utf-8"),
transfer_token.encode("utf-8"),
"sha3_224",
)
return base64.urlsafe_b64encode(alias_hmac.digest()).decode("utf-8").rstrip("=")
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 CSRFValidationForm(FlaskForm):
pass
def alias_transfer_send_route(alias_id):
alias = Alias.get(alias_id)
if not alias or alias.user_id != current_user.id:
flash("You cannot see this page", "warning")
return redirect(url_for("dashboard.index"))
if current_user.newsletter_alias_id == alias.id:
flash(
"This alias is currently used for receiving the newsletter and cannot be transferred",
"error",
)
return redirect(url_for("dashboard.index"))
alias_transfer_url = None
csrf_form = CSRFValidationForm()
if request.method == "POST":
if not csrf_form.validate():
flash("Invalid request", "warning")
return redirect(request.url)
# generate a new transfer_token
if request.form.get("form-name") == "create":
transfer_token = f"{alias.id}.{secrets.token_urlsafe(32)}"
alias.transfer_token = hmac_alias_transfer_token(transfer_token)
alias.transfer_token_expiration = arrow.utcnow().shift(hours=24)
Session.commit()
alias_transfer_url = (
config.URL
+ "/dashboard/alias_transfer/receive"
+ f"?token={transfer_token}"
)
flash("Share alias URL created", "success")
# request.form.get("form-name") == "remove"
else:
alias.transfer_token = None
alias.transfer_token_expiration = None
Session.commit()
alias_transfer_url = None
flash("Share URL deleted", "success")
return render_template(
"dashboard/alias_transfer_send.html",
alias=alias,
alias_transfer_url=alias_transfer_url,
link_active=alias.transfer_token_expiration is not None
and alias.transfer_token_expiration > arrow.utcnow(),
csrf_form=csrf_form,
) | null |
180,736 | import base64
import hmac
import secrets
import arrow
from flask import render_template, redirect, url_for, flash, request
from flask_login import login_required, current_user
from app import config
from app.alias_utils import transfer_alias
from app.dashboard.base import dashboard_bp
from app.dashboard.views.enter_sudo import sudo_required
from app.db import Session
from app.extensions import limiter
from app.log import LOG
from app.models import (
Alias,
)
from app.models import Mailbox
from app.utils import CSRFValidationForm
def hmac_alias_transfer_token(transfer_token: str) -> str:
alias_hmac = hmac.new(
config.ALIAS_TRANSFER_TOKEN_SECRET.encode("utf-8"),
transfer_token.encode("utf-8"),
"sha3_224",
)
return base64.urlsafe_b64encode(alias_hmac.digest()).decode("utf-8").rstrip("=")
def transfer_alias(alias, new_user, new_mailboxes: [Mailbox]):
# cannot transfer alias which is used for receiving newsletter
if User.get_by(newsletter_alias_id=alias.id):
raise Exception("Cannot transfer alias that's used to receive newsletter")
# update user_id
Session.query(Contact).filter(Contact.alias_id == alias.id).update(
{"user_id": new_user.id}
)
Session.query(AliasUsedOn).filter(AliasUsedOn.alias_id == alias.id).update(
{"user_id": new_user.id}
)
Session.query(ClientUser).filter(ClientUser.alias_id == alias.id).update(
{"user_id": new_user.id}
)
# remove existing mailboxes from the alias
Session.query(AliasMailbox).filter(AliasMailbox.alias_id == alias.id).delete()
# set mailboxes
alias.mailbox_id = new_mailboxes.pop().id
for mb in new_mailboxes:
AliasMailbox.create(alias_id=alias.id, mailbox_id=mb.id)
# alias has never been transferred before
if not alias.original_owner_id:
alias.original_owner_id = alias.user_id
# inform previous owner
old_user = alias.user
send_email(
old_user.email,
f"Alias {alias.email} has been received",
render(
"transactional/alias-transferred.txt",
alias=alias,
),
render(
"transactional/alias-transferred.html",
alias=alias,
),
)
# now the alias belongs to the new user
alias.user_id = new_user.id
# set some fields back to default
alias.disable_pgp = False
alias.pinned = False
Session.commit()
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
LOG = _get_logger("SL")
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}>"
The provided code snippet includes necessary dependencies for implementing the `alias_transfer_receive_route` function. Write a Python function `def alias_transfer_receive_route()` to solve the following problem:
URL has ?alias_id=signed_alias_id
Here is the function:
def alias_transfer_receive_route():
"""
URL has ?alias_id=signed_alias_id
"""
token = request.args.get("token")
if not token:
flash("Invalid transfer token", "error")
return redirect(url_for("dashboard.index"))
hashed_token = hmac_alias_transfer_token(token)
# TODO: Don't allow unhashed tokens once all the tokens have been migrated to the new format
alias = Alias.get_by(transfer_token=token) or Alias.get_by(
transfer_token=hashed_token
)
if not alias:
flash("Invalid link", "error")
return redirect(url_for("dashboard.index"))
# TODO: Don't allow none once all the tokens have been migrated to the new format
if (
alias.transfer_token_expiration is not None
and alias.transfer_token_expiration < arrow.utcnow()
):
flash("Expired link, please request a new one", "error")
return redirect(url_for("dashboard.index"))
# alias already belongs to this user
if alias.user_id == current_user.id:
flash("You already own this alias", "warning")
return redirect(url_for("dashboard.index"))
# check if user has not exceeded the alias quota
if not current_user.can_create_new_alias():
LOG.d("%s can't receive new alias", current_user)
flash(
"You have reached free plan limit, please upgrade to create new aliases",
"warning",
)
return redirect(url_for("dashboard.index"))
mailboxes = current_user.mailboxes()
if request.method == "POST":
mailbox_ids = request.form.getlist("mailbox_ids")
# check if mailbox is not tempered with
mailboxes = []
for mailbox_id in mailbox_ids:
mailbox = Mailbox.get(mailbox_id)
if (
not mailbox
or mailbox.user_id != current_user.id
or not mailbox.verified
):
flash("Something went wrong, please retry", "warning")
return redirect(request.url)
mailboxes.append(mailbox)
if not mailboxes:
flash("You must select at least 1 mailbox", "warning")
return redirect(request.url)
LOG.d(
"transfer alias %s from %s to %s with %s with token %s",
alias,
alias.user,
current_user,
mailboxes,
token,
)
transfer_alias(alias, current_user, mailboxes)
# reset transfer token
alias.transfer_token = None
alias.transfer_token_expiration = None
Session.commit()
flash(f"You are now owner of {alias.email}", "success")
return redirect(url_for("dashboard.index", highlight_alias_id=alias.id))
return render_template(
"dashboard/alias_transfer_receive.html",
alias=alias,
mailboxes=mailboxes,
) | URL has ?alias_id=signed_alias_id |
180,737 | from app.dashboard.base import dashboard_bp
from flask_login import login_required, current_user
from app.alias_utils import alias_export_csv
from app.dashboard.views.enter_sudo import sudo_required
from app.extensions import limiter
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
def alias_export_route():
return alias_export_csv(current_user) | null |
180,738 | from smtplib import SMTPRecipientsRefused
from email_validator import validate_email, EmailNotValidError
from flask import render_template, request, redirect, url_for, flash
from flask_login import login_required, current_user
from flask_wtf import FlaskForm
from itsdangerous import TimestampSigner
from wtforms import validators
from wtforms.fields.html5 import EmailField
from app.config import ENFORCE_SPF, MAILBOX_SECRET
from app.config import URL
from app.dashboard.base import dashboard_bp
from app.db import Session
from app.email_utils import email_can_be_used_as_mailbox
from app.email_utils import mailbox_already_used, render, send_email
from app.log import LOG
from app.models import Alias, AuthorizedAddress
from app.models import Mailbox
from app.pgp_utils import PGPException, load_public_key_and_check
from app.utils import sanitize_email, CSRFValidationForm
class ChangeEmailForm(FlaskForm):
email = EmailField(
"email", validators=[validators.DataRequired(), validators.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"]
ENFORCE_SPF = "ENFORCE_SPF" in os.environ
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 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 AuthorizedAddress(Base, ModelMixin):
"""Authorize other addresses to send emails from aliases that are owned by a mailbox"""
__tablename__ = "authorized_address"
user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False)
mailbox_id = sa.Column(
sa.ForeignKey(Mailbox.id, ondelete="cascade"), nullable=False
)
email = sa.Column(sa.String(256), nullable=False)
__table_args__ = (
sa.UniqueConstraint("mailbox_id", "email", name="uq_authorize_address"),
)
mailbox = orm.relationship(Mailbox, backref="authorized_addresses")
def __repr__(self):
return f"<AuthorizedAddress {self.id} {self.email} {self.mailbox_id}>"
class PGPException(Exception):
pass
def load_public_key_and_check(public_key: str) -> str:
"""Same as load_public_key but will try an encryption using the new key.
If the encryption fails, remove the newly created fingerprint.
Return the fingerprint
"""
try:
import_result = gpg.import_keys(public_key)
fingerprint = import_result.fingerprints[0]
except Exception as e:
raise PGPException("Cannot load key") from e
else:
dummy_data = BytesIO(b"test")
try:
encrypt_file(dummy_data, fingerprint)
except Exception as e:
LOG.w(
"Cannot encrypt using the imported key %s %s", fingerprint, public_key
)
# remove the fingerprint
gpg.delete_keys([fingerprint])
raise PGPException("Encryption fails with the key") from e
return fingerprint
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", "")
class CSRFValidationForm(FlaskForm):
pass
def mailbox_detail_route(mailbox_id):
mailbox: Mailbox = Mailbox.get(mailbox_id)
if not mailbox or mailbox.user_id != current_user.id:
flash("You cannot see this page", "warning")
return redirect(url_for("dashboard.index"))
change_email_form = ChangeEmailForm()
csrf_form = CSRFValidationForm()
if mailbox.new_email:
pending_email = mailbox.new_email
else:
pending_email = None
if request.method == "POST":
if not csrf_form.validate():
flash("Invalid request", "warning")
return redirect(request.url)
if (
request.form.get("form-name") == "update-email"
and change_email_form.validate_on_submit()
):
new_email = sanitize_email(change_email_form.email.data)
if new_email != mailbox.email and not pending_email:
# check if this email is not already used
if mailbox_already_used(new_email, current_user) or Alias.get_by(
email=new_email
):
flash(f"Email {new_email} already used", "error")
elif not email_can_be_used_as_mailbox(new_email):
flash("You cannot use this email address as your mailbox", "error")
else:
mailbox.new_email = new_email
Session.commit()
try:
verify_mailbox_change(current_user, mailbox, new_email)
except SMTPRecipientsRefused:
flash(
f"Incorrect mailbox, please recheck {mailbox.email}",
"error",
)
else:
flash(
f"You are going to receive an email to confirm {new_email}.",
"success",
)
return redirect(
url_for("dashboard.mailbox_detail_route", mailbox_id=mailbox_id)
)
elif request.form.get("form-name") == "force-spf":
if not ENFORCE_SPF:
flash("SPF enforcement globally not enabled", "error")
return redirect(url_for("dashboard.index"))
mailbox.force_spf = (
True if request.form.get("spf-status") == "on" else False
)
Session.commit()
flash(
"SPF enforcement was " + "enabled"
if request.form.get("spf-status")
else "disabled" + " successfully",
"success",
)
return redirect(
url_for("dashboard.mailbox_detail_route", mailbox_id=mailbox_id)
)
elif request.form.get("form-name") == "add-authorized-address":
address = sanitize_email(request.form.get("email"))
try:
validate_email(
address, check_deliverability=False, allow_smtputf8=False
).domain
except EmailNotValidError:
flash(f"invalid {address}", "error")
else:
if AuthorizedAddress.get_by(mailbox_id=mailbox.id, email=address):
flash(f"{address} already added", "error")
else:
AuthorizedAddress.create(
user_id=current_user.id,
mailbox_id=mailbox.id,
email=address,
commit=True,
)
flash(f"{address} added as authorized address", "success")
return redirect(
url_for("dashboard.mailbox_detail_route", mailbox_id=mailbox_id)
)
elif request.form.get("form-name") == "delete-authorized-address":
authorized_address_id = request.form.get("authorized-address-id")
authorized_address: AuthorizedAddress = AuthorizedAddress.get(
authorized_address_id
)
if not authorized_address or authorized_address.mailbox_id != mailbox.id:
flash("Unknown error. Refresh the page", "warning")
else:
address = authorized_address.email
AuthorizedAddress.delete(authorized_address_id)
Session.commit()
flash(f"{address} has been deleted", "success")
return redirect(
url_for("dashboard.mailbox_detail_route", mailbox_id=mailbox_id)
)
elif request.form.get("form-name") == "pgp":
if request.form.get("action") == "save":
if not current_user.is_premium():
flash("Only premium plan can add PGP Key", "warning")
return redirect(
url_for("dashboard.mailbox_detail_route", mailbox_id=mailbox_id)
)
if mailbox.is_proton():
flash(
"Enabling PGP for a Proton Mail mailbox is redundant and does not add any security benefit",
"info",
)
return redirect(
url_for("dashboard.mailbox_detail_route", mailbox_id=mailbox_id)
)
mailbox.pgp_public_key = request.form.get("pgp")
try:
mailbox.pgp_finger_print = load_public_key_and_check(
mailbox.pgp_public_key
)
except PGPException:
flash("Cannot add the public key, please verify it", "error")
else:
Session.commit()
flash("Your PGP public key is saved successfully", "success")
return redirect(
url_for("dashboard.mailbox_detail_route", mailbox_id=mailbox_id)
)
elif request.form.get("action") == "remove":
# Free user can decide to remove their added PGP key
mailbox.pgp_public_key = None
mailbox.pgp_finger_print = None
mailbox.disable_pgp = False
Session.commit()
flash("Your PGP public key is removed successfully", "success")
return redirect(
url_for("dashboard.mailbox_detail_route", mailbox_id=mailbox_id)
)
elif request.form.get("form-name") == "toggle-pgp":
if request.form.get("pgp-enabled") == "on":
mailbox.disable_pgp = False
flash(f"PGP is enabled on {mailbox.email}", "success")
else:
mailbox.disable_pgp = True
flash(f"PGP is disabled on {mailbox.email}", "info")
Session.commit()
return redirect(
url_for("dashboard.mailbox_detail_route", mailbox_id=mailbox_id)
)
elif request.form.get("form-name") == "generic-subject":
if request.form.get("action") == "save":
mailbox.generic_subject = request.form.get("generic-subject")
Session.commit()
flash("Generic subject is enabled", "success")
return redirect(
url_for("dashboard.mailbox_detail_route", mailbox_id=mailbox_id)
)
elif request.form.get("action") == "remove":
mailbox.generic_subject = None
Session.commit()
flash("Generic subject is disabled", "success")
return redirect(
url_for("dashboard.mailbox_detail_route", mailbox_id=mailbox_id)
)
spf_available = ENFORCE_SPF
return render_template("dashboard/mailbox_detail.html", **locals()) | null |
180,739 | from smtplib import SMTPRecipientsRefused
from email_validator import validate_email, EmailNotValidError
from flask import render_template, request, redirect, url_for, flash
from flask_login import login_required, current_user
from flask_wtf import FlaskForm
from itsdangerous import TimestampSigner
from wtforms import validators
from wtforms.fields.html5 import EmailField
from app.config import ENFORCE_SPF, MAILBOX_SECRET
from app.config import URL
from app.dashboard.base import dashboard_bp
from app.db import Session
from app.email_utils import email_can_be_used_as_mailbox
from app.email_utils import mailbox_already_used, render, send_email
from app.log import LOG
from app.models import Alias, AuthorizedAddress
from app.models import Mailbox
from app.pgp_utils import PGPException, load_public_key_and_check
from app.utils import sanitize_email, CSRFValidationForm
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
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 cancel_mailbox_change_route(mailbox_id):
mailbox = Mailbox.get(mailbox_id)
if not mailbox or mailbox.user_id != current_user.id:
flash("You cannot see this page", "warning")
return redirect(url_for("dashboard.index"))
if mailbox.new_email:
mailbox.new_email = None
Session.commit()
flash("Your mailbox change is cancelled", "success")
return redirect(
url_for("dashboard.mailbox_detail_route", mailbox_id=mailbox_id)
)
else:
flash("You have no pending mailbox change", "warning")
return redirect(
url_for("dashboard.mailbox_detail_route", mailbox_id=mailbox_id)
) | null |
180,740 | from smtplib import SMTPRecipientsRefused
from email_validator import validate_email, EmailNotValidError
from flask import render_template, request, redirect, url_for, flash
from flask_login import login_required, current_user
from flask_wtf import FlaskForm
from itsdangerous import TimestampSigner
from wtforms import validators
from wtforms.fields.html5 import EmailField
from app.config import ENFORCE_SPF, MAILBOX_SECRET
from app.config import URL
from app.dashboard.base import dashboard_bp
from app.db import Session
from app.email_utils import email_can_be_used_as_mailbox
from app.email_utils import mailbox_already_used, render, send_email
from app.log import LOG
from app.models import Alias, AuthorizedAddress
from app.models import Mailbox
from app.pgp_utils import PGPException, load_public_key_and_check
from app.utils import sanitize_email, CSRFValidationForm
MAILBOX_SECRET = FLASK_SECRET + "mailbox"
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
LOG = _get_logger("SL")
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 mailbox_confirm_change_route():
s = TimestampSigner(MAILBOX_SECRET)
signed_mailbox_id = request.args.get("mailbox_id")
try:
mailbox_id = int(s.unsign(signed_mailbox_id, max_age=900))
except Exception:
flash("Invalid link", "error")
return redirect(url_for("dashboard.index"))
else:
mailbox = Mailbox.get(mailbox_id)
# new_email can be None if user cancels change in the meantime
if mailbox and mailbox.new_email:
user = mailbox.user
if Mailbox.get_by(email=mailbox.new_email, user_id=user.id):
flash(f"{mailbox.new_email} is already used", "error")
return redirect(
url_for("dashboard.mailbox_detail_route", mailbox_id=mailbox.id)
)
mailbox.email = mailbox.new_email
mailbox.new_email = None
# mark mailbox as verified if the change request is sent from an unverified mailbox
mailbox.verified = True
Session.commit()
LOG.d("Mailbox change %s is verified", mailbox)
flash(f"The {mailbox.email} is updated", "success")
return redirect(
url_for("dashboard.mailbox_detail_route", mailbox_id=mailbox.id)
)
else:
flash("Invalid link", "error")
return redirect(url_for("dashboard.index")) | null |
180,741 | import arrow
from flask import (
render_template,
request,
redirect,
url_for,
flash,
)
from flask_login import login_required, current_user
from app import email_utils
from app.config import (
URL,
FIRST_ALIAS_DOMAIN,
ALIAS_RANDOM_SUFFIX_LENGTH,
CONNECT_WITH_PROTON,
)
from app.dashboard.base import dashboard_bp
from app.dashboard.views.enter_sudo import sudo_required
from app.dashboard.views.mailbox_detail import ChangeEmailForm
from app.db import Session
from app.email_utils import (
email_can_be_used_as_mailbox,
personal_email_already_used,
)
from app.extensions import limiter
from app.jobs.export_user_data_job import ExportUserDataJob
from app.log import LOG
from app.models import (
BlockBehaviourEnum,
PlanEnum,
ResetPasswordCode,
EmailChange,
User,
Alias,
AliasGeneratorEnum,
SenderFormatEnum,
UnsubscribeBehaviourEnum,
)
from app.proton.utils import perform_proton_account_unlink
from app.utils import (
random_string,
CSRFValidationForm,
canonicalize_email,
)
def send_reset_password_email(user):
"""
generate a new ResetPasswordCode and send it over email to user
"""
# the activation code is valid for 1h
reset_password_code = ResetPasswordCode.create(
user_id=user.id, code=random_string(60)
)
Session.commit()
reset_password_link = f"{URL}/auth/reset_password?code={reset_password_code.code}"
email_utils.send_reset_password_email(user.email, reset_password_link)
def send_change_email_confirmation(user: User, email_change: EmailChange):
"""
send confirmation email to the new email address
"""
link = f"{URL}/auth/change_email?code={email_change.code}"
email_utils.send_change_email(email_change.new_email, user.email, link)
FIRST_ALIAS_DOMAIN = os.environ.get("FIRST_ALIAS_DOMAIN") or EMAIL_DOMAIN
CONNECT_WITH_PROTON = "CONNECT_WITH_PROTON" in os.environ
ALIAS_RANDOM_SUFFIX_LENGTH = int(os.environ.get("ALIAS_RAND_SUFFIX_LENGTH", 5))
class ChangeEmailForm(FlaskForm):
email = EmailField(
"email", validators=[validators.DataRequired(), validators.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 personal_email_already_used(email_address: str) -> bool:
"""test if an email can be used as user email"""
if User.get_by(email=email_address):
return True
return False
class ExportUserDataJob:
REMOVE_FIELDS = {
"User": ("otp_secret", "password"),
"Alias": ("ts_vector", "transfer_token", "hibp_last_check"),
"CustomDomain": ("ownership_txt_token",),
}
def __init__(self, user: User):
self._user: User = user
def _get_paginated_model(self, model_class, page_size=50) -> List:
objects = []
page = 0
db_objects = []
while page == 0 or len(db_objects) == page_size:
db_objects = (
Session.query(model_class)
.filter(model_class.user_id == self._user.id)
.order_by(model_class.id)
.limit(page_size)
.offset(page * page_size)
.all()
)
objects.extend(db_objects)
page += 1
return objects
def _get_aliases(self) -> List[Alias]:
return self._get_paginated_model(Alias)
def _get_mailboxes(self) -> List[Mailbox]:
return self._get_paginated_model(Mailbox)
def _get_contacts(self) -> List[Contact]:
return self._get_paginated_model(Contact)
def _get_directories(self) -> List[Directory]:
return self._get_paginated_model(Directory)
def _get_email_logs(self) -> List[EmailLog]:
return self._get_paginated_model(EmailLog)
def _get_domains(self) -> List[CustomDomain]:
return self._get_paginated_model(CustomDomain)
def _get_refused_emails(self) -> List[RefusedEmail]:
return self._get_paginated_model(RefusedEmail)
def _model_to_dict(cls, object: Base) -> Dict:
data = {}
fields_to_filter = cls.REMOVE_FIELDS.get(object.__class__.__name__, ())
for column in object.__table__.columns:
if column.name in fields_to_filter:
continue
value = getattr(object, column.name)
if isinstance(value, arrow.Arrow):
value = value.isoformat()
if issubclass(value.__class__, EnumE):
value = value.value
data[column.name] = value
return data
def _build_zip(self) -> BytesIO:
memfile = BytesIO()
with zipfile.ZipFile(memfile, "w", zipfile.ZIP_DEFLATED) as zf:
zf.writestr(
"user.json", json.dumps(ExportUserDataJob._model_to_dict(self._user))
)
for model_name, get_models in [
("aliases", self._get_aliases),
("mailboxes", self._get_mailboxes),
("contacts", self._get_contacts),
("directories", self._get_directories),
("domains", self._get_domains),
("email_logs", self._get_email_logs),
# not include RefusedEmail as they are not usable by user and are automatically deleted
# ("refused_emails", self._get_refused_emails),
]:
model_objs = get_models()
data = json.dumps(
[
ExportUserDataJob._model_to_dict(model_obj)
for model_obj in model_objs
]
)
zf.writestr(f"{model_name}.json", data)
memfile.seek(0)
return memfile
def run(self):
zipped_contents = self._build_zip()
to_email = self._user.email
msg = MIMEMultipart()
msg[headers.SUBJECT] = "Your SimpleLogin data"
msg[headers.FROM] = f'"SimpleLogin (noreply)" <{config.NOREPLY}>'
msg[headers.TO] = to_email
msg.attach(MIMEText(render("transactional/user-report.html"), "html"))
attachment = MIMEApplication(zipped_contents.read())
attachment.add_header(
"Content-Disposition", "attachment", filename="user_report.zip"
)
attachment.add_header("Content-Type", "application/zip")
msg.attach(attachment)
# add DKIM
email_domain = config.NOREPLY[config.NOREPLY.find("@") + 1 :]
add_dkim_signature(msg, email_domain)
transaction = TransactionalEmail.create(email=to_email, commit=True)
sl_sendmail(
generate_verp_email(
VerpType.transactional,
transaction.id,
get_email_domain_part(config.NOREPLY),
),
to_email,
msg,
ignore_smtp_error=False,
)
def create_from_job(job: Job) -> Optional[ExportUserDataJob]:
user = User.get(job.payload["user_id"])
if not user:
return None
return ExportUserDataJob(user)
def store_job_in_db(self) -> Optional[Job]:
jobs_in_db = (
Session.query(Job)
.filter(
Job.name == config.JOB_SEND_USER_REPORT,
Job.payload.op("->")("user_id").cast(sqlalchemy.TEXT)
== str(self._user.id),
Job.taken.is_(False),
)
.count()
)
if jobs_in_db > 0:
return None
return Job.create(
name=config.JOB_SEND_USER_REPORT,
payload={"user_id": self._user.id},
run_at=arrow.now(),
commit=True,
)
LOG = _get_logger("SL")
class PlanEnum(EnumE):
monthly = 2
yearly = 3
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 BlockBehaviourEnum(EnumE):
return_2xx = 0
return_5xx = 1
class UnsubscribeBehaviourEnum(EnumE):
DisableAlias = 0
BlockContact = 1
PreserveOriginal = 2
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 EmailChange(Base, ModelMixin):
"""Used when user wants to update their email"""
__tablename__ = "email_change"
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"),
nullable=False,
unique=True,
index=True,
)
new_email = sa.Column(sa.String(256), unique=True, nullable=False)
code = sa.Column(sa.String(128), unique=True, nullable=False)
expired = sa.Column(ArrowType, nullable=False, default=_expiration_12h)
user = orm.relationship(User)
def is_expired(self):
return self.expired < arrow.now()
def __repr__(self):
return f"<EmailChange {self.id} {self.new_email} {self.user_id}>"
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))
def canonicalize_email(email_address: str) -> str:
email_address = sanitize_email(email_address)
parts = email_address.split("@")
if len(parts) != 2:
return ""
domain = parts[1]
if domain not in ("gmail.com", "protonmail.com", "proton.me", "pm.me"):
return email_address
first = parts[0]
try:
plus_idx = first.index("+")
first = first[:plus_idx]
except ValueError:
# No + in the email
pass
first = first.replace(".", "")
return f"{first}@{parts[1]}".lower().strip()
class CSRFValidationForm(FlaskForm):
pass
def account_setting():
change_email_form = ChangeEmailForm()
csrf_form = CSRFValidationForm()
email_change = EmailChange.get_by(user_id=current_user.id)
if email_change:
pending_email = email_change.new_email
else:
pending_email = None
if request.method == "POST":
if not csrf_form.validate():
flash("Invalid request", "warning")
return redirect(url_for("dashboard.setting"))
if request.form.get("form-name") == "update-email":
if change_email_form.validate():
# whether user can proceed with the email update
new_email_valid = True
new_email = canonicalize_email(change_email_form.email.data)
if new_email != current_user.email and not pending_email:
# check if this email is not already used
if personal_email_already_used(new_email) or Alias.get_by(
email=new_email
):
flash(f"Email {new_email} already used", "error")
new_email_valid = False
elif not email_can_be_used_as_mailbox(new_email):
flash(
"You cannot use this email address as your personal inbox.",
"error",
)
new_email_valid = False
# a pending email change with the same email exists from another user
elif EmailChange.get_by(new_email=new_email):
other_email_change: EmailChange = EmailChange.get_by(
new_email=new_email
)
LOG.w(
"Another user has a pending %s with the same email address. Current user:%s",
other_email_change,
current_user,
)
if other_email_change.is_expired():
LOG.d(
"delete the expired email change %s", other_email_change
)
EmailChange.delete(other_email_change.id)
Session.commit()
else:
flash(
"You cannot use this email address as your personal inbox.",
"error",
)
new_email_valid = False
if new_email_valid:
email_change = EmailChange.create(
user_id=current_user.id,
code=random_string(
60
), # todo: make sure the code is unique
new_email=new_email,
)
Session.commit()
send_change_email_confirmation(current_user, email_change)
flash(
"A confirmation email is on the way, please check your inbox",
"success",
)
return redirect(url_for("dashboard.account_setting"))
elif request.form.get("form-name") == "change-password":
flash(
"You are going to receive an email containing instructions to change your password",
"success",
)
send_reset_password_email(current_user)
return redirect(url_for("dashboard.account_setting"))
elif request.form.get("form-name") == "send-full-user-report":
if ExportUserDataJob(current_user).store_job_in_db():
flash(
"You will receive your SimpleLogin data via email shortly",
"success",
)
else:
flash("An export of your data is currently in progress", "error")
partner_sub = None
partner_name = None
return render_template(
"dashboard/account_setting.html",
csrf_form=csrf_form,
PlanEnum=PlanEnum,
SenderFormatEnum=SenderFormatEnum,
BlockBehaviourEnum=BlockBehaviourEnum,
change_email_form=change_email_form,
pending_email=pending_email,
AliasGeneratorEnum=AliasGeneratorEnum,
UnsubscribeBehaviourEnum=UnsubscribeBehaviourEnum,
partner_sub=partner_sub,
partner_name=partner_name,
FIRST_ALIAS_DOMAIN=FIRST_ALIAS_DOMAIN,
ALIAS_RAND_SUFFIX_LENGTH=ALIAS_RANDOM_SUFFIX_LENGTH,
connect_with_proton=CONNECT_WITH_PROTON,
) | null |
180,742 | import arrow
from flask import (
render_template,
request,
redirect,
url_for,
flash,
)
from flask_login import login_required, current_user
from app import email_utils
from app.config import (
URL,
FIRST_ALIAS_DOMAIN,
ALIAS_RANDOM_SUFFIX_LENGTH,
CONNECT_WITH_PROTON,
)
from app.dashboard.base import dashboard_bp
from app.dashboard.views.enter_sudo import sudo_required
from app.dashboard.views.mailbox_detail import ChangeEmailForm
from app.db import Session
from app.email_utils import (
email_can_be_used_as_mailbox,
personal_email_already_used,
)
from app.extensions import limiter
from app.jobs.export_user_data_job import ExportUserDataJob
from app.log import LOG
from app.models import (
BlockBehaviourEnum,
PlanEnum,
ResetPasswordCode,
EmailChange,
User,
Alias,
AliasGeneratorEnum,
SenderFormatEnum,
UnsubscribeBehaviourEnum,
)
from app.proton.utils import perform_proton_account_unlink
from app.utils import (
random_string,
CSRFValidationForm,
canonicalize_email,
)
def send_change_email_confirmation(user: User, email_change: EmailChange):
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
class EmailChange(Base, ModelMixin):
def is_expired(self):
def __repr__(self):
class CSRFValidationForm(FlaskForm):
def resend_email_change():
form = CSRFValidationForm()
if not form.validate():
flash("Invalid request. Please try again", "warning")
return redirect(url_for("dashboard.setting"))
email_change = EmailChange.get_by(user_id=current_user.id)
if email_change:
# extend email change expiration
email_change.expired = arrow.now().shift(hours=12)
Session.commit()
send_change_email_confirmation(current_user, email_change)
flash("A confirmation email is on the way, please check your inbox", "success")
return redirect(url_for("dashboard.setting"))
else:
flash(
"You have no pending email change. Redirect back to Setting page", "warning"
)
return redirect(url_for("dashboard.setting")) | null |
180,743 | import arrow
from flask import (
render_template,
request,
redirect,
url_for,
flash,
)
from flask_login import login_required, current_user
from app import email_utils
from app.config import (
URL,
FIRST_ALIAS_DOMAIN,
ALIAS_RANDOM_SUFFIX_LENGTH,
CONNECT_WITH_PROTON,
)
from app.dashboard.base import dashboard_bp
from app.dashboard.views.enter_sudo import sudo_required
from app.dashboard.views.mailbox_detail import ChangeEmailForm
from app.db import Session
from app.email_utils import (
email_can_be_used_as_mailbox,
personal_email_already_used,
)
from app.extensions import limiter
from app.jobs.export_user_data_job import ExportUserDataJob
from app.log import LOG
from app.models import (
BlockBehaviourEnum,
PlanEnum,
ResetPasswordCode,
EmailChange,
User,
Alias,
AliasGeneratorEnum,
SenderFormatEnum,
UnsubscribeBehaviourEnum,
)
from app.proton.utils import perform_proton_account_unlink
from app.utils import (
random_string,
CSRFValidationForm,
canonicalize_email,
)
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
class EmailChange(Base, ModelMixin):
"""Used when user wants to update their email"""
__tablename__ = "email_change"
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"),
nullable=False,
unique=True,
index=True,
)
new_email = sa.Column(sa.String(256), unique=True, nullable=False)
code = sa.Column(sa.String(128), unique=True, nullable=False)
expired = sa.Column(ArrowType, nullable=False, default=_expiration_12h)
user = orm.relationship(User)
def is_expired(self):
return self.expired < arrow.now()
def __repr__(self):
return f"<EmailChange {self.id} {self.new_email} {self.user_id}>"
class CSRFValidationForm(FlaskForm):
pass
def cancel_email_change():
form = CSRFValidationForm()
if not form.validate():
flash("Invalid request. Please try again", "warning")
return redirect(url_for("dashboard.setting"))
email_change = EmailChange.get_by(user_id=current_user.id)
if email_change:
EmailChange.delete(email_change.id)
Session.commit()
flash("Your email change is cancelled", "success")
return redirect(url_for("dashboard.setting"))
else:
flash(
"You have no pending email change. Redirect back to Setting page", "warning"
)
return redirect(url_for("dashboard.setting")) | null |
180,744 | import arrow
from flask import (
render_template,
request,
redirect,
url_for,
flash,
)
from flask_login import login_required, current_user
from app import email_utils
from app.config import (
URL,
FIRST_ALIAS_DOMAIN,
ALIAS_RANDOM_SUFFIX_LENGTH,
CONNECT_WITH_PROTON,
)
from app.dashboard.base import dashboard_bp
from app.dashboard.views.enter_sudo import sudo_required
from app.dashboard.views.mailbox_detail import ChangeEmailForm
from app.db import Session
from app.email_utils import (
email_can_be_used_as_mailbox,
personal_email_already_used,
)
from app.extensions import limiter
from app.jobs.export_user_data_job import ExportUserDataJob
from app.log import LOG
from app.models import (
BlockBehaviourEnum,
PlanEnum,
ResetPasswordCode,
EmailChange,
User,
Alias,
AliasGeneratorEnum,
SenderFormatEnum,
UnsubscribeBehaviourEnum,
)
from app.proton.utils import perform_proton_account_unlink
from app.utils import (
random_string,
CSRFValidationForm,
canonicalize_email,
)
def perform_proton_account_unlink(current_user: User):
proton_partner = get_proton_partner()
partner_user = PartnerUser.get_by(
user_id=current_user.id, partner_id=proton_partner.id
)
if partner_user is not None:
PartnerUser.delete(partner_user.id)
Session.commit()
agent.record_custom_event("AccountUnlinked", {"partner": proton_partner.name})
class CSRFValidationForm(FlaskForm):
pass
def unlink_proton_account():
csrf_form = CSRFValidationForm()
if not csrf_form.validate():
flash("Invalid request", "warning")
return redirect(url_for("dashboard.setting"))
perform_proton_account_unlink(current_user)
flash("Your Proton account has been unlinked", "success")
return redirect(url_for("dashboard.setting")) | null |
180,745 | import re
from flask import render_template, request, redirect, url_for, flash
from flask_login import login_required, current_user
from flask_wtf import FlaskForm
from wtforms import StringField, validators
from app import parallel_limiter
from app.config import MAX_NB_SUBDOMAIN
from app.dashboard.base import dashboard_bp
from app.errors import SubdomainInTrashError
from app.log import LOG
from app.models import CustomDomain, Mailbox, SLDomain
_SUBDOMAIN_PATTERN = r"[0-9a-z-]{1,}"
class NewSubdomainForm(FlaskForm):
domain = StringField(
"domain", validators=[validators.DataRequired(), validators.Length(max=64)]
)
subdomain = StringField(
"subdomain", validators=[validators.DataRequired(), validators.Length(max=64)]
)
MAX_NB_SUBDOMAIN = 5
class SubdomainInTrashError(SLException):
"""raised when a subdomain is deleted before"""
pass
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}>"
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 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'}"
def subdomain_route():
if not current_user.subdomain_is_available():
flash("Unknown error, redirect to the home page", "error")
return redirect(url_for("dashboard.index"))
sl_domains = SLDomain.filter_by(can_use_subdomain=True).all()
subdomains = CustomDomain.filter_by(
user_id=current_user.id, is_sl_subdomain=True
).all()
errors = {}
new_subdomain_form = NewSubdomainForm()
if request.method == "POST":
if request.form.get("form-name") == "create":
if not new_subdomain_form.validate():
flash("Invalid new subdomain", "warning")
return redirect(url_for("dashboard.subdomain_route"))
if not current_user.is_premium():
flash("Only premium plan can add subdomain", "warning")
return redirect(request.url)
if current_user.subdomain_quota <= 0:
flash(
f"You can't create more than {MAX_NB_SUBDOMAIN} subdomains", "error"
)
return redirect(request.url)
subdomain = new_subdomain_form.subdomain.data.lower().strip()
domain = new_subdomain_form.domain.data.lower().strip()
if len(subdomain) < 3:
flash("Subdomain must have at least 3 characters", "error")
return redirect(request.url)
if re.fullmatch(_SUBDOMAIN_PATTERN, subdomain) is None:
flash(
"Subdomain can only contain lowercase letters, numbers and dashes (-)",
"error",
)
return redirect(request.url)
if subdomain.endswith("-"):
flash("Subdomain can't end with dash (-)", "error")
return redirect(request.url)
if domain not in [sl_domain.domain for sl_domain in sl_domains]:
LOG.e("Domain %s is tampered by %s", domain, current_user)
flash("Unknown error, refresh the page", "error")
return redirect(request.url)
full_domain = f"{subdomain}.{domain}"
if CustomDomain.get_by(domain=full_domain):
flash(f"{full_domain} already used", "error")
elif Mailbox.filter(
Mailbox.verified.is_(True),
Mailbox.email.endswith(f"@{full_domain}"),
).first():
flash(f"{full_domain} already used in a SimpleLogin mailbox", "error")
else:
try:
new_custom_domain = CustomDomain.create(
is_sl_subdomain=True,
catch_all=True, # by default catch-all is enabled
domain=full_domain,
user_id=current_user.id,
verified=True,
dkim_verified=False, # wildcard DNS does not work for DKIM
spf_verified=True,
dmarc_verified=False, # wildcard DNS does not work for DMARC
ownership_verified=True,
commit=True,
)
except SubdomainInTrashError:
flash(
f"{full_domain} has been used before and cannot be reused",
"error",
)
else:
flash(
f"New subdomain {new_custom_domain.domain} is created",
"success",
)
return redirect(
url_for(
"dashboard.domain_detail",
custom_domain_id=new_custom_domain.id,
)
)
return render_template(
"dashboard/subdomain.html",
sl_domains=sl_domains,
errors=errors,
subdomains=subdomains,
new_subdomain_form=new_subdomain_form,
) | null |
180,746 | from dataclasses import dataclass
from operator import or_
from flask import render_template, request, redirect, flash
from flask import url_for
from flask_login import login_required, current_user
from flask_wtf import FlaskForm
from sqlalchemy import and_, func, case
from wtforms import StringField, validators, ValidationError
from app import config, parallel_limiter
from app.dashboard.base import dashboard_bp
from app.db import Session
from app.email_utils import (
generate_reply_email,
parse_full_address,
)
from app.email_validation import is_valid_email
from app.errors import (
CannotCreateContactForReverseAlias,
ErrContactErrorUpgradeNeeded,
ErrAddressInvalid,
ErrContactAlreadyExists,
)
from app.log import LOG
from app.models import Alias, Contact, EmailLog, User
from app.utils import sanitize_email, CSRFValidationForm
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
The provided code snippet includes necessary dependencies for implementing the `email_validator` function. Write a Python function `def email_validator()` to solve the following problem:
validate email address. Handle both only email and email with name: - ab@cd.com - AB CD <ab@cd.com>
Here is the function:
def email_validator():
"""validate email address. Handle both only email and email with name:
- ab@cd.com
- AB CD <ab@cd.com>
"""
message = "Invalid email format. Email must be either email@example.com or *First Last <email@example.com>*"
def _check(form, field):
email = field.data
email = email.strip()
email_part = email
if "<" in email and ">" in email:
if email.find("<") + 1 < email.find(">"):
email_part = email[email.find("<") + 1 : email.find(">")].strip()
if not is_valid_email(email_part):
raise ValidationError(message)
return _check | validate email address. Handle both only email and email with name: - ab@cd.com - AB CD <ab@cd.com> |
180,747 | from dataclasses import dataclass
from operator import or_
from flask import render_template, request, redirect, flash
from flask import url_for
from flask_login import login_required, current_user
from flask_wtf import FlaskForm
from sqlalchemy import and_, func, case
from wtforms import StringField, validators, ValidationError
from app import config, parallel_limiter
from app.dashboard.base import dashboard_bp
from app.db import Session
from app.email_utils import (
generate_reply_email,
parse_full_address,
)
from app.email_validation import is_valid_email
from app.errors import (
CannotCreateContactForReverseAlias,
ErrContactErrorUpgradeNeeded,
ErrAddressInvalid,
ErrContactAlreadyExists,
)
from app.log import LOG
from app.models import Alias, Contact, EmailLog, User
from app.utils import sanitize_email, CSRFValidationForm
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 NewContactForm(FlaskForm):
email = StringField(
"Email", validators=[validators.DataRequired(), email_validator()]
)
def get_contact_infos(
alias: Alias, page=0, contact_id=None, query: str = ""
) -> [ContactInfo]:
"""if contact_id is set, only return the contact info for this contact"""
sub = (
Session.query(
Contact.id,
func.sum(case([(EmailLog.is_reply, 1)], else_=0)).label("nb_reply"),
func.sum(
case(
[
(
and_(
EmailLog.is_reply.is_(False),
EmailLog.blocked.is_(False),
),
1,
)
],
else_=0,
)
).label("nb_forward"),
func.max(EmailLog.created_at).label("max_email_log_created_at"),
)
.join(
EmailLog,
EmailLog.contact_id == Contact.id,
isouter=True,
)
.filter(Contact.alias_id == alias.id)
.group_by(Contact.id)
.subquery()
)
q = (
Session.query(
Contact,
EmailLog,
sub.c.nb_reply,
sub.c.nb_forward,
)
.join(
EmailLog,
EmailLog.contact_id == Contact.id,
isouter=True,
)
.filter(Contact.alias_id == alias.id)
.filter(Contact.id == sub.c.id)
.filter(
or_(
EmailLog.created_at == sub.c.max_email_log_created_at,
# no email log yet for this contact
sub.c.max_email_log_created_at.is_(None),
)
)
)
if query:
q = q.filter(
or_(
Contact.website_email.ilike(f"%{query}%"),
Contact.name.ilike(f"%{query}%"),
)
)
if contact_id:
q = q.filter(Contact.id == contact_id)
latest_activity = case(
[
(EmailLog.created_at > Contact.created_at, EmailLog.created_at),
(EmailLog.created_at < Contact.created_at, Contact.created_at),
],
else_=Contact.created_at,
)
q = (
q.order_by(latest_activity.desc())
.limit(config.PAGE_LIMIT)
.offset(page * config.PAGE_LIMIT)
)
ret = []
for contact, latest_email_log, nb_reply, nb_forward in q:
contact_info = ContactInfo(
contact=contact,
nb_forward=nb_forward,
nb_reply=nb_reply,
latest_email_log=latest_email_log,
)
ret.append(contact_info)
return ret
def delete_contact(alias: Alias, contact_id: int):
contact = Contact.get(contact_id)
if not contact:
flash("Unknown error. Refresh the page", "warning")
elif contact.alias_id != alias.id:
flash("You cannot delete reverse-alias", "warning")
else:
delete_contact_email = contact.website_email
Contact.delete(contact_id)
Session.commit()
flash(f"Reverse-alias for {delete_contact_email} has been deleted", "success")
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}>"
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 CSRFValidationForm(FlaskForm):
pass
def alias_contact_manager(alias_id):
highlight_contact_id = None
if request.args.get("highlight_contact_id"):
try:
highlight_contact_id = int(request.args.get("highlight_contact_id"))
except ValueError:
flash("Invalid contact id", "error")
return redirect(url_for("dashboard.index"))
alias = Alias.get(alias_id)
page = 0
if request.args.get("page"):
page = int(request.args.get("page"))
query = request.args.get("query") or ""
# sanity check
if not alias:
flash("You do not have access to this page", "warning")
return redirect(url_for("dashboard.index"))
if alias.user_id != current_user.id:
flash("You do not have access to this page", "warning")
return redirect(url_for("dashboard.index"))
new_contact_form = NewContactForm()
csrf_form = CSRFValidationForm()
if request.method == "POST":
if not csrf_form.validate():
flash("Invalid request", "warning")
return redirect(request.url)
if request.form.get("form-name") == "create":
if new_contact_form.validate():
contact_address = new_contact_form.email.data.strip()
try:
contact = create_contact(current_user, alias, contact_address)
except (
ErrContactErrorUpgradeNeeded,
ErrAddressInvalid,
ErrContactAlreadyExists,
CannotCreateContactForReverseAlias,
) as excp:
flash(excp.error_for_user(), "error")
return redirect(request.url)
flash(f"Reverse alias for {contact_address} is created", "success")
return redirect(
url_for(
"dashboard.alias_contact_manager",
alias_id=alias_id,
highlight_contact_id=contact.id,
)
)
elif request.form.get("form-name") == "delete":
contact_id = request.form.get("contact-id")
delete_contact(alias, contact_id)
return redirect(
url_for("dashboard.alias_contact_manager", alias_id=alias_id)
)
elif request.form.get("form-name") == "search":
query = request.form.get("query")
return redirect(
url_for(
"dashboard.alias_contact_manager",
alias_id=alias_id,
query=query,
highlight_contact_id=highlight_contact_id,
)
)
contact_infos = get_contact_infos(alias, page, query=query)
last_page = len(contact_infos) < config.PAGE_LIMIT
nb_contact = Contact.filter(Contact.alias_id == alias.id).count()
# if highlighted contact isn't included, fetch it
# make sure highlighted contact is at array start
contact_ids = [contact_info.contact.id for contact_info in contact_infos]
if highlight_contact_id and highlight_contact_id not in contact_ids:
contact_infos = (
get_contact_infos(alias, contact_id=highlight_contact_id, query=query)
+ contact_infos
)
return render_template(
"dashboard/alias_contact_manager.html",
contact_infos=contact_infos,
alias=alias,
new_contact_form=new_contact_form,
highlight_contact_id=highlight_contact_id,
page=page,
last_page=last_page,
query=query,
nb_contact=nb_contact,
can_create_contacts=current_user.can_create_contacts(),
csrf_form=csrf_form,
) | null |
180,748 | from flask import render_template, request, flash, redirect
from flask_login import login_required, current_user
from sqlalchemy.orm import joinedload
from app.dashboard.base import dashboard_bp
from app.db import Session
from app.models import (
ClientUser,
)
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
class ClientUser(Base, ModelMixin):
__tablename__ = "client_user"
__table_args__ = (
sa.UniqueConstraint("user_id", "client_id", name="uq_client_user"),
)
user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False)
client_id = sa.Column(sa.ForeignKey(Client.id, ondelete="cascade"), nullable=False)
# Null means client has access to user original email
alias_id = sa.Column(
sa.ForeignKey(Alias.id, ondelete="cascade"), nullable=True, index=True
)
# user can decide to send to client another name
name = sa.Column(
sa.String(128), nullable=True, default=None, server_default=text("NULL")
)
# user can decide to send to client a default avatar
default_avatar = sa.Column(
sa.Boolean, nullable=False, default=False, server_default="0"
)
alias = orm.relationship(Alias, backref="client_users")
user = orm.relationship(User)
client = orm.relationship(Client)
def get_email(self):
return self.alias.email if self.alias_id else self.user.email
def get_user_name(self):
if self.name:
return self.name
else:
return self.user.name
def get_user_info(self) -> dict:
"""return user info according to client scope
Return dict with key being scope name. For now all the fields are the same for all clients:
{
"client": "Demo",
"email": "test-avk5l@mail-tester.com",
"email_verified": true,
"id": 1,
"name": "Son GM",
"avatar_url": "http://s3..."
}
"""
res = {
"id": self.id,
"client": self.client.name,
"email_verified": True,
"sub": str(self.id),
}
for scope in self.client.get_scopes():
if scope == Scope.NAME:
if self.name:
res[Scope.NAME.value] = self.name or ""
else:
res[Scope.NAME.value] = self.user.name or ""
elif scope == Scope.AVATAR_URL:
if self.user.profile_picture_id:
if self.default_avatar:
res[Scope.AVATAR_URL.value] = (
config.URL + "/static/default-avatar.png"
)
else:
res[Scope.AVATAR_URL.value] = self.user.profile_picture.get_url(
config.AVATAR_URL_EXPIRATION
)
else:
res[Scope.AVATAR_URL.value] = None
elif scope == Scope.EMAIL:
# Use generated email
if self.alias_id:
LOG.d(
"Use gen email for user %s, client %s", self.user, self.client
)
res[Scope.EMAIL.value] = self.alias.email
# Use user original email
else:
res[Scope.EMAIL.value] = self.user.email
return res
The provided code snippet includes necessary dependencies for implementing the `app_route` function. Write a Python function `def app_route()` to solve the following problem:
List of apps that user has used via the "Sign in with SimpleLogin"
Here is the function:
def app_route():
"""
List of apps that user has used via the "Sign in with SimpleLogin"
"""
client_users = (
ClientUser.filter_by(user_id=current_user.id)
.options(joinedload(ClientUser.client))
.options(joinedload(ClientUser.alias))
.all()
)
sorted(client_users, key=lambda cu: cu.client.name)
if request.method == "POST":
client_user_id = request.form.get("client-user-id")
client_user = ClientUser.get(client_user_id)
if not client_user or client_user.user_id != current_user.id:
flash(
"Unknown error, sorry for the inconvenience, refresh the page", "error"
)
return redirect(request.url)
client = client_user.client
ClientUser.delete(client_user_id)
Session.commit()
flash(f"Link with {client.name} has been removed", "success")
return redirect(request.url)
return render_template(
"dashboard/app.html",
client_users=client_users,
) | List of apps that user has used via the "Sign in with SimpleLogin" |
180,749 | from email_validator import validate_email, EmailNotValidError
from flask import render_template, redirect, url_for, flash, request
from flask_login import login_required, current_user
from sqlalchemy.exc import IntegrityError
from app import parallel_limiter
from app.alias_suffix import (
get_alias_suffixes,
check_suffix_signature,
verify_prefix_suffix,
)
from app.alias_utils import check_alias_prefix
from app.config import (
ALIAS_LIMIT,
)
from app.dashboard.base import dashboard_bp
from app.db import Session
from app.extensions import limiter
from app.log import LOG
from app.models import (
Alias,
DeletedAlias,
Mailbox,
AliasMailbox,
DomainDeletedAlias,
)
from app.utils import CSRFValidationForm
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 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 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
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
LOG = _get_logger("SL")
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 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)
class CSRFValidationForm(FlaskForm):
pass
def custom_alias():
# check if user has not exceeded the alias quota
if not current_user.can_create_new_alias():
LOG.d("%s can't create new alias", current_user)
flash(
"You have reached free plan limit, please upgrade to create new aliases",
"warning",
)
return redirect(url_for("dashboard.index"))
user_custom_domains = [cd.domain for cd in current_user.verified_custom_domains()]
alias_suffixes = get_alias_suffixes(current_user)
at_least_a_premium_domain = False
for alias_suffix in alias_suffixes:
if not alias_suffix.is_custom and alias_suffix.is_premium:
at_least_a_premium_domain = True
break
csrf_form = CSRFValidationForm()
mailboxes = current_user.mailboxes()
if request.method == "POST":
if not csrf_form.validate():
flash("Invalid request", "warning")
return redirect(request.url)
alias_prefix = request.form.get("prefix").strip().lower().replace(" ", "")
signed_alias_suffix = request.form.get("signed-alias-suffix")
mailbox_ids = request.form.getlist("mailboxes")
alias_note = request.form.get("note")
if not check_alias_prefix(alias_prefix):
flash(
"Only lowercase letters, numbers, dashes (-), dots (.) and underscores (_) "
"are currently supported for alias prefix. Cannot be more than 40 letters",
"error",
)
return redirect(request.url)
# check if mailbox is not tempered with
mailboxes = []
for mailbox_id in mailbox_ids:
mailbox = Mailbox.get(mailbox_id)
if (
not mailbox
or mailbox.user_id != current_user.id
or not mailbox.verified
):
flash("Something went wrong, please retry", "warning")
return redirect(request.url)
mailboxes.append(mailbox)
if not mailboxes:
flash("At least one mailbox must be selected", "error")
return redirect(request.url)
try:
suffix = check_suffix_signature(signed_alias_suffix)
if not suffix:
LOG.w("Alias creation time expired for %s", current_user)
flash("Alias creation time is expired, please retry", "warning")
return redirect(request.url)
except Exception:
LOG.w("Alias suffix is tampered, user %s", current_user)
flash("Unknown error, refresh the page", "error")
return redirect(request.url)
if verify_prefix_suffix(current_user, alias_prefix, suffix):
full_alias = alias_prefix + suffix
if ".." in full_alias:
flash("Your alias can't contain 2 consecutive dots (..)", "error")
return redirect(request.url)
try:
validate_email(
full_alias, check_deliverability=False, allow_smtputf8=False
)
except EmailNotValidError as e:
flash(str(e), "error")
return redirect(request.url)
general_error_msg = f"{full_alias} cannot be used"
if Alias.get_by(email=full_alias):
alias = Alias.get_by(email=full_alias)
if alias.user_id == current_user.id:
flash(f"You already have this alias {full_alias}", "error")
else:
flash(general_error_msg, "error")
elif DomainDeletedAlias.get_by(email=full_alias):
domain_deleted_alias: DomainDeletedAlias = DomainDeletedAlias.get_by(
email=full_alias
)
custom_domain = domain_deleted_alias.domain
flash(
f"You have deleted this alias before. You can restore it on "
f"{custom_domain.domain} 'Deleted Alias' page",
"error",
)
elif DeletedAlias.get_by(email=full_alias):
flash(general_error_msg, "error")
else:
try:
alias = Alias.create(
user_id=current_user.id,
email=full_alias,
note=alias_note,
mailbox_id=mailboxes[0].id,
)
Session.flush()
except IntegrityError:
LOG.w("Alias %s already exists", full_alias)
Session.rollback()
flash("Unknown error, please retry", "error")
return redirect(url_for("dashboard.custom_alias"))
for i in range(1, len(mailboxes)):
AliasMailbox.create(
alias_id=alias.id,
mailbox_id=mailboxes[i].id,
)
Session.commit()
flash(f"Alias {full_alias} has been created", "success")
return redirect(url_for("dashboard.index", highlight_alias_id=alias.id))
# only happen if the request has been "hacked"
else:
flash("something went wrong", "warning")
return render_template(
"dashboard/custom_alias.html",
user_custom_domains=user_custom_domains,
alias_suffixes=alias_suffixes,
at_least_a_premium_domain=at_least_a_premium_domain,
mailboxes=mailboxes,
csrf_form=csrf_form,
) | null |
180,750 | from io import BytesIO
from typing import Optional, Tuple
import arrow
from flask import (
render_template,
request,
redirect,
url_for,
flash,
)
from flask_login import login_required, current_user
from flask_wtf import FlaskForm
from flask_wtf.file import FileField
from wtforms import StringField, validators
from app import s3
from app.config import (
FIRST_ALIAS_DOMAIN,
ALIAS_RANDOM_SUFFIX_LENGTH,
CONNECT_WITH_PROTON,
)
from app.dashboard.base import dashboard_bp
from app.db import Session
from app.errors import ProtonPartnerNotSetUp
from app.extensions import limiter
from app.image_validation import detect_image_format, ImageFormat
from app.log import LOG
from app.models import (
BlockBehaviourEnum,
PlanEnum,
File,
EmailChange,
CustomDomain,
AliasGeneratorEnum,
AliasSuffixEnum,
ManualSubscription,
SenderFormatEnum,
SLDomain,
CoinbaseSubscription,
AppleSubscription,
PartnerUser,
PartnerSubscription,
UnsubscribeBehaviourEnum,
)
from app.proton.utils import get_proton_partner
from app.utils import (
random_string,
CSRFValidationForm,
)
class SettingForm(FlaskForm):
name = StringField("Name")
profile_picture = FileField("Profile Picture")
class PromoCodeForm(FlaskForm):
code = StringField("Name", validators=[validators.DataRequired()])
def get_proton_linked_account() -> Optional[str]:
# Check if the current user has a partner_id
try:
proton_partner_id = get_proton_partner().id
except ProtonPartnerNotSetUp:
return None
# It has. Retrieve the information for the PartnerUser
proton_linked_account = PartnerUser.get_by(
user_id=current_user.id, partner_id=proton_partner_id
)
if proton_linked_account is None:
return None
return proton_linked_account.partner_email
def get_partner_subscription_and_name(
user_id: int,
) -> Optional[Tuple[PartnerSubscription, str]]:
partner_sub = PartnerSubscription.find_by_user_id(user_id)
if not partner_sub or not partner_sub.is_active():
return None
partner = partner_sub.partner_user.partner
return (partner_sub, partner.name)
FIRST_ALIAS_DOMAIN = os.environ.get("FIRST_ALIAS_DOMAIN") or EMAIL_DOMAIN
CONNECT_WITH_PROTON = "CONNECT_WITH_PROTON" in os.environ
ALIAS_RANDOM_SUFFIX_LENGTH = int(os.environ.get("ALIAS_RAND_SUFFIX_LENGTH", 5))
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
class ImageFormat(Enum):
Png = 1
Jpg = 2
Webp = 3
Unknown = 9
def detect_image_format(image: bytes) -> ImageFormat:
# Detect image based on magic number
for fmt, header in magic_numbers.items():
if image.startswith(header):
return fmt
# We don't know the type
return ImageFormat.Unknown
LOG = _get_logger("SL")
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}>"
class PlanEnum(EnumE):
monthly = 2
yearly = 3
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 BlockBehaviourEnum(EnumE):
return_2xx = 0
return_5xx = 1
class UnsubscribeBehaviourEnum(EnumE):
DisableAlias = 0
BlockContact = 1
PreserveOriginal = 2
class ManualSubscription(Base, ModelMixin):
"""
For users who use other forms of payment and therefore not pass by Paddle
"""
__tablename__ = "manual_subscription"
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, unique=True
)
# an reminder is sent several days before the subscription ends
end_at = sa.Column(ArrowType, nullable=False)
# for storing note about this subscription
comment = sa.Column(sa.Text, nullable=True)
# manual subscription are also used for Premium giveaways
is_giveaway = sa.Column(
sa.Boolean, default=False, nullable=False, server_default="0"
)
user = orm.relationship(User)
def is_active(self):
return self.end_at > arrow.now()
class CoinbaseSubscription(Base, ModelMixin):
"""
For subscriptions using Coinbase Commerce
"""
__tablename__ = "coinbase_subscription"
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, unique=True
)
# an reminder is sent several days before the subscription ends
end_at = sa.Column(ArrowType, nullable=False)
# the Coinbase code
code = sa.Column(sa.String(64), nullable=True)
user = orm.relationship(User)
def is_active(self):
return self.end_at > arrow.now()
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)
class EmailChange(Base, ModelMixin):
"""Used when user wants to update their email"""
__tablename__ = "email_change"
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"),
nullable=False,
unique=True,
index=True,
)
new_email = sa.Column(sa.String(256), unique=True, nullable=False)
code = sa.Column(sa.String(128), unique=True, nullable=False)
expired = sa.Column(ArrowType, nullable=False, default=_expiration_12h)
user = orm.relationship(User)
def is_expired(self):
return self.expired < arrow.now()
def __repr__(self):
return f"<EmailChange {self.id} {self.new_email} {self.user_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 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'}"
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))
class CSRFValidationForm(FlaskForm):
pass
def setting():
form = SettingForm()
promo_form = PromoCodeForm()
csrf_form = CSRFValidationForm()
email_change = EmailChange.get_by(user_id=current_user.id)
if email_change:
pending_email = email_change.new_email
else:
pending_email = None
if request.method == "POST":
if not csrf_form.validate():
flash("Invalid request", "warning")
return redirect(url_for("dashboard.setting"))
if request.form.get("form-name") == "update-profile":
if form.validate():
profile_updated = False
# update user info
if form.name.data != current_user.name:
current_user.name = form.name.data
Session.commit()
profile_updated = True
if form.profile_picture.data:
image_contents = form.profile_picture.data.read()
if detect_image_format(image_contents) == ImageFormat.Unknown:
flash(
"This image format is not supported",
"error",
)
return redirect(url_for("dashboard.setting"))
if current_user.profile_picture_id is not None:
current_profile_file = File.get_by(
id=current_user.profile_picture_id
)
if (
current_profile_file is not None
and current_profile_file.user_id == current_user.id
):
s3.delete(current_profile_file.path)
file_path = random_string(30)
file = File.create(user_id=current_user.id, path=file_path)
s3.upload_from_bytesio(file_path, BytesIO(image_contents))
Session.flush()
LOG.d("upload file %s to s3", file)
current_user.profile_picture_id = file.id
Session.commit()
profile_updated = True
if profile_updated:
flash("Your profile has been updated", "success")
return redirect(url_for("dashboard.setting"))
elif request.form.get("form-name") == "notification-preference":
choose = request.form.get("notification")
if choose == "on":
current_user.notification = True
else:
current_user.notification = False
Session.commit()
flash("Your notification preference has been updated", "success")
return redirect(url_for("dashboard.setting"))
elif request.form.get("form-name") == "change-alias-generator":
scheme = int(request.form.get("alias-generator-scheme"))
if AliasGeneratorEnum.has_value(scheme):
current_user.alias_generator = scheme
Session.commit()
flash("Your preference has been updated", "success")
return redirect(url_for("dashboard.setting"))
elif request.form.get("form-name") == "change-random-alias-default-domain":
default_domain = request.form.get("random-alias-default-domain")
if default_domain:
sl_domain: SLDomain = SLDomain.get_by(domain=default_domain)
if sl_domain:
if sl_domain.premium_only and not current_user.is_premium():
flash("You cannot use this domain", "error")
return redirect(url_for("dashboard.setting"))
current_user.default_alias_public_domain_id = sl_domain.id
current_user.default_alias_custom_domain_id = None
else:
custom_domain = CustomDomain.get_by(domain=default_domain)
if custom_domain:
# sanity check
if (
custom_domain.user_id != current_user.id
or not custom_domain.verified
):
LOG.w(
"%s cannot use domain %s", current_user, custom_domain
)
flash(f"Domain {default_domain} can't be used", "error")
return redirect(request.url)
else:
current_user.default_alias_custom_domain_id = (
custom_domain.id
)
current_user.default_alias_public_domain_id = None
else:
current_user.default_alias_custom_domain_id = None
current_user.default_alias_public_domain_id = None
Session.commit()
flash("Your preference has been updated", "success")
return redirect(url_for("dashboard.setting"))
elif request.form.get("form-name") == "random-alias-suffix":
scheme = int(request.form.get("random-alias-suffix-generator"))
if AliasSuffixEnum.has_value(scheme):
current_user.random_alias_suffix = scheme
Session.commit()
flash("Your preference has been updated", "success")
return redirect(url_for("dashboard.setting"))
elif request.form.get("form-name") == "change-sender-format":
sender_format = int(request.form.get("sender-format"))
if SenderFormatEnum.has_value(sender_format):
current_user.sender_format = sender_format
current_user.sender_format_updated_at = arrow.now()
Session.commit()
flash("Your sender format preference has been updated", "success")
Session.commit()
return redirect(url_for("dashboard.setting"))
elif request.form.get("form-name") == "replace-ra":
choose = request.form.get("replace-ra")
if choose == "on":
current_user.replace_reverse_alias = True
else:
current_user.replace_reverse_alias = False
Session.commit()
flash("Your preference has been updated", "success")
return redirect(url_for("dashboard.setting"))
elif request.form.get("form-name") == "sender-in-ra":
choose = request.form.get("enable")
if choose == "on":
current_user.include_sender_in_reverse_alias = True
else:
current_user.include_sender_in_reverse_alias = False
Session.commit()
flash("Your preference has been updated", "success")
return redirect(url_for("dashboard.setting"))
elif request.form.get("form-name") == "expand-alias-info":
choose = request.form.get("enable")
if choose == "on":
current_user.expand_alias_info = True
else:
current_user.expand_alias_info = False
Session.commit()
flash("Your preference has been updated", "success")
return redirect(url_for("dashboard.setting"))
elif request.form.get("form-name") == "ignore-loop-email":
choose = request.form.get("enable")
if choose == "on":
current_user.ignore_loop_email = True
else:
current_user.ignore_loop_email = False
Session.commit()
flash("Your preference has been updated", "success")
return redirect(url_for("dashboard.setting"))
elif request.form.get("form-name") == "one-click-unsubscribe":
choose = request.form.get("unsubscribe-behaviour")
if choose == UnsubscribeBehaviourEnum.PreserveOriginal.name:
current_user.unsub_behaviour = UnsubscribeBehaviourEnum.PreserveOriginal
elif choose == UnsubscribeBehaviourEnum.DisableAlias.name:
current_user.unsub_behaviour = UnsubscribeBehaviourEnum.DisableAlias
elif choose == UnsubscribeBehaviourEnum.BlockContact.name:
current_user.unsub_behaviour = UnsubscribeBehaviourEnum.BlockContact
else:
flash("There was an error. Please try again", "warning")
return redirect(url_for("dashboard.setting"))
Session.commit()
flash("Your preference has been updated", "success")
return redirect(url_for("dashboard.setting"))
elif request.form.get("form-name") == "include_website_in_one_click_alias":
choose = request.form.get("enable")
if choose == "on":
current_user.include_website_in_one_click_alias = True
else:
current_user.include_website_in_one_click_alias = False
Session.commit()
flash("Your preference has been updated", "success")
return redirect(url_for("dashboard.setting"))
elif request.form.get("form-name") == "change-blocked-behaviour":
choose = request.form.get("blocked-behaviour")
if choose == str(BlockBehaviourEnum.return_2xx.value):
current_user.block_behaviour = BlockBehaviourEnum.return_2xx.name
elif choose == str(BlockBehaviourEnum.return_5xx.value):
current_user.block_behaviour = BlockBehaviourEnum.return_5xx.name
else:
flash("There was an error. Please try again", "warning")
return redirect(url_for("dashboard.setting"))
Session.commit()
flash("Your preference has been updated", "success")
elif request.form.get("form-name") == "sender-header":
choose = request.form.get("enable")
if choose == "on":
current_user.include_header_email_header = True
else:
current_user.include_header_email_header = False
Session.commit()
flash("Your preference has been updated", "success")
return redirect(url_for("dashboard.setting"))
manual_sub = ManualSubscription.get_by(user_id=current_user.id)
apple_sub = AppleSubscription.get_by(user_id=current_user.id)
coinbase_sub = CoinbaseSubscription.get_by(user_id=current_user.id)
paddle_sub = current_user.get_paddle_subscription()
partner_sub = None
partner_name = None
partner_sub_name = get_partner_subscription_and_name(current_user.id)
if partner_sub_name:
partner_sub, partner_name = partner_sub_name
proton_linked_account = get_proton_linked_account()
return render_template(
"dashboard/setting.html",
csrf_form=csrf_form,
form=form,
PlanEnum=PlanEnum,
SenderFormatEnum=SenderFormatEnum,
BlockBehaviourEnum=BlockBehaviourEnum,
promo_form=promo_form,
pending_email=pending_email,
AliasGeneratorEnum=AliasGeneratorEnum,
UnsubscribeBehaviourEnum=UnsubscribeBehaviourEnum,
manual_sub=manual_sub,
partner_sub=partner_sub,
partner_name=partner_name,
apple_sub=apple_sub,
paddle_sub=paddle_sub,
coinbase_sub=coinbase_sub,
FIRST_ALIAS_DOMAIN=FIRST_ALIAS_DOMAIN,
ALIAS_RAND_SUFFIX_LENGTH=ALIAS_RANDOM_SUFFIX_LENGTH,
connect_with_proton=CONNECT_WITH_PROTON,
proton_linked_account=proton_linked_account,
) | null |
180,751 | import arrow
from flask import make_response, redirect, url_for
from flask_login import login_required
from app.config import URL
from app.dashboard.base import dashboard_bp
URL = os.environ["URL"]
def setup_done():
response = make_response(redirect(url_for("dashboard.index")))
response.set_cookie(
"setup_done",
value="true",
expires=arrow.now().shift(days=30).datetime,
secure=True if URL.startswith("https") else False,
httponly=True,
samesite="Lax",
)
return response | null |
180,752 | import re
import arrow
from flask import render_template, request, redirect, url_for, flash
from flask_login import login_required, current_user
from flask_wtf import FlaskForm
from wtforms import StringField, validators, IntegerField
from app.config import EMAIL_SERVERS_WITH_PRIORITY, EMAIL_DOMAIN, JOB_DELETE_DOMAIN
from app.custom_domain_validation import CustomDomainValidation
from app.dashboard.base import dashboard_bp
from app.db import Session
from app.dns_utils import (
get_mx_domains,
get_spf_domain,
get_txt_record,
is_mx_equivalent,
)
from app.log import LOG
from app.models import (
CustomDomain,
Alias,
DomainDeletedAlias,
Mailbox,
DomainMailbox,
AutoCreateRule,
AutoCreateRuleMailbox,
Job,
)
from app.regex_utils import regex_match
from app.utils import random_string, CSRFValidationForm
EMAIL_DOMAIN = os.environ["EMAIL_DOMAIN"].lower()
EMAIL_SERVERS_WITH_PRIORITY = sl_getenv("EMAIL_SERVERS_WITH_PRIORITY")
class CustomDomainValidation:
def __init__(self, dkim_domain: str):
self.dkim_domain = dkim_domain
self._dkim_records = {
(f"{key}._domainkey", f"{key}._domainkey.{self.dkim_domain}")
for key in ("dkim", "dkim02", "dkim03")
}
def get_dkim_records(self) -> {str: str}:
"""
Get a list of dkim records to set up. It will be
"""
return self._dkim_records
def validate_dkim_records(self, custom_domain: CustomDomain) -> dict[str, str]:
"""
Check if dkim records are properly set for this custom domain.
Returns empty list if all records are ok. Other-wise return the records that aren't properly configured
"""
invalid_records = {}
for prefix, expected_record in self.get_dkim_records():
custom_record = f"{prefix}.{custom_domain.domain}"
dkim_record = get_cname_record(custom_record)
if dkim_record != expected_record:
invalid_records[custom_record] = dkim_record or "empty"
# HACK: If dkim is enabled, don't disable it to give users time to update their CNAMES
if custom_domain.dkim_verified:
return invalid_records
custom_domain.dkim_verified = len(invalid_records) == 0
Session.commit()
return invalid_records
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
def get_mx_domains(hostname) -> [(int, str)]:
"""return list of (priority, domain name) sorted by priority (lowest priority first)
domain name ends with a "." at the end.
"""
try:
answers = _get_dns_resolver().resolve(hostname, "MX", search=True)
except Exception:
return []
ret = []
for a in answers:
record = a.to_text() # for ex '20 alt2.aspmx.l.google.com.'
parts = record.split(" ")
ret.append((int(parts[0]), parts[1]))
return sorted(ret, key=lambda prio_domain: prio_domain[0])
def get_spf_domain(hostname) -> [str]:
"""return all domains listed in *include:*"""
try:
answers = _get_dns_resolver().resolve(hostname, "TXT", search=True)
except Exception:
return []
ret = []
for a in answers: # type: dns.rdtypes.ANY.TXT.TXT
for record in a.strings:
record = record.decode() # record is bytes
if record.startswith("v=spf1"):
parts = record.split(" ")
for part in parts:
if part.startswith(_include_spf):
ret.append(part[part.find(_include_spf) + len(_include_spf) :])
return ret
def get_txt_record(hostname) -> [str]:
try:
answers = _get_dns_resolver().resolve(hostname, "TXT", search=True)
except Exception:
return []
ret = []
for a in answers: # type: dns.rdtypes.ANY.TXT.TXT
for record in a.strings:
record = record.decode() # record is bytes
ret.append(record)
return ret
def is_mx_equivalent(
mx_domains: List[Tuple[int, str]], ref_mx_domains: List[Tuple[int, str]]
) -> bool:
"""
Compare mx_domains with ref_mx_domains to see if they are equivalent.
mx_domains and ref_mx_domains are list of (priority, domain)
The priority order is taken into account but not the priority number.
For example, [(1, domain1), (2, domain2)] is equivalent to [(10, domain1), (20, domain2)]
"""
mx_domains = sorted(mx_domains, key=lambda priority_domain: priority_domain[0])
ref_mx_domains = sorted(
ref_mx_domains, key=lambda priority_domain: priority_domain[0]
)
if len(mx_domains) < len(ref_mx_domains):
return False
for i in range(0, len(ref_mx_domains)):
if mx_domains[i][1] != ref_mx_domains[i][1]:
return False
return True
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 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))
class CSRFValidationForm(FlaskForm):
pass
def domain_detail_dns(custom_domain_id):
custom_domain: CustomDomain = CustomDomain.get(custom_domain_id)
if not custom_domain or custom_domain.user_id != current_user.id:
flash("You cannot see this page", "warning")
return redirect(url_for("dashboard.index"))
# generate a domain ownership txt token if needed
if not custom_domain.ownership_verified and not custom_domain.ownership_txt_token:
custom_domain.ownership_txt_token = random_string(30)
Session.commit()
spf_record = f"v=spf1 include:{EMAIL_DOMAIN} ~all"
domain_validator = CustomDomainValidation(EMAIL_DOMAIN)
csrf_form = CSRFValidationForm()
dmarc_record = "v=DMARC1; p=quarantine; pct=100; adkim=s; aspf=s"
mx_ok = spf_ok = dkim_ok = dmarc_ok = ownership_ok = True
mx_errors = spf_errors = dkim_errors = dmarc_errors = ownership_errors = []
if request.method == "POST":
if not csrf_form.validate():
flash("Invalid request", "warning")
return redirect(request.url)
if request.form.get("form-name") == "check-ownership":
txt_records = get_txt_record(custom_domain.domain)
if custom_domain.get_ownership_dns_txt_value() in txt_records:
flash(
"Domain ownership is verified. Please proceed to the other records setup",
"success",
)
custom_domain.ownership_verified = True
Session.commit()
return redirect(
url_for(
"dashboard.domain_detail_dns",
custom_domain_id=custom_domain.id,
_anchor="dns-setup",
)
)
else:
flash("We can't find the needed TXT record", "error")
ownership_ok = False
ownership_errors = txt_records
elif request.form.get("form-name") == "check-mx":
mx_domains = get_mx_domains(custom_domain.domain)
if not is_mx_equivalent(mx_domains, EMAIL_SERVERS_WITH_PRIORITY):
flash("The MX record is not correctly set", "warning")
mx_ok = False
# build mx_errors to show to user
mx_errors = [
f"{priority} {domain}" for (priority, domain) in mx_domains
]
else:
flash(
"Your domain can start receiving emails. You can now use it to create alias",
"success",
)
custom_domain.verified = True
Session.commit()
return redirect(
url_for(
"dashboard.domain_detail_dns", custom_domain_id=custom_domain.id
)
)
elif request.form.get("form-name") == "check-spf":
spf_domains = get_spf_domain(custom_domain.domain)
if EMAIL_DOMAIN in spf_domains:
custom_domain.spf_verified = True
Session.commit()
flash("SPF is setup correctly", "success")
return redirect(
url_for(
"dashboard.domain_detail_dns", custom_domain_id=custom_domain.id
)
)
else:
custom_domain.spf_verified = False
Session.commit()
flash(
f"SPF: {EMAIL_DOMAIN} is not included in your SPF record.",
"warning",
)
spf_ok = False
spf_errors = get_txt_record(custom_domain.domain)
elif request.form.get("form-name") == "check-dkim":
dkim_errors = domain_validator.validate_dkim_records(custom_domain)
if len(dkim_errors) == 0:
flash("DKIM is setup correctly.", "success")
return redirect(
url_for(
"dashboard.domain_detail_dns", custom_domain_id=custom_domain.id
)
)
else:
dkim_ok = False
flash("DKIM: the CNAME record is not correctly set", "warning")
elif request.form.get("form-name") == "check-dmarc":
txt_records = get_txt_record("_dmarc." + custom_domain.domain)
if dmarc_record in txt_records:
custom_domain.dmarc_verified = True
Session.commit()
flash("DMARC is setup correctly", "success")
return redirect(
url_for(
"dashboard.domain_detail_dns", custom_domain_id=custom_domain.id
)
)
else:
custom_domain.dmarc_verified = False
Session.commit()
flash(
"DMARC: The TXT record is not correctly set",
"warning",
)
dmarc_ok = False
dmarc_errors = txt_records
return render_template(
"dashboard/domain_detail/dns.html",
EMAIL_SERVERS_WITH_PRIORITY=EMAIL_SERVERS_WITH_PRIORITY,
dkim_records=domain_validator.get_dkim_records(),
**locals(),
) | null |
180,753 | import re
import arrow
from flask import render_template, request, redirect, url_for, flash
from flask_login import login_required, current_user
from flask_wtf import FlaskForm
from wtforms import StringField, validators, IntegerField
from app.config import EMAIL_SERVERS_WITH_PRIORITY, EMAIL_DOMAIN, JOB_DELETE_DOMAIN
from app.custom_domain_validation import CustomDomainValidation
from app.dashboard.base import dashboard_bp
from app.db import Session
from app.dns_utils import (
get_mx_domains,
get_spf_domain,
get_txt_record,
is_mx_equivalent,
)
from app.log import LOG
from app.models import (
CustomDomain,
Alias,
DomainDeletedAlias,
Mailbox,
DomainMailbox,
AutoCreateRule,
AutoCreateRuleMailbox,
Job,
)
from app.regex_utils import regex_match
from app.utils import random_string, CSRFValidationForm
JOB_DELETE_DOMAIN = "delete-domain"
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
LOG = _get_logger("SL")
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}>"
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}>"
class DomainMailbox(Base, ModelMixin):
"""store the owning mailboxes for a domain"""
__tablename__ = "domain_mailbox"
__table_args__ = (
sa.UniqueConstraint("domain_id", "mailbox_id", name="uq_domain_mailbox"),
)
domain_id = sa.Column(
sa.ForeignKey(CustomDomain.id, ondelete="cascade"), nullable=False
)
mailbox_id = sa.Column(
sa.ForeignKey(Mailbox.id, ondelete="cascade"), nullable=False
)
class CSRFValidationForm(FlaskForm):
pass
def domain_detail(custom_domain_id):
csrf_form = CSRFValidationForm()
custom_domain: CustomDomain = CustomDomain.get(custom_domain_id)
mailboxes = current_user.mailboxes()
if not custom_domain or custom_domain.user_id != current_user.id:
flash("You cannot see this page", "warning")
return redirect(url_for("dashboard.index"))
if request.method == "POST":
if not csrf_form.validate():
flash("Invalid request", "warning")
return redirect(request.url)
if request.form.get("form-name") == "switch-catch-all":
custom_domain.catch_all = not custom_domain.catch_all
Session.commit()
if custom_domain.catch_all:
flash(
f"The catch-all has been enabled for {custom_domain.domain}",
"success",
)
else:
flash(
f"The catch-all has been disabled for {custom_domain.domain}",
"warning",
)
return redirect(
url_for("dashboard.domain_detail", custom_domain_id=custom_domain.id)
)
elif request.form.get("form-name") == "set-name":
if request.form.get("action") == "save":
custom_domain.name = request.form.get("alias-name").replace("\n", "")
Session.commit()
flash(
f"Default alias name for Domain {custom_domain.domain} has been set",
"success",
)
else:
custom_domain.name = None
Session.commit()
flash(
f"Default alias name for Domain {custom_domain.domain} has been removed",
"info",
)
return redirect(
url_for("dashboard.domain_detail", custom_domain_id=custom_domain.id)
)
elif request.form.get("form-name") == "switch-random-prefix-generation":
custom_domain.random_prefix_generation = (
not custom_domain.random_prefix_generation
)
Session.commit()
if custom_domain.random_prefix_generation:
flash(
f"Random prefix generation has been enabled for {custom_domain.domain}",
"success",
)
else:
flash(
f"Random prefix generation has been disabled for {custom_domain.domain}",
"warning",
)
return redirect(
url_for("dashboard.domain_detail", custom_domain_id=custom_domain.id)
)
elif request.form.get("form-name") == "update":
mailbox_ids = request.form.getlist("mailbox_ids")
# check if mailbox is not tempered with
mailboxes = []
for mailbox_id in mailbox_ids:
mailbox = Mailbox.get(mailbox_id)
if (
not mailbox
or mailbox.user_id != current_user.id
or not mailbox.verified
):
flash("Something went wrong, please retry", "warning")
return redirect(
url_for(
"dashboard.domain_detail", custom_domain_id=custom_domain.id
)
)
mailboxes.append(mailbox)
if not mailboxes:
flash("You must select at least 1 mailbox", "warning")
return redirect(
url_for(
"dashboard.domain_detail", custom_domain_id=custom_domain.id
)
)
# first remove all existing domain-mailboxes links
DomainMailbox.filter_by(domain_id=custom_domain.id).delete()
Session.flush()
for mailbox in mailboxes:
DomainMailbox.create(domain_id=custom_domain.id, mailbox_id=mailbox.id)
Session.commit()
flash(f"{custom_domain.domain} mailboxes has been updated", "success")
return redirect(
url_for("dashboard.domain_detail", custom_domain_id=custom_domain.id)
)
elif request.form.get("form-name") == "delete":
name = custom_domain.domain
LOG.d("Schedule deleting %s", custom_domain)
# Schedule delete domain job
LOG.w("schedule delete domain job for %s", custom_domain)
Job.create(
name=JOB_DELETE_DOMAIN,
payload={"custom_domain_id": custom_domain.id},
run_at=arrow.now(),
commit=True,
)
flash(
f"{name} scheduled for deletion."
f"You will receive a confirmation email when the deletion is finished",
"success",
)
if custom_domain.is_sl_subdomain:
return redirect(url_for("dashboard.subdomain_route"))
else:
return redirect(url_for("dashboard.custom_domain"))
nb_alias = Alias.filter_by(custom_domain_id=custom_domain.id).count()
return render_template("dashboard/domain_detail/info.html", **locals()) | null |
180,754 | import re
import arrow
from flask import render_template, request, redirect, url_for, flash
from flask_login import login_required, current_user
from flask_wtf import FlaskForm
from wtforms import StringField, validators, IntegerField
from app.config import EMAIL_SERVERS_WITH_PRIORITY, EMAIL_DOMAIN, JOB_DELETE_DOMAIN
from app.custom_domain_validation import CustomDomainValidation
from app.dashboard.base import dashboard_bp
from app.db import Session
from app.dns_utils import (
get_mx_domains,
get_spf_domain,
get_txt_record,
is_mx_equivalent,
)
from app.log import LOG
from app.models import (
CustomDomain,
Alias,
DomainDeletedAlias,
Mailbox,
DomainMailbox,
AutoCreateRule,
AutoCreateRuleMailbox,
Job,
)
from app.regex_utils import regex_match
from app.utils import random_string, CSRFValidationForm
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
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 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 CSRFValidationForm(FlaskForm):
pass
def domain_detail_trash(custom_domain_id):
csrf_form = CSRFValidationForm()
custom_domain = CustomDomain.get(custom_domain_id)
if not custom_domain or custom_domain.user_id != current_user.id:
flash("You cannot see this page", "warning")
return redirect(url_for("dashboard.index"))
if request.method == "POST":
if not csrf_form.validate():
flash("Invalid request", "warning")
return redirect(request.url)
if request.form.get("form-name") == "empty-all":
DomainDeletedAlias.filter_by(domain_id=custom_domain.id).delete()
Session.commit()
flash("All deleted aliases can now be re-created", "success")
return redirect(
url_for(
"dashboard.domain_detail_trash", custom_domain_id=custom_domain.id
)
)
elif request.form.get("form-name") == "remove-single":
deleted_alias_id = request.form.get("deleted-alias-id")
deleted_alias = DomainDeletedAlias.get(deleted_alias_id)
if not deleted_alias or deleted_alias.domain_id != custom_domain.id:
flash("Unknown error, refresh the page", "warning")
return redirect(
url_for(
"dashboard.domain_detail_trash",
custom_domain_id=custom_domain.id,
)
)
DomainDeletedAlias.delete(deleted_alias.id)
Session.commit()
flash(
f"{deleted_alias.email} can now be re-created",
"success",
)
return redirect(
url_for(
"dashboard.domain_detail_trash", custom_domain_id=custom_domain.id
)
)
domain_deleted_aliases = DomainDeletedAlias.filter_by(
domain_id=custom_domain.id
).all()
return render_template(
"dashboard/domain_detail/trash.html",
domain_deleted_aliases=domain_deleted_aliases,
custom_domain=custom_domain,
csrf_form=csrf_form,
) | null |
180,755 | import re
import arrow
from flask import render_template, request, redirect, url_for, flash
from flask_login import login_required, current_user
from flask_wtf import FlaskForm
from wtforms import StringField, validators, IntegerField
from app.config import EMAIL_SERVERS_WITH_PRIORITY, EMAIL_DOMAIN, JOB_DELETE_DOMAIN
from app.custom_domain_validation import CustomDomainValidation
from app.dashboard.base import dashboard_bp
from app.db import Session
from app.dns_utils import (
get_mx_domains,
get_spf_domain,
get_txt_record,
is_mx_equivalent,
)
from app.log import LOG
from app.models import (
CustomDomain,
Alias,
DomainDeletedAlias,
Mailbox,
DomainMailbox,
AutoCreateRule,
AutoCreateRuleMailbox,
Job,
)
from app.regex_utils import regex_match
from app.utils import random_string, CSRFValidationForm
class AutoCreateRuleForm(FlaskForm):
regex = StringField(
"regex", validators=[validators.DataRequired(), validators.Length(max=128)]
)
order = IntegerField(
"order",
validators=[validators.DataRequired(), validators.NumberRange(min=0, max=100)],
)
class AutoCreateTestForm(FlaskForm):
local = StringField(
"local part", validators=[validators.DataRequired(), validators.Length(max=128)]
)
"/domains/<int:custom_domain_id>/auto-create", methods=["GET", "POST"]
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
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 AutoCreateRule(Base, ModelMixin):
"""Alias auto creation rule for custom domain"""
__tablename__ = "auto_create_rule"
__table_args__ = (
sa.UniqueConstraint(
"custom_domain_id", "order", name="uq_auto_create_rule_order"
),
)
custom_domain_id = sa.Column(
sa.ForeignKey(CustomDomain.id, ondelete="cascade"), nullable=False
)
# an alias is auto created if it matches the regex
regex = sa.Column(sa.String(512), nullable=False)
# the order in which rules are evaluated in case there are multiple rules
order = sa.Column(sa.Integer, default=0, nullable=False)
custom_domain = orm.relationship(CustomDomain, backref="_auto_create_rules")
mailboxes = orm.relationship(
"Mailbox", secondary="auto_create_rule__mailbox", lazy="joined"
)
class AutoCreateRuleMailbox(Base, ModelMixin):
"""store auto create rule - mailbox association"""
__tablename__ = "auto_create_rule__mailbox"
__table_args__ = (
sa.UniqueConstraint(
"auto_create_rule_id", "mailbox_id", name="uq_auto_create_rule_mailbox"
),
)
auto_create_rule_id = sa.Column(
sa.ForeignKey(AutoCreateRule.id, ondelete="cascade"), nullable=False
)
mailbox_id = sa.Column(
sa.ForeignKey("mailbox.id", ondelete="cascade"), nullable=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 regex_match(rule_regex: str, local):
regex = re2.compile(rule_regex)
try:
if re2.fullmatch(regex, local):
return True
except TypeError: # re2 bug "Argument 'pattern' has incorrect type (expected bytes, got PythonRePattern)"
LOG.w("use re instead of re2 for %s %s", rule_regex, local)
regex = re.compile(rule_regex)
if re.fullmatch(regex, local):
return True
return False
def domain_detail_auto_create(custom_domain_id):
custom_domain: CustomDomain = CustomDomain.get(custom_domain_id)
mailboxes = current_user.mailboxes()
new_auto_create_rule_form = AutoCreateRuleForm()
auto_create_test_form = AutoCreateTestForm()
auto_create_test_local, auto_create_test_result, auto_create_test_passed = (
"",
"",
False,
)
if not custom_domain or custom_domain.user_id != current_user.id:
flash("You cannot see this page", "warning")
return redirect(url_for("dashboard.index"))
if request.method == "POST":
if request.form.get("form-name") == "create-auto-create-rule":
if new_auto_create_rule_form.validate():
# make sure order isn't used before
for auto_create_rule in custom_domain.auto_create_rules:
auto_create_rule: AutoCreateRule
if auto_create_rule.order == int(
new_auto_create_rule_form.order.data
):
flash(
"Another rule with the same order already exists", "error"
)
break
else:
mailbox_ids = request.form.getlist("mailbox_ids")
# check if mailbox is not tempered with
mailboxes = []
for mailbox_id in mailbox_ids:
mailbox = Mailbox.get(mailbox_id)
if (
not mailbox
or mailbox.user_id != current_user.id
or not mailbox.verified
):
flash("Something went wrong, please retry", "warning")
return redirect(
url_for(
"dashboard.domain_detail_auto_create",
custom_domain_id=custom_domain.id,
)
)
mailboxes.append(mailbox)
if not mailboxes:
flash("You must select at least 1 mailbox", "warning")
return redirect(
url_for(
"dashboard.domain_detail_auto_create",
custom_domain_id=custom_domain.id,
)
)
try:
re.compile(new_auto_create_rule_form.regex.data)
except Exception:
flash(
f"Invalid regex {new_auto_create_rule_form.regex.data}",
"error",
)
return redirect(
url_for(
"dashboard.domain_detail_auto_create",
custom_domain_id=custom_domain.id,
)
)
rule = AutoCreateRule.create(
custom_domain_id=custom_domain.id,
order=int(new_auto_create_rule_form.order.data),
regex=new_auto_create_rule_form.regex.data,
flush=True,
)
for mailbox in mailboxes:
AutoCreateRuleMailbox.create(
auto_create_rule_id=rule.id, mailbox_id=mailbox.id
)
Session.commit()
flash("New auto create rule has been created", "success")
return redirect(
url_for(
"dashboard.domain_detail_auto_create",
custom_domain_id=custom_domain.id,
)
)
elif request.form.get("form-name") == "delete-auto-create-rule":
rule_id = request.form.get("rule-id")
rule: AutoCreateRule = AutoCreateRule.get(int(rule_id))
if not rule or rule.custom_domain_id != custom_domain.id:
flash("Something wrong, please retry", "error")
return redirect(
url_for(
"dashboard.domain_detail_auto_create",
custom_domain_id=custom_domain.id,
)
)
rule_order = rule.order
AutoCreateRule.delete(rule_id)
Session.commit()
flash(f"Rule #{rule_order} has been deleted", "success")
return redirect(
url_for(
"dashboard.domain_detail_auto_create",
custom_domain_id=custom_domain.id,
)
)
elif request.form.get("form-name") == "test-auto-create-rule":
if auto_create_test_form.validate():
local = auto_create_test_form.local.data
auto_create_test_local = local
for rule in custom_domain.auto_create_rules:
if regex_match(rule.regex, local):
auto_create_test_result = (
f"{local}@{custom_domain.domain} passes rule #{rule.order}"
)
auto_create_test_passed = True
break
else: # no rule passes
auto_create_test_result = (
f"{local}@{custom_domain.domain} doesn't pass any rule"
)
return render_template(
"dashboard/domain_detail/auto-create.html", **locals()
)
return render_template("dashboard/domain_detail/auto-create.html", **locals()) | null |
180,756 | from app.db import Session
from flask import redirect, url_for, flash, request, render_template
from flask_login import login_required, current_user
from app.dashboard.base import dashboard_bp
from app.handler.unsubscribe_encoder import UnsubscribeAction
from app.handler.unsubscribe_handler import UnsubscribeHandler
from app.models import Alias, Contact
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}>"
def unsubscribe(alias_id):
alias = Alias.get(alias_id)
if not alias:
flash("Incorrect link. Redirect you to the home page", "warning")
return redirect(url_for("dashboard.index"))
if alias.user_id != current_user.id:
flash(
"You don't have access to this page. Redirect you to the home page",
"warning",
)
return redirect(url_for("dashboard.index"))
# automatic unsubscribe, according to https://tools.ietf.org/html/rfc8058
if request.method == "POST":
alias.enabled = False
flash(f"Alias {alias.email} has been blocked", "success")
Session.commit()
return redirect(url_for("dashboard.index", highlight_alias_id=alias.id))
else: # ask user confirmation
return render_template("dashboard/unsubscribe.html", alias=alias.email) | null |
180,757 | from app.db import Session
from flask import redirect, url_for, flash, request, render_template
from flask_login import login_required, current_user
from app.dashboard.base import dashboard_bp
from app.handler.unsubscribe_encoder import UnsubscribeAction
from app.handler.unsubscribe_handler import UnsubscribeHandler
from app.models import Alias, Contact
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}>"
def block_contact(contact_id):
contact = Contact.get(contact_id)
if not contact:
flash("Incorrect link. Redirect you to the home page", "warning")
return redirect(url_for("dashboard.index"))
if contact.user_id != current_user.id:
flash(
"You don't have access to this page. Redirect you to the home page",
"warning",
)
return redirect(url_for("dashboard.index"))
# automatic unsubscribe, according to https://tools.ietf.org/html/rfc8058
if request.method == "POST":
contact.block_forward = True
flash(f"Emails sent from {contact.website_email} are now blocked", "success")
Session.commit()
return redirect(
url_for(
"dashboard.alias_contact_manager",
alias_id=contact.alias_id,
highlight_contact_id=contact.id,
)
)
else: # ask user confirmation
return render_template("dashboard/block_contact.html", contact=contact) | null |
180,758 | from app.db import Session
from flask import redirect, url_for, flash, request, render_template
from flask_login import login_required, current_user
from app.dashboard.base import dashboard_bp
from app.handler.unsubscribe_encoder import UnsubscribeAction
from app.handler.unsubscribe_handler import UnsubscribeHandler
from app.models import Alias, Contact
class UnsubscribeAction(enum.Enum):
UnsubscribeNewsletter = 1
DisableAlias = 2
DisableContact = 3
OriginalUnsubscribeMailto = 4
class UnsubscribeHandler:
def _extract_unsub_info_from_message(
self, message: Message
) -> Optional[UnsubscribeData]:
header_value = message[headers.SUBJECT]
if not header_value:
return None
return UnsubscribeEncoder.decode_subject(header_value)
def handle_unsubscribe_from_message(self, envelope: Envelope, msg: Message) -> str:
unsub_data = self._extract_unsub_info_from_message(msg)
if not unsub_data:
LOG.w("Wrong format subject %s", msg[headers.SUBJECT])
return status.E507
mailbox = Mailbox.get_by(email=envelope.mail_from)
if not mailbox:
LOG.w("Unknown mailbox %s", envelope.mail_from)
return status.E507
if unsub_data.action == UnsubscribeAction.DisableAlias:
return self._disable_alias(unsub_data.data, mailbox.user, mailbox)
elif unsub_data.action == UnsubscribeAction.DisableContact:
return self._disable_contact(unsub_data.data, mailbox.user, mailbox)
elif unsub_data.action == UnsubscribeAction.UnsubscribeNewsletter:
return self._unsubscribe_user_from_newsletter(unsub_data.data, mailbox.user)
elif unsub_data.action == UnsubscribeAction.OriginalUnsubscribeMailto:
return self._unsubscribe_original_behaviour(unsub_data.data, mailbox.user)
else:
raise Exception(f"Unknown unsubscribe action {unsub_data.action}")
def handle_unsubscribe_from_request(
self, user: User, unsub_request: str
) -> Optional[UnsubscribeData]:
unsub_data = UnsubscribeEncoder.decode_subject(unsub_request)
if not unsub_data:
LOG.w("Wrong request %s", unsub_request)
return None
if unsub_data.action == UnsubscribeAction.DisableAlias:
response_code = self._disable_alias(unsub_data.data, user)
elif unsub_data.action == UnsubscribeAction.DisableContact:
response_code = self._disable_contact(unsub_data.data, user)
elif unsub_data.action == UnsubscribeAction.UnsubscribeNewsletter:
response_code = self._unsubscribe_user_from_newsletter(
unsub_data.data, user
)
elif unsub_data.action == UnsubscribeAction.OriginalUnsubscribeMailto:
response_code = self._unsubscribe_original_behaviour(unsub_data.data, user)
else:
raise Exception(f"Unknown unsubscribe action {unsub_data.action}")
if response_code == status.E202:
return unsub_data
return None
def _disable_alias(
self, alias_id: int, user: User, mailbox: Optional[Mailbox] = None
) -> str:
alias = Alias.get(alias_id)
if not alias:
return status.E508
if alias.user_id != user.id:
LOG.w("Alias doesn't belong to user")
return status.E508
# Only alias's owning mailbox can send the unsubscribe request
if mailbox and not self._check_email_is_authorized_for_alias(
mailbox.email, alias
):
return status.E509
alias.enabled = False
Session.commit()
enable_alias_url = config.URL + f"/dashboard/?highlight_alias_id={alias.id}"
for mailbox in alias.mailboxes:
send_email(
mailbox.email,
f"Alias {alias.email} has been disabled successfully",
render(
"transactional/unsubscribe-disable-alias.txt",
user=alias.user,
alias=alias.email,
enable_alias_url=enable_alias_url,
),
render(
"transactional/unsubscribe-disable-alias.html",
user=alias.user,
alias=alias.email,
enable_alias_url=enable_alias_url,
),
)
return status.E202
def _disable_contact(
self, contact_id: int, user: User, mailbox: Optional[Mailbox] = None
) -> str:
contact = Contact.get(contact_id)
if not contact:
return status.E508
if contact.user_id != user.id:
LOG.w("Contact doesn't belong to user")
return status.E508
# Only contact's owning mailbox can send the unsubscribe request
if mailbox and not self._check_email_is_authorized_for_alias(
mailbox.email, contact.alias
):
return status.E509
alias = contact.alias
contact.block_forward = True
Session.commit()
unblock_contact_url = (
config.URL
+ f"/dashboard/alias_contact_manager/{alias.id}?highlight_contact_id={contact.id}"
)
for mailbox in alias.mailboxes:
send_email(
mailbox.email,
f"Emails from {contact.website_email} to {alias.email} are now blocked",
render(
"transactional/unsubscribe-block-contact.txt.jinja2",
user=alias.user,
alias=alias,
contact=contact,
unblock_contact_url=unblock_contact_url,
),
)
return status.E202
def _unsubscribe_user_from_newsletter(
self, user_id: int, request_user: User
) -> str:
"""return the SMTP status"""
user = User.get(user_id)
if not user:
LOG.w("No such user %s", user_id)
return status.E510
if user.id != request_user.id:
LOG.w("Unauthorized unsubscribe user from", request_user)
return status.E511
user.notification = False
Session.commit()
send_email(
user.email,
"You have been unsubscribed from SimpleLogin newsletter",
render(
"transactional/unsubscribe-newsletter.txt",
user=user,
),
render(
"transactional/unsubscribe-newsletter.html",
user=user,
),
)
return status.E202
def _check_email_is_authorized_for_alias(
self, email_address: str, alias: Alias
) -> bool:
"""return if the email_address is authorized to unsubscribe from an alias or block a contact
Usually the mail_from=mailbox.email but it can also be one of the authorized address
"""
for mailbox in alias.mailboxes:
if mailbox.email == email_address:
return True
for authorized_address in mailbox.authorized_addresses:
if authorized_address.email == email_address:
LOG.d(
"Found an authorized address for %s %s %s",
alias,
mailbox,
authorized_address,
)
return True
LOG.d(
"%s cannot disable alias %s. Alias authorized addresses:%s",
email_address,
alias,
alias.authorized_addresses,
)
return False
def _unsubscribe_original_behaviour(
self, original_unsub_data: UnsubscribeOriginalData, user: User
) -> str:
alias = Alias.get(original_unsub_data.alias_id)
if not alias:
return status.E508
if alias.user_id != user.id:
return status.E509
email_domain = get_email_domain_part(alias.email)
to_email = sanitize_email(original_unsub_data.recipient)
msg = EmailMessage()
msg[headers.TO] = to_email
msg[headers.SUBJECT] = original_unsub_data.subject
msg[headers.FROM] = alias.email
msg[headers.MESSAGE_ID] = make_msgid(domain=email_domain)
msg[headers.DATE] = formatdate()
msg[headers.CONTENT_TYPE] = "text/plain"
msg[headers.MIME_VERSION] = "1.0"
msg.set_payload("")
add_dkim_signature(msg, email_domain)
transaction = TransactionalEmail.create(email=to_email, commit=True)
sl_sendmail(
generate_verp_email(
VerpType.transactional, transaction.id, sender_domain=email_domain
),
to_email,
msg,
retries=3,
ignore_smtp_error=True,
)
return status.E202
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 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}>"
def encoded_unsubscribe(encoded_request: str):
unsub_data = UnsubscribeHandler().handle_unsubscribe_from_request(
current_user, encoded_request
)
if not unsub_data:
flash("Invalid unsubscribe request", "error")
return redirect(url_for("dashboard.index"))
if unsub_data.action == UnsubscribeAction.DisableAlias:
alias = Alias.get(unsub_data.data)
flash(f"Alias {alias.email} has been blocked", "success")
return redirect(url_for("dashboard.index", highlight_alias_id=alias.id))
if unsub_data.action == UnsubscribeAction.DisableContact:
contact = Contact.get(unsub_data.data)
flash(f"Emails sent from {contact.website_email} are now blocked", "success")
return redirect(
url_for(
"dashboard.alias_contact_manager",
alias_id=contact.alias_id,
highlight_contact_id=contact.id,
)
)
if unsub_data.action == UnsubscribeAction.UnsubscribeNewsletter:
flash("You've unsubscribed from the newsletter", "success")
return redirect(
url_for(
"dashboard.index",
)
)
if unsub_data.action == UnsubscribeAction.OriginalUnsubscribeMailto:
flash("The original unsubscribe request has been forwarded", "success")
return redirect(
url_for(
"dashboard.index",
)
)
return redirect(url_for("dashboard.index")) | null |
180,759 | from flask import render_template, flash, redirect, url_for, request
from flask_login import login_required, current_user
from app.dashboard.base import dashboard_bp
from app.dashboard.views.enter_sudo import sudo_required
from app.db import Session
from app.models import RecoveryCode
from app.utils import CSRFValidationForm
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
class RecoveryCode(Base, ModelMixin):
"""allow user to login in case you lose any of your authenticators"""
__tablename__ = "recovery_code"
__table_args__ = (sa.UniqueConstraint("user_id", "code", name="uq_recovery_code"),)
user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False)
code = sa.Column(sa.String(64), nullable=False)
used = sa.Column(sa.Boolean, nullable=False, default=False)
used_at = sa.Column(ArrowType, nullable=True, default=None)
user = orm.relationship(User)
def _hash_code(cls, code: str) -> str:
code_hmac = hmac.new(
config.RECOVERY_CODE_HMAC_SECRET.encode("utf-8"),
code.encode("utf-8"),
"sha3_224",
)
return base64.urlsafe_b64encode(code_hmac.digest()).decode("utf-8").rstrip("=")
def generate(cls, user):
"""generate recovery codes for user"""
# delete all existing codes
cls.filter_by(user_id=user.id).delete()
Session.flush()
nb_code = 0
raw_codes = []
while nb_code < _NB_RECOVERY_CODE:
raw_code = random_string(_RECOVERY_CODE_LENGTH)
encoded_code = cls._hash_code(raw_code)
if not cls.get_by(user_id=user.id, code=encoded_code):
cls.create(user_id=user.id, code=encoded_code)
raw_codes.append(raw_code)
nb_code += 1
LOG.d("Create recovery codes for %s", user)
Session.commit()
return raw_codes
def find_by_user_code(cls, user: User, code: str):
hashed_code = cls._hash_code(code)
# TODO: Only return hashed codes once there aren't unhashed codes in the db.
found_code = cls.get_by(user_id=user.id, code=hashed_code)
if found_code:
return found_code
return cls.get_by(user_id=user.id, code=code)
def empty(cls, user):
"""Delete all recovery codes for user"""
cls.filter_by(user_id=user.id).delete()
Session.commit()
class CSRFValidationForm(FlaskForm):
pass
def mfa_cancel():
if not current_user.enable_otp:
flash("you don't have MFA enabled", "warning")
return redirect(url_for("dashboard.index"))
csrf_form = CSRFValidationForm()
# user cancels TOTP
if request.method == "POST":
if not csrf_form.validate():
flash("Invalid request", "warning")
return redirect(request.url)
current_user.enable_otp = False
current_user.otp_secret = None
Session.commit()
# user does not have any 2FA enabled left, delete all recovery codes
if not current_user.two_factor_authentication_enabled():
RecoveryCode.empty(current_user)
flash("TOTP is now disabled", "warning")
return redirect(url_for("dashboard.index"))
return render_template("dashboard/mfa_cancel.html", csrf_form=csrf_form) | null |
180,760 | from flask import render_template, request, redirect, url_for, flash
from flask_login import login_required, current_user
from flask_wtf import FlaskForm
from wtforms import StringField, validators
from app import parallel_limiter
from app.config import EMAIL_SERVERS_WITH_PRIORITY
from app.dashboard.base import dashboard_bp
from app.db import Session
from app.email_utils import get_email_domain_part
from app.log import LOG
from app.models import CustomDomain, Mailbox, DomainMailbox, SLDomain
class NewCustomDomainForm(FlaskForm):
domain = StringField(
"domain", validators=[validators.DataRequired(), validators.Length(max=128)]
)
EMAIL_SERVERS_WITH_PRIORITY = sl_getenv("EMAIL_SERVERS_WITH_PRIORITY")
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
def get_email_domain_part(address):
"""
Get the domain part from email
ab@cd.com -> cd.com
"""
address = sanitize_email(address)
return address[address.find("@") + 1 :]
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}>"
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 DomainMailbox(Base, ModelMixin):
"""store the owning mailboxes for a domain"""
__tablename__ = "domain_mailbox"
__table_args__ = (
sa.UniqueConstraint("domain_id", "mailbox_id", name="uq_domain_mailbox"),
)
domain_id = sa.Column(
sa.ForeignKey(CustomDomain.id, ondelete="cascade"), nullable=False
)
mailbox_id = sa.Column(
sa.ForeignKey(Mailbox.id, ondelete="cascade"), nullable=False
)
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'}"
def custom_domain():
custom_domains = CustomDomain.filter_by(
user_id=current_user.id, is_sl_subdomain=False
).all()
mailboxes = current_user.mailboxes()
new_custom_domain_form = NewCustomDomainForm()
errors = {}
if request.method == "POST":
if request.form.get("form-name") == "create":
if not current_user.is_premium():
flash("Only premium plan can add custom domain", "warning")
return redirect(url_for("dashboard.custom_domain"))
if new_custom_domain_form.validate():
new_domain = new_custom_domain_form.domain.data.lower().strip()
if new_domain.startswith("http://"):
new_domain = new_domain[len("http://") :]
if new_domain.startswith("https://"):
new_domain = new_domain[len("https://") :]
if SLDomain.get_by(domain=new_domain):
flash("A custom domain cannot be a built-in domain.", "error")
elif CustomDomain.get_by(domain=new_domain):
flash(f"{new_domain} already used", "error")
elif get_email_domain_part(current_user.email) == new_domain:
flash(
"You cannot add a domain that you are currently using for your personal email. "
"Please change your personal email to your real email",
"error",
)
elif Mailbox.filter(
Mailbox.verified.is_(True), Mailbox.email.endswith(f"@{new_domain}")
).first():
flash(
f"{new_domain} already used in a SimpleLogin mailbox", "error"
)
else:
new_custom_domain = CustomDomain.create(
domain=new_domain, user_id=current_user.id
)
# new domain has ownership verified if its parent has the ownership verified
for root_cd in current_user.custom_domains:
if (
new_domain.endswith("." + root_cd.domain)
and root_cd.ownership_verified
):
LOG.i(
"%s ownership verified thanks to %s",
new_custom_domain,
root_cd,
)
new_custom_domain.ownership_verified = True
Session.commit()
mailbox_ids = request.form.getlist("mailbox_ids")
if mailbox_ids:
# check if mailbox is not tempered with
mailboxes = []
for mailbox_id in mailbox_ids:
mailbox = Mailbox.get(mailbox_id)
if (
not mailbox
or mailbox.user_id != current_user.id
or not mailbox.verified
):
flash("Something went wrong, please retry", "warning")
return redirect(url_for("dashboard.custom_domain"))
mailboxes.append(mailbox)
for mailbox in mailboxes:
DomainMailbox.create(
domain_id=new_custom_domain.id, mailbox_id=mailbox.id
)
Session.commit()
flash(
f"New domain {new_custom_domain.domain} is created", "success"
)
return redirect(
url_for(
"dashboard.domain_detail_dns",
custom_domain_id=new_custom_domain.id,
)
)
return render_template(
"dashboard/custom_domain.html",
custom_domains=custom_domains,
new_custom_domain_form=new_custom_domain_form,
EMAIL_SERVERS_WITH_PRIORITY=EMAIL_SERVERS_WITH_PRIORITY,
errors=errors,
mailboxes=mailboxes,
) | null |
180,761 | from dataclasses import dataclass
from flask import render_template, request, redirect, url_for, flash
from flask_login import login_required, current_user
from app import alias_utils, parallel_limiter
from app.api.serializer import get_alias_infos_with_pagination_v3, get_alias_info_v3
from app.config import ALIAS_LIMIT, PAGE_LIMIT
from app.dashboard.base import dashboard_bp
from app.db import Session
from app.extensions import limiter
from app.log import LOG
from app.models import (
Alias,
AliasGeneratorEnum,
User,
EmailLog,
Contact,
)
from app.utils import CSRFValidationForm
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",
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
def get_alias_info_v3(user: User, alias_id: int) -> AliasInfo:
# use the same query construction in get_alias_infos_with_pagination_v3
q = construct_alias_query(user)
q = q.filter(Alias.id == alias_id)
for alias, contact, email_log, nb_reply, nb_blocked, nb_forward in q:
return 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,
)
PAGE_LIMIT = 20
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
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 CSRFValidationForm(FlaskForm):
pass
def index():
query = request.args.get("query") or ""
sort = request.args.get("sort") or ""
alias_filter = request.args.get("filter") or ""
page = 0
if request.args.get("page"):
page = int(request.args.get("page"))
highlight_alias_id = None
if request.args.get("highlight_alias_id"):
try:
highlight_alias_id = int(request.args.get("highlight_alias_id"))
except ValueError:
LOG.w(
"highlight_alias_id must be a number, received %s",
request.args.get("highlight_alias_id"),
)
csrf_form = CSRFValidationForm()
if request.method == "POST":
if not csrf_form.validate():
flash("Invalid request", "warning")
return redirect(request.url)
if request.form.get("form-name") == "create-custom-email":
if current_user.can_create_new_alias():
return redirect(url_for("dashboard.custom_alias"))
else:
flash("You need to upgrade your plan to create new alias.", "warning")
elif request.form.get("form-name") == "create-random-email":
if current_user.can_create_new_alias():
scheme = int(
request.form.get("generator_scheme") or current_user.alias_generator
)
if not scheme or not AliasGeneratorEnum.has_value(scheme):
scheme = current_user.alias_generator
alias = Alias.create_new_random(user=current_user, scheme=scheme)
alias.mailbox_id = current_user.default_mailbox_id
Session.commit()
LOG.d("create new random alias %s for user %s", alias, current_user)
flash(f"Alias {alias.email} has been created", "success")
return redirect(
url_for(
"dashboard.index",
highlight_alias_id=alias.id,
query=query,
sort=sort,
filter=alias_filter,
)
)
else:
flash("You need to upgrade your plan to create new alias.", "warning")
elif request.form.get("form-name") in ("delete-alias", "disable-alias"):
try:
alias_id = int(request.form.get("alias-id"))
except ValueError:
flash("unknown error", "error")
return redirect(request.url)
alias: Alias = Alias.get(alias_id)
if not alias or alias.user_id != current_user.id:
flash("Unknown error, sorry for the inconvenience", "error")
return redirect(
url_for(
"dashboard.index",
query=query,
sort=sort,
filter=alias_filter,
)
)
if request.form.get("form-name") == "delete-alias":
LOG.d("delete alias %s", alias)
email = alias.email
alias_utils.delete_alias(alias, current_user)
flash(f"Alias {email} has been deleted", "success")
elif request.form.get("form-name") == "disable-alias":
alias.enabled = False
Session.commit()
flash(f"Alias {alias.email} has been disabled", "success")
return redirect(
url_for(
"dashboard.index",
query=query,
sort=sort,
filter=alias_filter,
page=page,
)
)
mailboxes = current_user.mailboxes()
show_intro = False
if not current_user.intro_shown:
LOG.d("Show intro to %s", current_user)
show_intro = True
# to make sure not showing intro to user again
current_user.intro_shown = True
Session.commit()
stats = get_stats(current_user)
mailbox_id = None
if alias_filter and alias_filter.startswith("mailbox:"):
mailbox_id = int(alias_filter[len("mailbox:") :])
directory_id = None
if alias_filter and alias_filter.startswith("directory:"):
directory_id = int(alias_filter[len("directory:") :])
alias_infos = get_alias_infos_with_pagination_v3(
current_user,
page,
query,
sort,
alias_filter,
mailbox_id,
directory_id,
# load 1 alias more to know whether this is the last page
page_limit=PAGE_LIMIT + 1,
)
last_page = len(alias_infos) <= PAGE_LIMIT
# remove the last alias that's added to know whether this is the last page
alias_infos = alias_infos[:PAGE_LIMIT]
# add highlighted alias in case it's not included
if highlight_alias_id and highlight_alias_id not in [
alias_info.alias.id for alias_info in alias_infos
]:
highlight_alias_info = get_alias_info_v3(
current_user, alias_id=highlight_alias_id
)
if highlight_alias_info:
alias_infos.insert(0, highlight_alias_info)
return render_template(
"dashboard/index.html",
alias_infos=alias_infos,
highlight_alias_id=highlight_alias_id,
query=query,
AliasGeneratorEnum=AliasGeneratorEnum,
mailboxes=mailboxes,
show_intro=show_intro,
page=page,
last_page=last_page,
sort=sort,
filter=alias_filter,
stats=stats,
csrf_form=csrf_form,
) | null |
180,762 | from dataclasses import dataclass
from flask import render_template, request, redirect, url_for, flash
from flask_login import login_required, current_user
from app import alias_utils, parallel_limiter
from app.api.serializer import get_alias_infos_with_pagination_v3, get_alias_info_v3
from app.config import ALIAS_LIMIT, PAGE_LIMIT
from app.dashboard.base import dashboard_bp
from app.db import Session
from app.extensions import limiter
from app.log import LOG
from app.models import (
Alias,
AliasGeneratorEnum,
User,
EmailLog,
Contact,
)
from app.utils import CSRFValidationForm
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
Here is the function:
def toggle_contact(contact_id):
"""
Block/Unblock contact
"""
contact = Contact.get(contact_id)
if not contact or contact.alias.user_id != current_user.id:
return "Forbidden", 403
contact.block_forward = not contact.block_forward
Session.commit()
if contact.block_forward:
toast_msg = f"{contact.website_email} can no longer send emails to {contact.alias.email}"
else:
toast_msg = (
f"{contact.website_email} can now send emails to {contact.alias.email}"
)
return render_template(
"partials/toggle_contact.html", contact=contact, toast_msg=toast_msg
) | Block/Unblock contact |
180,763 | from flask import render_template, flash, redirect, url_for
from flask_login import login_required, current_user
from flask_wtf import FlaskForm
from wtforms import HiddenField, validators
from app.dashboard.base import dashboard_bp
from app.dashboard.views.enter_sudo import sudo_required
from app.db import Session
from app.log import LOG
from app.models import RecoveryCode, Fido
class FidoManageForm(FlaskForm):
credential_id = HiddenField("credential_id", validators=[validators.DataRequired()])
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
LOG = _get_logger("SL")
class Fido(Base, ModelMixin):
__tablename__ = "fido"
credential_id = sa.Column(sa.String(), nullable=False, unique=True, index=True)
uuid = sa.Column(
sa.ForeignKey("users.fido_uuid", ondelete="cascade"),
unique=False,
nullable=False,
)
public_key = sa.Column(sa.String(), nullable=False, unique=True)
sign_count = sa.Column(sa.BigInteger(), nullable=False)
name = sa.Column(sa.String(128), nullable=False, unique=False)
user_id = sa.Column(sa.ForeignKey("users.id", ondelete="cascade"), nullable=True)
class RecoveryCode(Base, ModelMixin):
"""allow user to login in case you lose any of your authenticators"""
__tablename__ = "recovery_code"
__table_args__ = (sa.UniqueConstraint("user_id", "code", name="uq_recovery_code"),)
user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False)
code = sa.Column(sa.String(64), nullable=False)
used = sa.Column(sa.Boolean, nullable=False, default=False)
used_at = sa.Column(ArrowType, nullable=True, default=None)
user = orm.relationship(User)
def _hash_code(cls, code: str) -> str:
code_hmac = hmac.new(
config.RECOVERY_CODE_HMAC_SECRET.encode("utf-8"),
code.encode("utf-8"),
"sha3_224",
)
return base64.urlsafe_b64encode(code_hmac.digest()).decode("utf-8").rstrip("=")
def generate(cls, user):
"""generate recovery codes for user"""
# delete all existing codes
cls.filter_by(user_id=user.id).delete()
Session.flush()
nb_code = 0
raw_codes = []
while nb_code < _NB_RECOVERY_CODE:
raw_code = random_string(_RECOVERY_CODE_LENGTH)
encoded_code = cls._hash_code(raw_code)
if not cls.get_by(user_id=user.id, code=encoded_code):
cls.create(user_id=user.id, code=encoded_code)
raw_codes.append(raw_code)
nb_code += 1
LOG.d("Create recovery codes for %s", user)
Session.commit()
return raw_codes
def find_by_user_code(cls, user: User, code: str):
hashed_code = cls._hash_code(code)
# TODO: Only return hashed codes once there aren't unhashed codes in the db.
found_code = cls.get_by(user_id=user.id, code=hashed_code)
if found_code:
return found_code
return cls.get_by(user_id=user.id, code=code)
def empty(cls, user):
"""Delete all recovery codes for user"""
cls.filter_by(user_id=user.id).delete()
Session.commit()
def fido_manage():
if not current_user.fido_enabled():
flash("You haven't registered a security key", "warning")
return redirect(url_for("dashboard.index"))
fido_manage_form = FidoManageForm()
if fido_manage_form.validate_on_submit():
credential_id = fido_manage_form.credential_id.data
fido_key = Fido.get_by(uuid=current_user.fido_uuid, credential_id=credential_id)
if not fido_key:
flash("Unknown error, redirect back to manage page", "warning")
return redirect(url_for("dashboard.fido_manage"))
Fido.delete(fido_key.id)
Session.commit()
LOG.d(f"FIDO Key ID={fido_key.id} Removed")
flash(f"Key {fido_key.name} successfully unlinked", "success")
# Disable FIDO for the user if all keys have been deleted
if not Fido.filter_by(uuid=current_user.fido_uuid).all():
current_user.fido_uuid = None
Session.commit()
# user does not have any 2FA enabled left, delete all recovery codes
if not current_user.two_factor_authentication_enabled():
RecoveryCode.empty(current_user)
return redirect(url_for("dashboard.index"))
return redirect(url_for("dashboard.fido_manage"))
return render_template(
"dashboard/fido_manage.html",
fido_manage_form=fido_manage_form,
keys=Fido.filter_by(uuid=current_user.fido_uuid),
) | null |
180,764 | import arrow
from flask import render_template, flash, request, redirect, url_for
from flask_login import login_required, current_user
from app import s3
from app.config import JOB_BATCH_IMPORT
from app.dashboard.base import dashboard_bp
from app.dashboard.views.enter_sudo import sudo_required
from app.db import Session
from app.extensions import limiter
from app.log import LOG
from app.models import File, BatchImport, Job
from app.utils import random_string, CSRFValidationForm
JOB_BATCH_IMPORT = "batch-import"
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
LOG = _get_logger("SL")
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}>"
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 BatchImport(Base, ModelMixin):
__tablename__ = "batch_import"
user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False)
file_id = sa.Column(sa.ForeignKey(File.id, ondelete="cascade"), nullable=False)
processed = sa.Column(sa.Boolean, nullable=False, default=False)
summary = sa.Column(sa.Text, nullable=True, default=None)
file = orm.relationship(File)
user = orm.relationship(User)
def nb_alias(self):
return Alias.filter_by(batch_import_id=self.id).count()
def __repr__(self):
return f"<BatchImport {self.id}>"
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))
class CSRFValidationForm(FlaskForm):
pass
def batch_import_route():
# only for users who have custom domains
if not current_user.verified_custom_domains():
flash("Alias batch import is only available for custom domains", "warning")
if current_user.disable_import:
flash(
"you cannot use the import feature, please contact SimpleLogin team",
"error",
)
return redirect(url_for("dashboard.index"))
batch_imports = BatchImport.filter_by(
user_id=current_user.id, processed=False
).all()
csrf_form = CSRFValidationForm()
if request.method == "POST":
if not csrf_form.validate():
flash("Invalid request", "warning")
return redirect(request.url)
if len(batch_imports) > 10:
flash(
"You have too many imports already. Please wait until some get cleaned up",
"error",
)
return render_template(
"dashboard/batch_import.html",
batch_imports=batch_imports,
csrf_form=csrf_form,
)
alias_file = request.files["alias-file"]
file_path = random_string(20) + ".csv"
file = File.create(user_id=current_user.id, path=file_path)
s3.upload_from_bytesio(file_path, alias_file)
Session.flush()
LOG.d("upload file %s to s3 at %s", file, file_path)
bi = BatchImport.create(user_id=current_user.id, file_id=file.id)
Session.flush()
LOG.d("Add a batch import job %s for %s", bi, current_user)
# Schedule batch import job
Job.create(
name=JOB_BATCH_IMPORT,
payload={"batch_import_id": bi.id},
run_at=arrow.now(),
)
Session.commit()
flash(
"The file has been uploaded successfully and the import will start shortly",
"success",
)
return redirect(url_for("dashboard.batch_import_route"))
return render_template(
"dashboard/batch_import.html", batch_imports=batch_imports, csrf_form=csrf_form
) | null |
180,765 | from flask import render_template, flash, redirect, url_for
from flask_login import login_required, current_user
from flask_wtf import FlaskForm
from wtforms import StringField, validators
from app.config import ADMIN_EMAIL
from app.dashboard.base import dashboard_bp
from app.db import Session
from app.email_utils import send_email
from app.models import LifetimeCoupon
class CouponForm(FlaskForm):
code = StringField("Coupon Code", validators=[validators.DataRequired()])
ADMIN_EMAIL = os.environ.get("ADMIN_EMAIL")
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
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,
)
class LifetimeCoupon(Base, ModelMixin):
__tablename__ = "lifetime_coupon"
code = sa.Column(sa.String(128), nullable=False, unique=True)
nb_used = sa.Column(sa.Integer, nullable=False)
paid = sa.Column(sa.Boolean, default=False, server_default="0", nullable=False)
comment = sa.Column(sa.Text, nullable=True)
def lifetime_licence():
if current_user.lifetime:
flash("You already have a lifetime licence", "warning")
return redirect(url_for("dashboard.index"))
# user needs to cancel active subscription first
# to avoid being charged
sub = current_user.get_paddle_subscription()
if sub and not sub.cancelled:
flash("Please cancel your current subscription first", "warning")
return redirect(url_for("dashboard.index"))
coupon_form = CouponForm()
if coupon_form.validate_on_submit():
code = coupon_form.code.data
coupon: LifetimeCoupon = LifetimeCoupon.get_by(code=code)
if coupon and coupon.nb_used > 0:
coupon.nb_used -= 1
current_user.lifetime = True
current_user.lifetime_coupon_id = coupon.id
if coupon.paid:
current_user.paid_lifetime = True
Session.commit()
# notify admin
send_email(
ADMIN_EMAIL,
subject=f"User {current_user} used lifetime coupon({coupon.comment}). Coupon nb_used: {coupon.nb_used}",
plaintext="",
html="",
)
flash("You are upgraded to lifetime premium!", "success")
return redirect(url_for("dashboard.index"))
else:
flash(f"Code *{code}* expired or invalid", "warning")
return render_template("dashboard/lifetime_licence.html", coupon_form=coupon_form) | null |
180,766 | from flask import render_template, request
from flask_login import login_required, current_user
from app.dashboard.base import dashboard_bp
from app.log import LOG
from app.models import EmailLog
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}>"
def refused_email_route():
# Highlight a refused email
highlight_id = request.args.get("highlight_id")
if highlight_id:
try:
highlight_id = int(highlight_id)
except ValueError:
LOG.w("Cannot parse highlight_id %s", highlight_id)
highlight_id = None
email_logs: [EmailLog] = (
EmailLog.filter(
EmailLog.user_id == current_user.id, EmailLog.refused_email_id.isnot(None)
)
.order_by(EmailLog.id.desc())
.all()
)
# make sure the highlighted email_log is the first email_log
highlight_index = None
for ix, email_log in enumerate(email_logs):
if email_log.id == highlight_id:
highlight_index = ix
break
if highlight_index:
email_logs.insert(0, email_logs.pop(highlight_index))
return render_template("dashboard/refused_email.html", **locals()) | null |
180,767 | import arrow
from flask import flash, redirect, url_for, request, render_template
from flask_login import login_required, current_user
from flask_wtf import FlaskForm
from app.config import JOB_DELETE_ACCOUNT
from app.dashboard.base import dashboard_bp
from app.dashboard.views.enter_sudo import sudo_required
from app.log import LOG
from app.models import Subscription, Job
class DeleteDirForm(FlaskForm):
pass
JOB_DELETE_ACCOUNT = "delete-account"
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}>"
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}>"
def delete_account():
delete_form = DeleteDirForm()
if request.method == "POST" and request.form.get("form-name") == "delete-account":
if not delete_form.validate():
flash("Invalid request", "warning")
return render_template(
"dashboard/delete_account.html", delete_form=delete_form
)
sub: Subscription = current_user.get_paddle_subscription()
# user who has canceled can also re-subscribe
if sub and not sub.cancelled:
flash("Please cancel your current subscription first", "warning")
return redirect(url_for("dashboard.setting"))
# Schedule delete account job
LOG.w("schedule delete account job for %s", current_user)
Job.create(
name=JOB_DELETE_ACCOUNT,
payload={"user_id": current_user.id},
run_at=arrow.now(),
commit=True,
)
flash(
"Your account deletion has been scheduled. "
"You'll receive an email when the deletion is finished",
"info",
)
return redirect(url_for("dashboard.setting"))
return render_template("dashboard/delete_account.html", delete_form=delete_form) | null |
180,768 | from flask import redirect, url_for, flash, render_template, request
from flask_login import login_required, current_user
from app.config import PAGE_LIMIT
from app.dashboard.base import dashboard_bp
from app.db import Session
from app.models import Notification
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
class Notification(Base, ModelMixin):
def render(template_name, **kwargs) -> str:
def notification_route(notification_id):
notification = Notification.get(notification_id)
if not notification:
flash("Incorrect link. Redirect you to the home page", "warning")
return redirect(url_for("dashboard.index"))
if notification.user_id != current_user.id:
flash(
"You don't have access to this page. Redirect you to the home page",
"warning",
)
return redirect(url_for("dashboard.index"))
if not notification.read:
notification.read = True
Session.commit()
if request.method == "POST":
notification_title = notification.title or notification.message[:20]
Notification.delete(notification_id)
Session.commit()
flash(f"{notification_title} has been deleted", "success")
return redirect(url_for("dashboard.index"))
else:
return render_template("dashboard/notification.html", notification=notification) | null |
180,769 | from flask import redirect, url_for, flash, render_template, request
from flask_login import login_required, current_user
from app.config import PAGE_LIMIT
from app.dashboard.base import dashboard_bp
from app.db import Session
from app.models import Notification
PAGE_LIMIT = 20
class Notification(Base, ModelMixin):
__tablename__ = "notification"
user_id = sa.Column(
sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, index=True
)
message = sa.Column(sa.Text, nullable=False)
title = sa.Column(sa.String(512))
# whether user has marked the notification as read
read = sa.Column(sa.Boolean, nullable=False, default=False)
def render(template_name, **kwargs) -> str:
templates_dir = os.path.join(config.ROOT_DIR, "templates")
env = Environment(loader=FileSystemLoader(templates_dir))
template = env.get_template(template_name)
return template.render(
URL=config.URL,
LANDING_PAGE_URL=config.LANDING_PAGE_URL,
YEAR=arrow.now().year,
**kwargs,
)
def notifications_route():
page = 0
if request.args.get("page"):
page = int(request.args.get("page"))
notifications = (
Notification.filter_by(user_id=current_user.id)
.order_by(Notification.read, Notification.created_at.desc())
.limit(PAGE_LIMIT + 1) # load a record more to know whether there's more
.offset(page * PAGE_LIMIT)
.all()
)
return render_template(
"dashboard/notifications.html",
notifications=notifications,
page=page,
last_page=len(notifications) <= PAGE_LIMIT,
) | null |
180,770 | from flask import render_template, request, redirect, url_for, flash
from flask_login import login_required, current_user
from flask_wtf import FlaskForm
from wtforms import StringField, validators
from app.dashboard.base import dashboard_bp
from app.db import Session
from app.models import Contact
from app.pgp_utils import PGPException, load_public_key_and_check
class PGPContactForm(FlaskForm):
action = StringField(
"action",
validators=[validators.DataRequired(), validators.AnyOf(("save", "remove"))],
)
pgp = StringField("pgp", validators=[validators.Optional()])
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}>"
class PGPException(Exception):
pass
def load_public_key_and_check(public_key: str) -> str:
"""Same as load_public_key but will try an encryption using the new key.
If the encryption fails, remove the newly created fingerprint.
Return the fingerprint
"""
try:
import_result = gpg.import_keys(public_key)
fingerprint = import_result.fingerprints[0]
except Exception as e:
raise PGPException("Cannot load key") from e
else:
dummy_data = BytesIO(b"test")
try:
encrypt_file(dummy_data, fingerprint)
except Exception as e:
LOG.w(
"Cannot encrypt using the imported key %s %s", fingerprint, public_key
)
# remove the fingerprint
gpg.delete_keys([fingerprint])
raise PGPException("Encryption fails with the key") from e
return fingerprint
def contact_detail_route(contact_id):
contact = Contact.get(contact_id)
if not contact or contact.user_id != current_user.id:
flash("You cannot see this page", "warning")
return redirect(url_for("dashboard.index"))
alias = contact.alias
pgp_form = PGPContactForm()
if request.method == "POST":
if request.form.get("form-name") == "pgp":
if not pgp_form.validate():
flash("Invalid request", "warning")
return redirect(request.url)
if pgp_form.action.data == "save":
if not current_user.is_premium():
flash("Only premium plan can add PGP Key", "warning")
return redirect(
url_for("dashboard.contact_detail_route", contact_id=contact_id)
)
if not pgp_form.pgp.data:
flash("Invalid pgp key")
else:
contact.pgp_public_key = pgp_form.pgp.data
try:
contact.pgp_finger_print = load_public_key_and_check(
contact.pgp_public_key
)
except PGPException:
flash("Cannot add the public key, please verify it", "error")
else:
Session.commit()
flash(
f"PGP public key for {contact.email} is saved successfully",
"success",
)
return redirect(
url_for(
"dashboard.contact_detail_route", contact_id=contact_id
)
)
elif pgp_form.action.data == "remove":
# Free user can decide to remove contact PGP key
contact.pgp_public_key = None
contact.pgp_finger_print = None
Session.commit()
flash(f"PGP public key for {contact.email} is removed", "success")
return redirect(
url_for("dashboard.contact_detail_route", contact_id=contact_id)
)
return render_template(
"dashboard/contact_detail.html", contact=contact, alias=alias, pgp_form=pgp_form
) | null |
180,771 | from flask import render_template, flash, redirect, url_for, request
from flask_login import login_required, current_user
from app.config import PADDLE_MONTHLY_PRODUCT_ID, PADDLE_YEARLY_PRODUCT_ID
from app.dashboard.base import dashboard_bp
from app.db import Session
from app.log import LOG
from app.models import Subscription, PlanEnum
from app.paddle_utils import cancel_subscription, change_plan
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
LOG = _get_logger("SL")
class PlanEnum(EnumE):
class Subscription(Base, ModelMixin):
def plan_name(self):
def __repr__(self):
def cancel_subscription(subscription_id: str) -> bool:
def change_plan(user: User, subscription_id: str, plan_id) -> (bool, str):
def billing():
# sanity check: make sure this page is only for user who has paddle subscription
sub: Subscription = current_user.get_paddle_subscription()
if not sub:
flash("You don't have any active subscription", "warning")
return redirect(url_for("dashboard.index"))
if request.method == "POST":
if request.form.get("form-name") == "cancel":
LOG.w(f"User {current_user} cancels their subscription")
success = cancel_subscription(sub.subscription_id)
if success:
sub.cancelled = True
Session.commit()
flash("Your subscription has been canceled successfully", "success")
else:
flash(
"Something went wrong, sorry for the inconvenience. Please retry. "
"We are already notified and will be on it asap",
"error",
)
return redirect(url_for("dashboard.billing"))
elif request.form.get("form-name") == "change-monthly":
LOG.d(f"User {current_user} changes to monthly plan")
success, msg = change_plan(
current_user, sub.subscription_id, PADDLE_MONTHLY_PRODUCT_ID
)
if success:
sub.plan = PlanEnum.monthly
Session.commit()
flash("Your subscription has been updated", "success")
else:
if msg:
flash(msg, "error")
else:
flash(
"Something went wrong, sorry for the inconvenience. Please retry. "
"We are already notified and will be on it asap",
"error",
)
return redirect(url_for("dashboard.billing"))
elif request.form.get("form-name") == "change-yearly":
LOG.d(f"User {current_user} changes to yearly plan")
success, msg = change_plan(
current_user, sub.subscription_id, PADDLE_YEARLY_PRODUCT_ID
)
if success:
sub.plan = PlanEnum.yearly
Session.commit()
flash("Your subscription has been updated", "success")
else:
if msg:
flash(msg, "error")
else:
flash(
"Something went wrong, sorry for the inconvenience. Please retry. "
"We are already notified and will be on it asap",
"error",
)
return redirect(url_for("dashboard.billing"))
return render_template("dashboard/billing.html", sub=sub, PlanEnum=PlanEnum) | null |
180,772 | import re2 as re
from flask import render_template, request, flash, redirect, url_for
from flask_login import login_required, current_user
from app.dashboard.base import dashboard_bp
from app.db import Session
from app.models import Referral, Payout
_REFERRAL_PATTERN = r"[0-9a-z-_]{3,}"
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
class Referral(Base, ModelMixin):
def nb_user(self) -> int:
def nb_paid_user(self) -> int:
def link(self):
def __repr__(self):
class Payout(Base, ModelMixin):
def referral_route():
if request.method == "POST":
if request.form.get("form-name") == "create":
code = request.form.get("code")
if re.fullmatch(_REFERRAL_PATTERN, code) is None:
flash(
"At least 3 characters. Only lowercase letters, "
"numbers, dashes (-) and underscores (_) are currently supported.",
"error",
)
return redirect(url_for("dashboard.referral_route"))
if Referral.get_by(code=code):
flash("Code already used", "error")
return redirect(url_for("dashboard.referral_route"))
name = request.form.get("name")
referral = Referral.create(user_id=current_user.id, code=code, name=name)
Session.commit()
flash("A new referral code has been created", "success")
return redirect(
url_for("dashboard.referral_route", highlight_id=referral.id)
)
elif request.form.get("form-name") == "update":
referral_id = request.form.get("referral-id")
referral = Referral.get(referral_id)
if referral and referral.user_id == current_user.id:
referral.name = request.form.get("name")
Session.commit()
flash("Referral name updated", "success")
return redirect(
url_for("dashboard.referral_route", highlight_id=referral.id)
)
elif request.form.get("form-name") == "delete":
referral_id = request.form.get("referral-id")
referral = Referral.get(referral_id)
if referral and referral.user_id == current_user.id:
Referral.delete(referral.id)
Session.commit()
flash("Referral deleted", "success")
return redirect(url_for("dashboard.referral_route"))
# Highlight a referral
highlight_id = request.args.get("highlight_id")
if highlight_id:
highlight_id = int(highlight_id)
referrals = Referral.filter_by(user_id=current_user.id).all()
# make sure the highlighted referral is the first referral
highlight_index = None
for ix, referral in enumerate(referrals):
if referral.id == highlight_id:
highlight_index = ix
break
if highlight_index:
referrals.insert(0, referrals.pop(highlight_index))
payouts = Payout.filter_by(user_id=current_user.id).all()
return render_template("dashboard/referral.html", **locals()) | null |
180,773 | import asyncio
import time
from email.message import Message
import aiospamc
from app.config import SPAMASSASSIN_HOST
from app.log import LOG
from app.message_utils import message_to_bytes
from app.models import EmailLog
from app.spamassassin_utils import SpamAssassin
SPAMASSASSIN_HOST = os.environ.get("SPAMASSASSIN_HOST")
LOG = _get_logger("SL")
def message_to_bytes(msg: Message) -> bytes:
"""replace Message.as_bytes() method by trying different policies"""
for generator_policy in [None, policy.SMTP, policy.SMTPUTF8]:
try:
return msg.as_bytes(policy=generator_policy)
except Exception:
LOG.w("as_bytes() fails with %s policy", policy, exc_info=True)
msg_string = msg.as_string()
try:
return msg_string.encode()
except Exception:
LOG.w("as_string().encode() fails", exc_info=True)
return msg_string.encode(errors="replace")
async def get_spam_score_async(message: Message) -> float:
sa_input = message_to_bytes(message)
# Spamassassin requires to have an ending linebreak
if not sa_input.endswith(b"\n"):
LOG.d("add linebreak to spamassassin input")
sa_input += b"\n"
try:
# wait for at max 300s which is the default spamd timeout-child
response = await asyncio.wait_for(
aiospamc.check(sa_input, host=SPAMASSASSIN_HOST), timeout=300
)
return response.headers["Spam"].score
except asyncio.TimeoutError:
LOG.e("SpamAssassin timeout")
# return a negative score so the message is always considered as ham
return -999
except Exception:
LOG.e("SpamAssassin exception")
return -999 | null |
180,774 | import os
from io import BytesIO
from typing import Union
import gnupg
import pgpy
from memory_profiler import memory_usage
from pgpy import PGPMessage
from app.config import GNUPGHOME, PGP_SENDER_PRIVATE_KEY
from app.log import LOG
from app.models import Mailbox, Contact
LOG = _get_logger("SL")
def hard_exit():
pid = os.getpid()
LOG.w("kill pid %s", pid)
os.kill(pid, 9) | null |
180,775 | import time
from typing import List
import arrow
from sqlalchemy.sql.expression import or_, and_
from app import config
from app.db import Session
from app.email_utils import (
send_email,
render,
)
from app.import_utils import handle_batch_import
from app.jobs.export_user_data_job import ExportUserDataJob
from app.log import LOG
from app.models import User, Job, BatchImport, Mailbox, CustomDomain, JobState
from server import create_light_app
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,
)
def onboarding_browser_extension(user):
comm_email, unsubscribe_link, via_email = user.get_communication_email()
if not comm_email:
return
send_email(
comm_email,
"SimpleLogin Tip: Chrome/Firefox/Safari extensions and Android/iOS apps",
render(
"com/onboarding/browser-extension.txt",
user=user,
to_email=comm_email,
),
render(
"com/onboarding/browser-extension.html",
user=user,
to_email=comm_email,
),
unsubscribe_link,
via_email,
retries=3,
ignore_smtp_error=True,
) | null |
180,776 | import time
from typing import List
import arrow
from sqlalchemy.sql.expression import or_, and_
from app import config
from app.db import Session
from app.email_utils import (
send_email,
render,
)
from app.import_utils import handle_batch_import
from app.jobs.export_user_data_job import ExportUserDataJob
from app.log import LOG
from app.models import User, Job, BatchImport, Mailbox, CustomDomain, JobState
from server import create_light_app
def onboarding_send_from_alias(user):
comm_email, unsubscribe_link, via_email = user.get_communication_email()
if not comm_email:
return
send_email(
comm_email,
"SimpleLogin Tip: Send emails from your alias",
render(
"com/onboarding/send-from-alias.txt.j2",
user=user,
to_email=comm_email,
),
render("com/onboarding/send-from-alias.html", user=user, to_email=comm_email),
unsubscribe_link,
via_email,
retries=3,
ignore_smtp_error=True,
)
def onboarding_pgp(user):
comm_email, unsubscribe_link, via_email = user.get_communication_email()
if not comm_email:
return
send_email(
comm_email,
"SimpleLogin Tip: Secure your emails with PGP",
render("com/onboarding/pgp.txt", user=user, to_email=comm_email),
render("com/onboarding/pgp.html", user=user, to_email=comm_email),
unsubscribe_link,
via_email,
retries=3,
ignore_smtp_error=True,
)
def onboarding_mailbox(user):
comm_email, unsubscribe_link, via_email = user.get_communication_email()
if not comm_email:
return
send_email(
comm_email,
"SimpleLogin Tip: Multiple mailboxes",
render("com/onboarding/mailbox.txt", user=user, to_email=comm_email),
render("com/onboarding/mailbox.html", user=user, to_email=comm_email),
unsubscribe_link,
via_email,
retries=3,
ignore_smtp_error=True,
)
def welcome_proton(user):
comm_email, _, _ = user.get_communication_email()
if not comm_email:
return
send_email(
comm_email,
"Welcome to SimpleLogin, an email masking service provided by Proton",
render(
"com/onboarding/welcome-proton-user.txt.jinja2",
user=user,
to_email=comm_email,
),
render(
"com/onboarding/welcome-proton-user.html",
user=user,
to_email=comm_email,
),
retries=3,
ignore_smtp_error=True,
)
def delete_mailbox_job(job: Job):
mailbox_id = job.payload.get("mailbox_id")
mailbox = Mailbox.get(mailbox_id)
if not mailbox:
return
transfer_mailbox_id = job.payload.get("transfer_mailbox_id")
alias_transferred_to = None
if transfer_mailbox_id:
transfer_mailbox = Mailbox.get(transfer_mailbox_id)
if transfer_mailbox:
alias_transferred_to = transfer_mailbox.email
for alias in mailbox.aliases:
if alias.mailbox_id == mailbox.id:
alias.mailbox_id = transfer_mailbox.id
if transfer_mailbox in alias._mailboxes:
alias._mailboxes.remove(transfer_mailbox)
else:
alias._mailboxes.remove(mailbox)
if transfer_mailbox not in alias._mailboxes:
alias._mailboxes.append(transfer_mailbox)
Session.commit()
mailbox_email = mailbox.email
user = mailbox.user
Mailbox.delete(mailbox_id)
Session.commit()
LOG.d("Mailbox %s %s deleted", mailbox_id, mailbox_email)
if alias_transferred_to:
send_email(
user.email,
f"Your mailbox {mailbox_email} has been deleted",
f"""Mailbox {mailbox_email} and its alias have been transferred to {alias_transferred_to}.
Regards,
SimpleLogin team.
""",
retries=3,
)
else:
send_email(
user.email,
f"Your mailbox {mailbox_email} has been deleted",
f"""Mailbox {mailbox_email} along with its aliases have been deleted successfully.
Regards,
SimpleLogin team.
""",
retries=3,
)
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,
)
def handle_batch_import(batch_import: BatchImport):
user = batch_import.user
batch_import.processed = True
Session.commit()
LOG.d("Start batch import for %s %s", batch_import, user)
file_url = s3.get_url(batch_import.file.path)
LOG.d("Download file %s from %s", batch_import.file, file_url)
r = requests.get(file_url)
lines = [line.decode("utf-8") for line in r.iter_lines()]
import_from_csv(batch_import, user, lines)
class ExportUserDataJob:
REMOVE_FIELDS = {
"User": ("otp_secret", "password"),
"Alias": ("ts_vector", "transfer_token", "hibp_last_check"),
"CustomDomain": ("ownership_txt_token",),
}
def __init__(self, user: User):
self._user: User = user
def _get_paginated_model(self, model_class, page_size=50) -> List:
objects = []
page = 0
db_objects = []
while page == 0 or len(db_objects) == page_size:
db_objects = (
Session.query(model_class)
.filter(model_class.user_id == self._user.id)
.order_by(model_class.id)
.limit(page_size)
.offset(page * page_size)
.all()
)
objects.extend(db_objects)
page += 1
return objects
def _get_aliases(self) -> List[Alias]:
return self._get_paginated_model(Alias)
def _get_mailboxes(self) -> List[Mailbox]:
return self._get_paginated_model(Mailbox)
def _get_contacts(self) -> List[Contact]:
return self._get_paginated_model(Contact)
def _get_directories(self) -> List[Directory]:
return self._get_paginated_model(Directory)
def _get_email_logs(self) -> List[EmailLog]:
return self._get_paginated_model(EmailLog)
def _get_domains(self) -> List[CustomDomain]:
return self._get_paginated_model(CustomDomain)
def _get_refused_emails(self) -> List[RefusedEmail]:
return self._get_paginated_model(RefusedEmail)
def _model_to_dict(cls, object: Base) -> Dict:
data = {}
fields_to_filter = cls.REMOVE_FIELDS.get(object.__class__.__name__, ())
for column in object.__table__.columns:
if column.name in fields_to_filter:
continue
value = getattr(object, column.name)
if isinstance(value, arrow.Arrow):
value = value.isoformat()
if issubclass(value.__class__, EnumE):
value = value.value
data[column.name] = value
return data
def _build_zip(self) -> BytesIO:
memfile = BytesIO()
with zipfile.ZipFile(memfile, "w", zipfile.ZIP_DEFLATED) as zf:
zf.writestr(
"user.json", json.dumps(ExportUserDataJob._model_to_dict(self._user))
)
for model_name, get_models in [
("aliases", self._get_aliases),
("mailboxes", self._get_mailboxes),
("contacts", self._get_contacts),
("directories", self._get_directories),
("domains", self._get_domains),
("email_logs", self._get_email_logs),
# not include RefusedEmail as they are not usable by user and are automatically deleted
# ("refused_emails", self._get_refused_emails),
]:
model_objs = get_models()
data = json.dumps(
[
ExportUserDataJob._model_to_dict(model_obj)
for model_obj in model_objs
]
)
zf.writestr(f"{model_name}.json", data)
memfile.seek(0)
return memfile
def run(self):
zipped_contents = self._build_zip()
to_email = self._user.email
msg = MIMEMultipart()
msg[headers.SUBJECT] = "Your SimpleLogin data"
msg[headers.FROM] = f'"SimpleLogin (noreply)" <{config.NOREPLY}>'
msg[headers.TO] = to_email
msg.attach(MIMEText(render("transactional/user-report.html"), "html"))
attachment = MIMEApplication(zipped_contents.read())
attachment.add_header(
"Content-Disposition", "attachment", filename="user_report.zip"
)
attachment.add_header("Content-Type", "application/zip")
msg.attach(attachment)
# add DKIM
email_domain = config.NOREPLY[config.NOREPLY.find("@") + 1 :]
add_dkim_signature(msg, email_domain)
transaction = TransactionalEmail.create(email=to_email, commit=True)
sl_sendmail(
generate_verp_email(
VerpType.transactional,
transaction.id,
get_email_domain_part(config.NOREPLY),
),
to_email,
msg,
ignore_smtp_error=False,
)
def create_from_job(job: Job) -> Optional[ExportUserDataJob]:
user = User.get(job.payload["user_id"])
if not user:
return None
return ExportUserDataJob(user)
def store_job_in_db(self) -> Optional[Job]:
jobs_in_db = (
Session.query(Job)
.filter(
Job.name == config.JOB_SEND_USER_REPORT,
Job.payload.op("->")("user_id").cast(sqlalchemy.TEXT)
== str(self._user.id),
Job.taken.is_(False),
)
.count()
)
if jobs_in_db > 0:
return None
return Job.create(
name=config.JOB_SEND_USER_REPORT,
payload={"user_id": self._user.id},
run_at=arrow.now(),
commit=True,
)
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 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 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 BatchImport(Base, ModelMixin):
__tablename__ = "batch_import"
user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False)
file_id = sa.Column(sa.ForeignKey(File.id, ondelete="cascade"), nullable=False)
processed = sa.Column(sa.Boolean, nullable=False, default=False)
summary = sa.Column(sa.Text, nullable=True, default=None)
file = orm.relationship(File)
user = orm.relationship(User)
def nb_alias(self):
return Alias.filter_by(batch_import_id=self.id).count()
def __repr__(self):
return f"<BatchImport {self.id}>"
def process_job(job: Job):
if job.name == config.JOB_ONBOARDING_1:
user_id = job.payload.get("user_id")
user = User.get(user_id)
# user might delete their account in the meantime
# or disable the notification
if user and user.notification and user.activated:
LOG.d("send onboarding send-from-alias email to user %s", user)
onboarding_send_from_alias(user)
elif job.name == config.JOB_ONBOARDING_2:
user_id = job.payload.get("user_id")
user = User.get(user_id)
# user might delete their account in the meantime
# or disable the notification
if user and user.notification and user.activated:
LOG.d("send onboarding mailbox email to user %s", user)
onboarding_mailbox(user)
elif job.name == config.JOB_ONBOARDING_4:
user_id = job.payload.get("user_id")
user = User.get(user_id)
# user might delete their account in the meantime
# or disable the notification
if user and user.notification and user.activated:
LOG.d("send onboarding pgp email to user %s", user)
onboarding_pgp(user)
elif job.name == config.JOB_BATCH_IMPORT:
batch_import_id = job.payload.get("batch_import_id")
batch_import = BatchImport.get(batch_import_id)
handle_batch_import(batch_import)
elif job.name == config.JOB_DELETE_ACCOUNT:
user_id = job.payload.get("user_id")
user = User.get(user_id)
if not user:
LOG.i("No user found for %s", user_id)
return
user_email = user.email
LOG.w("Delete user %s", user)
User.delete(user.id)
Session.commit()
send_email(
user_email,
"Your SimpleLogin account has been deleted",
render("transactional/account-delete.txt"),
render("transactional/account-delete.html"),
retries=3,
)
elif job.name == config.JOB_DELETE_MAILBOX:
delete_mailbox_job(job)
elif job.name == config.JOB_DELETE_DOMAIN:
custom_domain_id = job.payload.get("custom_domain_id")
custom_domain = CustomDomain.get(custom_domain_id)
if not custom_domain:
return
domain_name = custom_domain.domain
user = custom_domain.user
CustomDomain.delete(custom_domain.id)
Session.commit()
LOG.d("Domain %s deleted", domain_name)
send_email(
user.email,
f"Your domain {domain_name} has been deleted",
f"""Domain {domain_name} along with its aliases are deleted successfully.
Regards,
SimpleLogin team.
""",
retries=3,
)
elif job.name == config.JOB_SEND_USER_REPORT:
export_job = ExportUserDataJob.create_from_job(job)
if export_job:
export_job.run()
elif job.name == config.JOB_SEND_PROTON_WELCOME_1:
user_id = job.payload.get("user_id")
user = User.get(user_id)
if user and user.activated:
LOG.d("send proton welcome email to user %s", user)
welcome_proton(user)
else:
LOG.e("Unknown job name %s", job.name) | null |
180,777 | import time
from typing import List
import arrow
from sqlalchemy.sql.expression import or_, and_
from app import config
from app.db import Session
from app.email_utils import (
send_email,
render,
)
from app.import_utils import handle_batch_import
from app.jobs.export_user_data_job import ExportUserDataJob
from app.log import LOG
from app.models import User, Job, BatchImport, Mailbox, CustomDomain, JobState
from server import create_light_app
class JobState(EnumE):
class Job(Base, ModelMixin):
def __repr__(self):
def get_jobs_to_run() -> List[Job]:
# Get jobs that match all conditions:
# - Job.state == ready OR (Job.state == taken AND Job.taken_at < now - 30 mins AND Job.attempts < 5)
# - Job.run_at is Null OR Job.run_at < now + 10 mins
taken_at_earliest = arrow.now().shift(minutes=-config.JOB_TAKEN_RETRY_WAIT_MINS)
run_at_earliest = arrow.now().shift(minutes=+10)
query = Job.filter(
and_(
or_(
Job.state == JobState.ready.value,
and_(
Job.state == JobState.taken.value,
Job.taken_at < taken_at_earliest,
Job.attempts < config.JOB_MAX_ATTEMPTS,
),
),
or_(Job.run_at.is_(None), and_(Job.run_at <= run_at_earliest)),
)
)
return query.all() | null |
180,778 | from app.config import (
ALIAS_DOMAINS,
PREMIUM_ALIAS_DOMAINS,
)
from app.db import Session
from app.log import LOG
from app.models import Mailbox, Contact, SLDomain, Partner
from app.pgp_utils import load_public_key
from app.proton.utils import PROTON_PARTNER_NAME
from server import create_light_app
Session = scoped_session(sessionmaker(bind=connection))
Session: sqlalchemy.orm.Session
LOG = _get_logger("SL")
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 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 load_public_key(public_key: str) -> str:
"""Load a public key into keyring and return the fingerprint. If error, raise Exception"""
try:
import_result = gpg.import_keys(public_key)
return import_result.fingerprints[0]
except Exception as e:
raise PGPException("Cannot load key") from e
The provided code snippet includes necessary dependencies for implementing the `load_pgp_public_keys` function. Write a Python function `def load_pgp_public_keys()` to solve the following problem:
Load PGP public key to keyring
Here is the function:
def load_pgp_public_keys():
"""Load PGP public key to keyring"""
for mailbox in Mailbox.filter(Mailbox.pgp_public_key.isnot(None)).all():
LOG.d("Load PGP key for mailbox %s", mailbox)
fingerprint = load_public_key(mailbox.pgp_public_key)
# sanity check
if fingerprint != mailbox.pgp_finger_print:
LOG.e("fingerprint %s different for mailbox %s", fingerprint, mailbox)
mailbox.pgp_finger_print = fingerprint
Session.commit()
for contact in Contact.filter(Contact.pgp_public_key.isnot(None)).all():
LOG.d("Load PGP key for %s", contact)
fingerprint = load_public_key(contact.pgp_public_key)
# sanity check
if fingerprint != contact.pgp_finger_print:
LOG.e("fingerprint %s different for contact %s", fingerprint, contact)
contact.pgp_finger_print = fingerprint
Session.commit()
LOG.d("Finish load_pgp_public_keys") | Load PGP public key to keyring |
180,780 | import math
from dataclasses import dataclass
from typing import Any, Optional, Tuple
import fairscale.nn.model_parallel.initialize as fs_init
import torch
import torch.nn.functional as F
from fairscale.nn.model_parallel.layers import (
ColumnParallelLinear,
ParallelEmbedding,
RowParallelLinear,
)
from torch import nn
if torch.cuda.is_available():
device = "cuda"
elif torch.backends.mps.is_available():
device = "mps"
else:
device = "cpu"
def precompute_freqs_cis(dim: int, end: int, theta: float = 10000.0):
freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
t = torch.arange(end, device=freqs.device, dtype=torch.float32) # type: ignore
freqs = torch.outer(t, freqs) # type: ignore
freqs_cis = torch.polar(torch.ones_like(freqs), freqs) # complex64
return freqs_cis | null |
180,781 | import math
from dataclasses import dataclass
from typing import Any, Optional, Tuple
import fairscale.nn.model_parallel.initialize as fs_init
import torch
import torch.nn.functional as F
from fairscale.nn.model_parallel.layers import (
ColumnParallelLinear,
ParallelEmbedding,
RowParallelLinear,
)
from torch import nn
if torch.cuda.is_available():
device = "cuda"
elif torch.backends.mps.is_available():
device = "mps"
else:
device = "cpu"
def reshape_for_broadcast(freqs_cis: torch.Tensor, x: torch.Tensor):
ndim = x.ndim
assert 0 <= 1 < ndim
assert freqs_cis.shape == (x.shape[1], x.shape[-1])
shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
return freqs_cis.view(*shape)
def apply_rotary_emb(
xq: torch.Tensor,
xk: torch.Tensor,
freqs_cis: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor]:
if not torch.cuda.is_available():
xq = xq.to('cpu')
xk = xk.to('cpu')
xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
freqs_cis = reshape_for_broadcast(freqs_cis, xq_)
xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3)
xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3)
return xq_out.type_as(xq).to(device), xk_out.type_as(xk).to(device) | null |
180,782 | import math
from dataclasses import dataclass
from typing import Any, Optional, Tuple
import fairscale.nn.model_parallel.initialize as fs_init
import torch
import torch.nn.functional as F
from fairscale.nn.model_parallel.layers import (
ColumnParallelLinear,
ParallelEmbedding,
RowParallelLinear,
)
from torch import nn
if torch.cuda.is_available():
device = "cuda"
elif torch.backends.mps.is_available():
device = "mps"
else:
device = "cpu"
The provided code snippet includes necessary dependencies for implementing the `repeat_kv` function. Write a Python function `def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor` to solve the following problem:
torch.repeat_interleave(x, dim=2, repeats=n_rep)
Here is the function:
def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
"""torch.repeat_interleave(x, dim=2, repeats=n_rep)"""
bs, slen, n_kv_heads, head_dim = x.shape
if n_rep == 1:
return x
return (
x[:, :, :, None, :]
.expand(bs, slen, n_kv_heads, n_rep, head_dim)
.reshape(bs, slen, n_kv_heads * n_rep, head_dim)
) | torch.repeat_interleave(x, dim=2, repeats=n_rep) |
180,783 | import json
import os
import sys
import time
from pathlib import Path
from typing import List, Literal, Optional, Tuple, TypedDict
import torch
import torch.nn.functional as F
from fairscale.nn.model_parallel.initialize import (
get_model_parallel_rank,
initialize_model_parallel,
model_parallel_is_initialized,
)
from llama.model import ModelArgs, Transformer
from llama.tokenizer import Tokenizer
if torch.cuda.is_available():
device = "cuda"
elif torch.backends.mps.is_available():
device = "mps"
else:
device = "cpu"
def sample_top_p(probs, p):
probs_sort, probs_idx = torch.sort(probs, dim=-1, descending=True)
probs_sum = torch.cumsum(probs_sort, dim=-1)
mask = probs_sum - probs_sort > p
probs_sort[mask] = 0.0
probs_sort.div_(probs_sort.sum(dim=-1, keepdim=True))
next_token = torch.multinomial(probs_sort, num_samples=1)
next_token = torch.gather(probs_idx, -1, next_token)
return next_token | null |
180,784 | import json
import os
import sys
import time
from pathlib import Path
from typing import List, Literal, Optional, Tuple, TypedDict
import torch
import torch.nn.functional as F
from fairscale.nn.model_parallel.initialize import (
get_model_parallel_rank,
initialize_model_parallel,
model_parallel_is_initialized,
)
from llama.model import ModelArgs, Transformer
from llama.tokenizer import Tokenizer
class Tokenizer:
def __init__(self, model_path: str):
# reload tokenizer
assert os.path.isfile(model_path), model_path
self.sp_model = SentencePieceProcessor(model_file=model_path)
logger.info(f"Reloaded SentencePiece model from {model_path}")
# BOS / EOS token IDs
self.n_words: int = self.sp_model.vocab_size()
self.bos_id: int = self.sp_model.bos_id()
self.eos_id: int = self.sp_model.eos_id()
self.pad_id: int = self.sp_model.pad_id()
# token IDs for special infilling tokens
self.prefix_id: Optional[int] = self.sp_model.piece_to_id("▁<PRE>") or None
self.middle_id: Optional[int] = self.sp_model.piece_to_id("▁<MID>") or None
self.suffix_id: Optional[int] = self.sp_model.piece_to_id("▁<SUF>") or None
self.eot_id: Optional[int] = self.sp_model.piece_to_id("▁<EOT>") or None
# marker for turn-based step format
self.step_id: Optional[int] = self.sp_model.piece_to_id("<step>") or None
logger.info(
f"#words: {self.n_words} - BOS ID: {self.bos_id} - EOS ID: {self.eos_id} "
f"- PRE ID: {self.prefix_id} - MID ID: {self.middle_id} - SUF ID: {self.suffix_id} - EOT ID: {self.eot_id} - STEP ID: {self.step_id}"
)
assert self.sp_model.vocab_size() == self.sp_model.get_piece_size()
def encode(self, s: str, bos: bool, eos: bool) -> List[int]:
assert type(s) is str
t = self.sp_model.encode(s)
if bos:
t = [self.bos_id] + t
if eos:
t = t + [self.eos_id]
return t
def decode(self, t: List[int]) -> str:
return self.sp_model.decode(list(filter(lambda tk: tk != -1, t)))
def token_piece(self, t: int) -> str:
return self.sp_model.id_to_piece(t)
def encode_infilling(self, s: str) -> List[int]:
"""Encode a string without an implicit leading space."""
return self.sp_model.encode("☺" + s)[2:]
def decode_infilling(self, t: List[int]) -> str:
"""Decode a string without an implicit leading space."""
return self.sp_model.decode([self.sp_model.piece_to_id("☺")] + t)[1:]
The provided code snippet includes necessary dependencies for implementing the `infilling_prompt_tokens` function. Write a Python function `def infilling_prompt_tokens( tokenizer: Tokenizer, pre: str, suf: str, suffix_first: bool = False, ) -> List[int]` to solve the following problem:
Format and encode an infilling problem. If `suffix_first` is set, format in suffix-prefix-middle format.
Here is the function:
def infilling_prompt_tokens(
tokenizer: Tokenizer,
pre: str,
suf: str,
suffix_first: bool = False,
) -> List[int]:
"""
Format and encode an infilling problem.
If `suffix_first` is set, format in suffix-prefix-middle format.
"""
assert tokenizer.prefix_id is not None
assert tokenizer.middle_id is not None
assert tokenizer.suffix_id is not None
if suffix_first:
# format as "<PRE> <SUF>{suf} <MID> {pre}"
return (
[tokenizer.bos_id, tokenizer.prefix_id, tokenizer.suffix_id]
+ tokenizer.encode_infilling(suf)
+ [tokenizer.middle_id]
+ tokenizer.encode(pre, bos=False, eos=False)
)
else:
# format as "<PRE> {pre} <SUF>{suf} <MID>"
return (
[tokenizer.bos_id, tokenizer.prefix_id]
+ tokenizer.encode(pre, bos=False, eos=False)
+ [tokenizer.suffix_id]
+ tokenizer.encode_infilling(suf)
+ [tokenizer.middle_id]
) | Format and encode an infilling problem. If `suffix_first` is set, format in suffix-prefix-middle format. |
180,785 | import json
import os
import sys
import time
from pathlib import Path
from typing import List, Literal, Optional, Tuple, TypedDict
import torch
import torch.nn.functional as F
from fairscale.nn.model_parallel.initialize import (
get_model_parallel_rank,
initialize_model_parallel,
model_parallel_is_initialized,
)
from llama.model import ModelArgs, Transformer
from llama.tokenizer import Tokenizer
Dialog = List[Message]
class Tokenizer:
def __init__(self, model_path: str):
# reload tokenizer
assert os.path.isfile(model_path), model_path
self.sp_model = SentencePieceProcessor(model_file=model_path)
logger.info(f"Reloaded SentencePiece model from {model_path}")
# BOS / EOS token IDs
self.n_words: int = self.sp_model.vocab_size()
self.bos_id: int = self.sp_model.bos_id()
self.eos_id: int = self.sp_model.eos_id()
self.pad_id: int = self.sp_model.pad_id()
# token IDs for special infilling tokens
self.prefix_id: Optional[int] = self.sp_model.piece_to_id("▁<PRE>") or None
self.middle_id: Optional[int] = self.sp_model.piece_to_id("▁<MID>") or None
self.suffix_id: Optional[int] = self.sp_model.piece_to_id("▁<SUF>") or None
self.eot_id: Optional[int] = self.sp_model.piece_to_id("▁<EOT>") or None
# marker for turn-based step format
self.step_id: Optional[int] = self.sp_model.piece_to_id("<step>") or None
logger.info(
f"#words: {self.n_words} - BOS ID: {self.bos_id} - EOS ID: {self.eos_id} "
f"- PRE ID: {self.prefix_id} - MID ID: {self.middle_id} - SUF ID: {self.suffix_id} - EOT ID: {self.eot_id} - STEP ID: {self.step_id}"
)
assert self.sp_model.vocab_size() == self.sp_model.get_piece_size()
def encode(self, s: str, bos: bool, eos: bool) -> List[int]:
assert type(s) is str
t = self.sp_model.encode(s)
if bos:
t = [self.bos_id] + t
if eos:
t = t + [self.eos_id]
return t
def decode(self, t: List[int]) -> str:
return self.sp_model.decode(list(filter(lambda tk: tk != -1, t)))
def token_piece(self, t: int) -> str:
return self.sp_model.id_to_piece(t)
def encode_infilling(self, s: str) -> List[int]:
"""Encode a string without an implicit leading space."""
return self.sp_model.encode("☺" + s)[2:]
def decode_infilling(self, t: List[int]) -> str:
"""Decode a string without an implicit leading space."""
return self.sp_model.decode([self.sp_model.piece_to_id("☺")] + t)[1:]
The provided code snippet includes necessary dependencies for implementing the `dialog_prompt_tokens` function. Write a Python function `def dialog_prompt_tokens(tokenizer: Tokenizer, dialog: Dialog) -> List[int]` to solve the following problem:
Prompt formatting for multi-turn dialogs. The dialog is expected to start with a system message and then alternate between user and assistant messages.
Here is the function:
def dialog_prompt_tokens(tokenizer: Tokenizer, dialog: Dialog) -> List[int]:
"""
Prompt formatting for multi-turn dialogs.
The dialog is expected to start with a system message and then alternate
between user and assistant messages.
"""
assert tokenizer.step_id is not None
assert all([msg["role"] == "user" for msg in dialog[1::2]]) and all(
[msg["role"] == "assistant" for msg in dialog[2::2]]
), (
"model only supports 'system', 'user' and 'assistant' roles, "
"starting with 'system', then 'user' and alternating (u/a/u/a/u...)"
)
assert (
dialog[-1]["role"] == "user"
), f"Last message must be from user, got {dialog[-1]['role']}"
# Format context
dialog_tokens: List[int] = [tokenizer.bos_id]
headers: List[str] = []
for message in dialog:
headers.clear()
headers.append(f"Source: {message['role'].strip()}")
if message.get("destination") is not None:
headers.append(f"Destination: {message['destination'].strip()}")
header = " " + "\n".join(headers)
dialog_tokens += tokenizer.encode(header, bos=False, eos=False)
if message["content"]:
body = "\n\n " + message["content"].strip()
dialog_tokens += tokenizer.encode(body, bos=False, eos=False)
dialog_tokens += [tokenizer.step_id]
# Start of reply
headers.clear()
headers.append("Source: assistant")
headers.append("Destination: user")
header = " " + "\n".join(headers)
dialog_tokens += tokenizer.encode(header, bos=False, eos=False)
dialog_tokens += tokenizer.encode("\n\n ", bos=False, eos=False)
return dialog_tokens | Prompt formatting for multi-turn dialogs. The dialog is expected to start with a system message and then alternate between user and assistant messages. |
180,786 | import torch
import torch.nn as nn
import torchvision.models.resnet as resnet
import numpy as np
import math
import sys
from bodymocap.utils.geometry import rot6d_to_rotmat
class Bottleneck(nn.Module):
""" Redefinition of Bottleneck residual block
Adapted from the official PyTorch implementation
"""
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(planes)
self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)
self.bn3 = nn.BatchNorm2d(planes * 4)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class HMR(nn.Module):
""" SMPL Iterative Regressor with ResNet50 backbone
"""
def __init__(self, block, layers, smpl_mean_params):
self.inplanes = 64
super(HMR, self).__init__()
npose = 24 * 6
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
self.avgpool = nn.AvgPool2d(7, stride=1)
self.fc1 = nn.Linear(512 * block.expansion + npose + 13, 1024)
self.drop1 = nn.Dropout()
self.fc2 = nn.Linear(1024, 1024)
self.drop2 = nn.Dropout()
self.decpose = nn.Linear(1024, npose)
self.decshape = nn.Linear(1024, 10)
self.deccam = nn.Linear(1024, 3)
nn.init.xavier_uniform_(self.decpose.weight, gain=0.01)
nn.init.xavier_uniform_(self.decshape.weight, gain=0.01)
nn.init.xavier_uniform_(self.deccam.weight, gain=0.01)
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
mean_params = np.load(smpl_mean_params)
init_pose = torch.from_numpy(mean_params['pose'][:]).unsqueeze(0)
init_shape = torch.from_numpy(mean_params['shape'][:].astype('float32')).unsqueeze(0)
init_cam = torch.from_numpy(mean_params['cam']).unsqueeze(0)
self.register_buffer('init_pose', init_pose)
self.register_buffer('init_shape', init_shape)
self.register_buffer('init_cam', init_cam)
def _make_layer(self, block, planes, blocks, stride=1):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(planes * block.expansion),
)
layers = []
layers.append(block(self.inplanes, planes, stride, downsample))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(self.inplanes, planes))
return nn.Sequential(*layers)
def forward(self, x, init_pose=None, init_shape=None, init_cam=None, n_iter=3):
batch_size = x.shape[0]
if init_pose is None:
init_pose = self.init_pose.expand(batch_size, -1)
if init_shape is None:
init_shape = self.init_shape.expand(batch_size, -1)
if init_cam is None:
init_cam = self.init_cam.expand(batch_size, -1)
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x1 = self.layer1(x)
x2 = self.layer2(x1)
x3 = self.layer3(x2)
x4 = self.layer4(x3)
xf = self.avgpool(x4)
xf = xf.view(xf.size(0), -1)
pred_pose = init_pose
pred_shape = init_shape
pred_cam = init_cam
for i in range(n_iter):
xc = torch.cat([xf, pred_pose, pred_shape, pred_cam],1)
xc = self.fc1(xc)
xc = self.drop1(xc)
xc = self.fc2(xc)
xc = self.drop2(xc)
pred_pose = self.decpose(xc) + pred_pose
pred_shape = self.decshape(xc) + pred_shape
pred_cam = self.deccam(xc) + pred_cam
pred_rotmat = rot6d_to_rotmat(pred_pose).view(batch_size, 24, 3, 3)
return pred_rotmat, pred_shape, pred_cam
The provided code snippet includes necessary dependencies for implementing the `hmr` function. Write a Python function `def hmr(smpl_mean_params, pretrained=True, **kwargs)` to solve the following problem:
Constructs an HMR model with ResNet50 backbone. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Here is the function:
def hmr(smpl_mean_params, pretrained=True, **kwargs):
""" Constructs an HMR model with ResNet50 backbone.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = HMR(Bottleneck, [3, 4, 6, 3], smpl_mean_params, **kwargs)
if pretrained:
resnet_imagenet = resnet.resnet50(pretrained=True)
model.load_state_dict(resnet_imagenet.state_dict(),strict=False)
return model | Constructs an HMR model with ResNet50 backbone. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet |
180,787 | import torch
from torch.nn import functional as F
import numpy as np
import torchgeometry
def quat_to_rotmat(quat):
"""Convert quaternion coefficients to rotation matrix.
Args:
quat: size = [B, 4] 4 <===>(w, x, y, z)
Returns:
Rotation matrix corresponding to the quaternion -- size = [B, 3, 3]
"""
norm_quat = quat
norm_quat = norm_quat/norm_quat.norm(p=2, dim=1, keepdim=True)
w, x, y, z = norm_quat[:,0], norm_quat[:,1], norm_quat[:,2], norm_quat[:,3]
B = quat.size(0)
w2, x2, y2, z2 = w.pow(2), x.pow(2), y.pow(2), z.pow(2)
wx, wy, wz = w*x, w*y, w*z
xy, xz, yz = x*y, x*z, y*z
rotMat = torch.stack([w2 + x2 - y2 - z2, 2*xy - 2*wz, 2*wy + 2*xz,
2*wz + 2*xy, w2 - x2 + y2 - z2, 2*yz - 2*wx,
2*xz - 2*wy, 2*wx + 2*yz, w2 - x2 - y2 + z2], dim=1).view(B, 3, 3)
return rotMat
The provided code snippet includes necessary dependencies for implementing the `batch_rodrigues` function. Write a Python function `def batch_rodrigues(theta)` to solve the following problem:
Convert axis-angle representation to rotation matrix. Args: theta: size = [B, 3] Returns: Rotation matrix corresponding to the quaternion -- size = [B, 3, 3]
Here is the function:
def batch_rodrigues(theta):
"""Convert axis-angle representation to rotation matrix.
Args:
theta: size = [B, 3]
Returns:
Rotation matrix corresponding to the quaternion -- size = [B, 3, 3]
"""
l1norm = torch.norm(theta + 1e-8, p = 2, dim = 1)
angle = torch.unsqueeze(l1norm, -1)
normalized = torch.div(theta, angle)
angle = angle * 0.5
v_cos = torch.cos(angle)
v_sin = torch.sin(angle)
quat = torch.cat([v_cos, v_sin * normalized], dim = 1)
return quat_to_rotmat(quat) | Convert axis-angle representation to rotation matrix. Args: theta: size = [B, 3] Returns: Rotation matrix corresponding to the quaternion -- size = [B, 3, 3] |
180,788 | import torch
from torch.nn import functional as F
import numpy as np
import torchgeometry
def cross_product(u, v):
batch = u.shape[0]
i = u[:, 1] * v[:, 2] - u[:, 2] * v[:, 1]
j = u[:, 2] * v[:, 0] - u[:, 0] * v[:, 2]
k = u[:, 0] * v[:, 1] - u[:, 1] * v[:, 0]
out = torch.cat((i.view(batch, 1), j.view(batch, 1), k.view(batch, 1)), 1)
return out | null |
180,789 | import torch
from torch.nn import functional as F
import numpy as np
import torchgeometry
def normalize_vector(v):
batch = v.shape[0]
v_mag = torch.sqrt(v.pow(2).sum(1)) # batch
v_mag = torch.max(v_mag, v.new([1e-8]))
v_mag = v_mag.view(batch, 1).expand(batch, v.shape[1])
v = v/v_mag
return v | null |
180,790 | import torch
from torch.nn import functional as F
import numpy as np
import torchgeometry
The provided code snippet includes necessary dependencies for implementing the `rot6d_to_rotmat` function. Write a Python function `def rot6d_to_rotmat(x)` to solve the following problem:
Convert 6D rotation representation to 3x3 rotation matrix. Based on Zhou et al., "On the Continuity of Rotation Representations in Neural Networks", CVPR 2019 Input: (B,6) Batch of 6-D rotation representations Output: (B,3,3) Batch of corresponding rotation matrices
Here is the function:
def rot6d_to_rotmat(x):
"""Convert 6D rotation representation to 3x3 rotation matrix.
Based on Zhou et al., "On the Continuity of Rotation Representations in Neural Networks", CVPR 2019
Input:
(B,6) Batch of 6-D rotation representations
Output:
(B,3,3) Batch of corresponding rotation matrices
"""
x = x.view(-1,3,2)
a1 = x[:, :, 0]
a2 = x[:, :, 1]
b1 = F.normalize(a1)
b2 = F.normalize(a2 - torch.einsum('bi,bi->b', b1, a2).unsqueeze(-1) * b1)
b3 = torch.cross(b1, b2)
return torch.stack((b1, b2, b3), dim=-1) | Convert 6D rotation representation to 3x3 rotation matrix. Based on Zhou et al., "On the Continuity of Rotation Representations in Neural Networks", CVPR 2019 Input: (B,6) Batch of 6-D rotation representations Output: (B,3,3) Batch of corresponding rotation matrices |
180,791 | import torch
from torch.nn import functional as F
import numpy as np
import torchgeometry
The provided code snippet includes necessary dependencies for implementing the `perspective_projection` function. Write a Python function `def perspective_projection(points, rotation, translation, focal_length, camera_center)` to solve the following problem:
This function computes the perspective projection of a set of points. Input: points (bs, N, 3): 3D points rotation (bs, 3, 3): Camera rotation translation (bs, 3): Camera translation focal_length (bs,) or scalar: Focal length camera_center (bs, 2): Camera center
Here is the function:
def perspective_projection(points, rotation, translation,
focal_length, camera_center):
"""
This function computes the perspective projection of a set of points.
Input:
points (bs, N, 3): 3D points
rotation (bs, 3, 3): Camera rotation
translation (bs, 3): Camera translation
focal_length (bs,) or scalar: Focal length
camera_center (bs, 2): Camera center
"""
batch_size = points.shape[0]
K = torch.zeros([batch_size, 3, 3], device=points.device)
K[:,0,0] = focal_length
K[:,1,1] = focal_length
K[:,2,2] = 1.
K[:,:-1, -1] = camera_center
# Transform points
points = torch.einsum('bij,bkj->bki', rotation, points)
points = points + translation.unsqueeze(1)
# Apply perspective distortion
projected_points = points / points[:,:,-1].unsqueeze(-1)
# Apply camera intrinsics
projected_points = torch.einsum('bij,bkj->bki', K, projected_points)
return projected_points[:, :, :-1] | This function computes the perspective projection of a set of points. Input: points (bs, N, 3): 3D points rotation (bs, 3, 3): Camera rotation translation (bs, 3): Camera translation focal_length (bs,) or scalar: Focal length camera_center (bs, 2): Camera center |
180,792 | import torch
from torch.nn import functional as F
import numpy as np
import torchgeometry
def estimate_translation_np(S, joints_2d, joints_conf, focal_length=5000, img_size=224):
"""Find camera translation that brings 3D joints S closest to 2D the corresponding joints_2d.
Input:
S: (25, 3) 3D joint locations
joints: (25, 3) 2D joint locations and confidence
Returns:
(3,) camera translation vector
"""
num_joints = S.shape[0]
# focal length
f = np.array([focal_length,focal_length])
# optical center
center = np.array([img_size/2., img_size/2.])
# transformations
Z = np.reshape(np.tile(S[:,2],(2,1)).T,-1)
XY = np.reshape(S[:,0:2],-1)
O = np.tile(center,num_joints)
F = np.tile(f,num_joints)
weight2 = np.reshape(np.tile(np.sqrt(joints_conf),(2,1)).T,-1)
# least squares
Q = np.array([F*np.tile(np.array([1,0]),num_joints), F*np.tile(np.array([0,1]),num_joints), O-np.reshape(joints_2d,-1)]).T
c = (np.reshape(joints_2d,-1)-O)*Z - F*XY
# weighted least squares
W = np.diagflat(weight2)
Q = np.dot(W,Q)
c = np.dot(W,c)
# square matrix
A = np.dot(Q.T,Q)
b = np.dot(Q.T,c)
# solution
trans = np.linalg.solve(A, b)
return trans
The provided code snippet includes necessary dependencies for implementing the `estimate_translation` function. Write a Python function `def estimate_translation(S, joints_2d, focal_length=5000., img_size=224.)` to solve the following problem:
Find camera translation that brings 3D joints S closest to 2D the corresponding joints_2d. Input: S: (B, 49, 3) 3D joint locations joints: (B, 49, 3) 2D joint locations and confidence Returns: (B, 3) camera translation vectors
Here is the function:
def estimate_translation(S, joints_2d, focal_length=5000., img_size=224.):
"""Find camera translation that brings 3D joints S closest to 2D the corresponding joints_2d.
Input:
S: (B, 49, 3) 3D joint locations
joints: (B, 49, 3) 2D joint locations and confidence
Returns:
(B, 3) camera translation vectors
"""
device = S.device
# Use only joints 25:49 (GT joints)
S = S[:, 25:, :].cpu().numpy()
joints_2d = joints_2d[:, 25:, :].cpu().numpy()
joints_conf = joints_2d[:, :, -1]
joints_2d = joints_2d[:, :, :-1]
trans = np.zeros((S.shape[0], 3), dtype=np.float32)
# Find the translation for each example in the batch
for i in range(S.shape[0]):
S_i = S[i]
joints_i = joints_2d[i]
conf_i = joints_conf[i]
trans[i] = estimate_translation_np(S_i, joints_i, conf_i, focal_length=focal_length, img_size=img_size)
return torch.from_numpy(trans).to(device) | Find camera translation that brings 3D joints S closest to 2D the corresponding joints_2d. Input: S: (B, 49, 3) 3D joint locations joints: (B, 49, 3) 2D joint locations and confidence Returns: (B, 3) camera translation vectors |
180,793 | import torch
from torch.nn import functional as F
import numpy as np
import torchgeometry
def weakProjection_gpu(skel3D, scale, trans2D ):
# if len(skel3D.shape)==1:
# skel3D = np.reshape(skel3D, (-1,3))
skel3D = skel3D.view((skel3D.shape[0],-1,3))
trans2D = trans2D.view((trans2D.shape[0],1,2))
scale = scale.view((scale.shape[0],1,1))
skel3D_proj = scale* skel3D[:,:,:2] + trans2D
return skel3D_proj#skel3D_proj.view((skel3D.shape[0],-1)) #(N, 19*2) o | null |
180,794 | import torch
from torch.nn import functional as F
import numpy as np
import torchgeometry
def weakProjection(skel3D, scale, trans2D ):
skel3D_proj = scale* skel3D[:,:2] + trans2D
return skel3D_proj#skel3D_proj.view((skel3D.shape[0],-1)) #(N, 19*2) o | null |
180,795 | import torch
from torch.nn import functional as F
import numpy as np
import torchgeometry
The provided code snippet includes necessary dependencies for implementing the `rotmat_to_angleaxis` function. Write a Python function `def rotmat_to_angleaxis(init_pred_rotmat)` to solve the following problem:
init_pred_rotmat: torch.tensor with (24,3,3) dimension
Here is the function:
def rotmat_to_angleaxis(init_pred_rotmat):
"""
init_pred_rotmat: torch.tensor with (24,3,3) dimension
"""
device = init_pred_rotmat.device
ones = torch.tensor([0,0,1], dtype=torch.float32,).view(1, 3, 1).expand(init_pred_rotmat.shape[1], -1, -1).to(device)
pred_rotmat_hom = torch.cat([ init_pred_rotmat.view(-1, 3, 3),ones ], dim=-1) #24,3,4
pred_aa = torchgeometry.rotation_matrix_to_angle_axis(pred_rotmat_hom).contiguous().view(1, -1) #[1,72]
# tgm.rotation_matrix_to_angle_axis returns NaN for 0 rotation, so manually hack it
pred_aa[torch.isnan(pred_aa)] = 0.0 #[1,72]
pred_aa = pred_aa.view(1,24,3)
return pred_aa | init_pred_rotmat: torch.tensor with (24,3,3) dimension |
180,796 | import torch
import numpy as np
import scipy.misc
import cv2
from bodymocap import constants
from torchvision.transforms import Normalize
def transform(pt, center, scale, res, invert=0, rot=0):
"""Transform pixel location to different reference."""
t = get_transform(center, scale, res, rot=rot)
if invert:
t = np.linalg.inv(t)
new_pt = np.array([pt[0]-1, pt[1]-1, 1.]).T
new_pt = np.dot(t, new_pt)
return new_pt[:2].astype(int)+1
The provided code snippet includes necessary dependencies for implementing the `crop` function. Write a Python function `def crop(img, center, scale, res, rot=0)` to solve the following problem:
Crop image according to the supplied bounding box.
Here is the function:
def crop(img, center, scale, res, rot=0):
"""Crop image according to the supplied bounding box."""
# Upper left point
ul = np.array(transform([1, 1], center, scale, res, invert=1))-1
# Bottom right point
br = np.array(transform([res[0]+1,
res[1]+1], center, scale, res, invert=1))-1
# Padding so that when rotated proper amount of context is included
pad = int(np.linalg.norm(br - ul) / 2 - float(br[1] - ul[1]) / 2)
if not rot == 0:
ul -= pad
br += pad
new_shape = [br[1] - ul[1], br[0] - ul[0]]
if new_shape[0]>15000 or new_shape[1]>15000:
print("Image Size Too Big! scale{}, new_shape{} br{}, ul{}".format(scale, new_shape, br, ul))
return None
if len(img.shape) > 2:
new_shape += [img.shape[2]]
new_img = np.zeros(new_shape, dtype=np.uint8)
# #Compute bbox for Han's format
# bboxScale_o2n = 224/new_img.shape[0]
# bboxTopLeft = ul *bboxScale_o2n
# Range to fill new array
new_x = max(0, -ul[0]), min(br[0], len(img[0])) - ul[0]
new_y = max(0, -ul[1]), min(br[1], len(img)) - ul[1]
# Range to sample from original image
old_x = max(0, ul[0]), min(len(img[0]), br[0])
old_y = max(0, ul[1]), min(len(img), br[1])
# print("{} vs {} || {} vs {}".format(new_y[1] - new_y[0] , old_y[1] - old_y[0], new_x[1] - new_x[0], old_x[1] -old_x[0] ) )
if new_y[1] - new_y[0] != old_y[1] - old_y[0] or new_x[1] - new_x[0] != old_x[1] -old_x[0] or new_y[1] - new_y[0] <0 or new_x[1] - new_x[0] <0:
print("Warning: maybe person is out of image boundary!")
return None
new_img[new_y[0]:new_y[1], new_x[0]:new_x[1]] = img[old_y[0]:old_y[1],
old_x[0]:old_x[1]]
if not rot == 0:
# Remove padding
new_img = scipy.misc.imrotate(new_img, rot)
new_img = new_img[pad:-pad, pad:-pad]
new_img = cv2.resize(new_img, tuple(res))
# new_img = scipy.misc.imresize(new_img, res) #Need this to get the same number with the old model (trained with this resize)
return new_img#, bboxScale_o2n, bboxTopLeft | Crop image according to the supplied bounding box. |
180,797 | import torch
import numpy as np
import scipy.misc
import cv2
from bodymocap import constants
from torchvision.transforms import Normalize
def transform(pt, center, scale, res, invert=0, rot=0):
"""Transform pixel location to different reference."""
t = get_transform(center, scale, res, rot=rot)
if invert:
t = np.linalg.inv(t)
new_pt = np.array([pt[0]-1, pt[1]-1, 1.]).T
new_pt = np.dot(t, new_pt)
return new_pt[:2].astype(int)+1
The provided code snippet includes necessary dependencies for implementing the `uncrop` function. Write a Python function `def uncrop(img, center, scale, orig_shape, rot=0, is_rgb=True)` to solve the following problem:
Undo' the image cropping/resizing. This function is used when evaluating mask/part segmentation.
Here is the function:
def uncrop(img, center, scale, orig_shape, rot=0, is_rgb=True):
"""'Undo' the image cropping/resizing.
This function is used when evaluating mask/part segmentation.
"""
res = img.shape[:2]
# Upper left point
ul = np.array(transform([1, 1], center, scale, res, invert=1))-1
# Bottom right point
br = np.array(transform([res[0]+1,res[1]+1], center, scale, res, invert=1))-1
# size of cropped image
crop_shape = [br[1] - ul[1], br[0] - ul[0]]
new_shape = [br[1] - ul[1], br[0] - ul[0]]
if len(img.shape) > 2:
new_shape += [img.shape[2]]
new_img = np.zeros(orig_shape, dtype=np.uint8)
# Range to fill new array
new_x = max(0, -ul[0]), min(br[0], orig_shape[1]) - ul[0]
new_y = max(0, -ul[1]), min(br[1], orig_shape[0]) - ul[1]
# Range to sample from original image
old_x = max(0, ul[0]), min(orig_shape[1], br[0])
old_y = max(0, ul[1]), min(orig_shape[0], br[1])
img = cv2.resize(img, crop_shape, interp='nearest')
new_img[old_y[0]:old_y[1], old_x[0]:old_x[1]] = img[new_y[0]:new_y[1], new_x[0]:new_x[1]]
return new_img | Undo' the image cropping/resizing. This function is used when evaluating mask/part segmentation. |
180,798 | import torch
import numpy as np
import scipy.misc
import cv2
from bodymocap import constants
from torchvision.transforms import Normalize
The provided code snippet includes necessary dependencies for implementing the `rot_aa` function. Write a Python function `def rot_aa(aa, rot)` to solve the following problem:
Rotate axis angle parameters.
Here is the function:
def rot_aa(aa, rot):
"""Rotate axis angle parameters."""
# pose parameters
R = np.array([[np.cos(np.deg2rad(-rot)), -np.sin(np.deg2rad(-rot)), 0],
[np.sin(np.deg2rad(-rot)), np.cos(np.deg2rad(-rot)), 0],
[0, 0, 1]])
# find the rotation of the body in camera frame
per_rdg, _ = cv2.Rodrigues(aa)
# apply the global rotation to the global orientation
resrot, _ = cv2.Rodrigues(np.dot(R,per_rdg))
aa = (resrot.T)[0]
return aa | Rotate axis angle parameters. |
180,799 | import torch
import numpy as np
import scipy.misc
import cv2
from bodymocap import constants
from torchvision.transforms import Normalize
The provided code snippet includes necessary dependencies for implementing the `flip_img` function. Write a Python function `def flip_img(img)` to solve the following problem:
Flip rgb images or masks. channels come last, e.g. (256,256,3).
Here is the function:
def flip_img(img):
"""Flip rgb images or masks.
channels come last, e.g. (256,256,3).
"""
img = np.fliplr(img)
return img | Flip rgb images or masks. channels come last, e.g. (256,256,3). |
180,800 | import torch
import numpy as np
import scipy.misc
import cv2
from bodymocap import constants
from torchvision.transforms import Normalize
The provided code snippet includes necessary dependencies for implementing the `flip_kp` function. Write a Python function `def flip_kp(kp)` to solve the following problem:
Flip keypoints.
Here is the function:
def flip_kp(kp):
"""Flip keypoints."""
if len(kp) == 24:
flipped_parts = constants.J24_FLIP_PERM
elif len(kp) == 49:
flipped_parts = constants.J49_FLIP_PERM
kp = kp[flipped_parts]
kp[:,0] = - kp[:,0]
return kp | Flip keypoints. |
180,801 | import torch
import numpy as np
import scipy.misc
import cv2
from bodymocap import constants
from torchvision.transforms import Normalize
The provided code snippet includes necessary dependencies for implementing the `flip_pose` function. Write a Python function `def flip_pose(pose)` to solve the following problem:
Flip pose. The flipping is based on SMPL parameters.
Here is the function:
def flip_pose(pose):
"""Flip pose.
The flipping is based on SMPL parameters.
"""
flipped_parts = constants.SMPL_POSE_FLIP_PERM
pose = pose[flipped_parts]
# we also negate the second and the third dimension of the axis-angle
pose[1::3] = -pose[1::3]
pose[2::3] = -pose[2::3]
return pose | Flip pose. The flipping is based on SMPL parameters. |
180,802 | import torch
import numpy as np
import scipy.misc
import cv2
from bodymocap import constants
from torchvision.transforms import Normalize
The provided code snippet includes necessary dependencies for implementing the `bbox_from_openpose` function. Write a Python function `def bbox_from_openpose(openpose_file, rescale=1.2, detection_thresh=0.2)` to solve the following problem:
Get center and scale for bounding box from openpose detections.
Here is the function:
def bbox_from_openpose(openpose_file, rescale=1.2, detection_thresh=0.2):
"""Get center and scale for bounding box from openpose detections."""
with open(openpose_file, 'r') as f:
data = json.load(f)
if 'people' not in data or len(data['people'])==0:
return None, None
# keypoints = json.load(f)['people'][0]['pose_keypoints_2d']
keypoints = data['people'][0]['pose_keypoints_2d']
keypoints = np.reshape(np.array(keypoints), (-1,3))
valid = keypoints[:,-1] > detection_thresh
valid_keypoints = keypoints[valid][:,:-1] #(25,2)
# min_pt = np.min(valid_keypoints, axis=0)
# max_pt = np.max(valid_keypoints, axis=0)
# bbox= [ min_pt[0], min_pt[1], max_pt[0] - min_pt[0], max_pt[1] - min_pt[1]]
center = valid_keypoints.mean(axis=0)
bbox_size = (valid_keypoints.max(axis=0) - valid_keypoints.min(axis=0)).max()
# adjust bounding box tightness
scale = bbox_size / 200.0
scale *= rescale
return center, scale#, bbox | Get center and scale for bounding box from openpose detections. |
180,803 | import torch
import numpy as np
import scipy.misc
import cv2
from bodymocap import constants
from torchvision.transforms import Normalize
The provided code snippet includes necessary dependencies for implementing the `bbox_from_keypoint2d` function. Write a Python function `def bbox_from_keypoint2d(keypoints, rescale=1.2, detection_thresh=0.2)` to solve the following problem:
output: center: bbox center scale: scale_n2o: 224x224 -> original bbox size (max length if not a square bbox)
Here is the function:
def bbox_from_keypoint2d(keypoints, rescale=1.2, detection_thresh=0.2):
"""
output:
center: bbox center
scale: scale_n2o: 224x224 -> original bbox size (max length if not a square bbox)
"""
# """Get center and scale for bounding box from openpose detections."""
if len(keypoints.shape)==2 and keypoints.shape[1]==2: #(X,2)
valid_keypoints = keypoints
else:
keypoints = np.reshape(np.array(keypoints), (-1,3))
valid = keypoints[:,-1] > detection_thresh
valid_keypoints = keypoints[valid][:,:-1] #(25,2)
# min_pt = np.min(valid_keypoints, axis=0)
# max_pt = np.max(valid_keypoints, axis=0)
# bbox= [ min_pt[0], min_pt[1], max_pt[0] - min_pt[0], max_pt[1] - min_pt[1]]
center = valid_keypoints.mean(axis=0)
bbox_size = (valid_keypoints.max(axis=0) - valid_keypoints.min(axis=0)).max()
# adjust bounding box tightness
scale = bbox_size / 200.0
scale *= rescale
return center, scale#, bbox | output: center: bbox center scale: scale_n2o: 224x224 -> original bbox size (max length if not a square bbox) |
180,804 | import torch
import numpy as np
import scipy.misc
import cv2
from bodymocap import constants
from torchvision.transforms import Normalize
def crop_bboxInfo(img, center, scale, res =(224,224)):
"""Crop image according to the supplied bounding box."""
# Upper left point
ul = np.array(transform([1, 1], center, scale, res, invert=1))-1
# Bottom right point
br = np.array(transform([res[0]+1,
res[1]+1], center, scale, res, invert=1))-1
# Padding so that when rotated proper amount of context is included
pad = int(np.linalg.norm(br - ul) / 2 - float(br[1] - ul[1]) / 2)
new_shape = [br[1] - ul[1], br[0] - ul[0]]
if len(img.shape) > 2:
new_shape += [img.shape[2]]
# new_img = np.zeros(new_shape)
if new_shape[0] <1 or new_shape[1] <1:
return None, None, None
new_img = np.zeros(new_shape, dtype=np.uint8)
if new_img.shape[0] ==0:
return None, None, None
#Compute bbox for Han's format
bboxScale_o2n = res[0]/new_img.shape[0] #224/ 531
# Range to fill new array
new_x = max(0, -ul[0]), min(br[0], len(img[0])) - ul[0]
new_y = max(0, -ul[1]), min(br[1], len(img)) - ul[1]
# Range to sample from original image
old_x = max(0, ul[0]), min(len(img[0]), br[0])
old_y = max(0, ul[1]), min(len(img), br[1])
if new_y[0] <0 or new_y[1]<0 or new_x[0] <0 or new_x[1]<0 :
return None, None, None
new_img[new_y[0]:new_y[1], new_x[0]:new_x[1]] = img[old_y[0]:old_y[1],
old_x[0]:old_x[1]]
bboxTopLeft_inOriginal = (ul[0], ul[1] )
if new_img.shape[0] <20 or new_img.shape[1]<20:
return None, None, None
# print(bboxTopLeft_inOriginal)
# from renderer import viewer2D
# viewer2D.ImShow(new_img.astype(np.uint8),name='cropped')
new_img = cv2.resize(new_img, res)
# viewer2D.ImShow(new_img.astype(np.uint8),name='original')
return new_img, bboxScale_o2n, np.array(bboxTopLeft_inOriginal)
def bbox_from_keypoints(keypoints, rescale=1.2, detection_thresh=0.2, imageHeight= None):
"""Get center and scale for bounding box from openpose detections."""
# with open(openpose_file, 'r') as f:
# data = json.load(f)
# if 'people' not in data or len(data['people'])==0:
# return None, None
# # keypoints = json.load(f)['people'][0]['pose_keypoints_2d']
# keypoints = data['people'][0]['pose_keypoints_2d']
keypoints = np.reshape(np.array(keypoints), (-1,3))
valid = keypoints[:,-1] > detection_thresh
# if g_debugUpperBodyOnly: #Intentionally remove lower bodies
# valid[ [ 9,10,11,12,13,14, 22,23,24, 19,20,21] ] = False
valid_keypoints = keypoints[valid][:,:-1] #(25,2)
if len(valid_keypoints)<2:
return None, None, None
if False: #Should have all limbs and nose
if np.sum(valid[ [ 2,3,4, 5,6,7, 9,10, 12,13,1,0] ]) <12:
return None, None, None
min_pt = np.min(valid_keypoints, axis=0)
max_pt = np.max(valid_keypoints, axis=0)
bbox= [ min_pt[0], min_pt[1], max_pt[0] - min_pt[0], max_pt[1] - min_pt[1]]
# print(valid_keypoints)
# print(valid)
print(bbox)
if imageHeight is not None:
if valid[10]==False and valid[13] == False: # No knees ub ioeb
max_pt[1] = min(max_pt[1] + (max_pt[1]- min_pt[1]), imageHeight )
bbox= [ min_pt[0], min_pt[1], max_pt[0] - min_pt[0], max_pt[1] - min_pt[1]]
valid_keypoints = np.vstack( (valid_keypoints, np.array(max_pt)) )
elif valid[11]==False and valid[14] == False: #No foot
max_pt[1] = min(max_pt[1] + (max_pt[1]- min_pt[1])*0.2, imageHeight )
bbox= [ min_pt[0], min_pt[1], max_pt[0] - min_pt[0], max_pt[1] - min_pt[1]]
valid_keypoints = np.vstack( (valid_keypoints, np.array(max_pt)) )
center = valid_keypoints.mean(axis=0)
bbox_size = (valid_keypoints.max(axis=0) - valid_keypoints.min(axis=0)).max()
# adjust bounding box tightness
scale = bbox_size / 200.0
scale *= rescale
return center, scale, bbox
The provided code snippet includes necessary dependencies for implementing the `process_image_keypoints` function. Write a Python function `def process_image_keypoints(img, keypoints, input_res=224)` to solve the following problem:
Read image, do preprocessing and possibly crop it according to the bounding box. If there are bounding box annotations, use them to crop the image. If no bounding box is specified but openpose detections are available, use them to get the bounding box.
Here is the function:
def process_image_keypoints(img, keypoints, input_res=224):
"""Read image, do preprocessing and possibly crop it according to the bounding box.
If there are bounding box annotations, use them to crop the image.
If no bounding box is specified but openpose detections are available, use them to get the bounding box.
"""
normalize_img = Normalize(mean=constants.IMG_NORM_MEAN, std=constants.IMG_NORM_STD)
img = img[:,:,::-1].copy() # PyTorch does not support negative stride at the moment
center, scale, bbox = bbox_from_keypoints(keypoints, imageHeight = img.shape[0])
if center is None:
return None, None, None, None, None
img, boxScale_o2n, bboxTopLeft = crop_bboxInfo(img, center, scale, (input_res, input_res))
# viewer2D.ImShow(img, name='cropped', waitTime=1) #224,224,3
if img is None:
return None, None, None, None, None
# unCropped = uncrop(img, center, scale, (input_res, input_res))
# if True:
# viewer2D.ImShow(img)
img = img.astype(np.float32) / 255.
img = torch.from_numpy(img).permute(2,0,1)
norm_img = normalize_img(img.clone())[None]
# return img, norm_img, img_original, boxScale_o2n, bboxTopLeft, bbox
bboxInfo ={"center": center, "scale": scale, "bboxXYWH":bbox}
return img, norm_img, boxScale_o2n, bboxTopLeft, bboxInfo | Read image, do preprocessing and possibly crop it according to the bounding box. If there are bounding box annotations, use them to crop the image. If no bounding box is specified but openpose detections are available, use them to get the bounding box. |
180,805 | import torch
import numpy as np
import scipy.misc
import cv2
from bodymocap import constants
from torchvision.transforms import Normalize
The provided code snippet includes necessary dependencies for implementing the `bbox_from_json` function. Write a Python function `def bbox_from_json(bbox_file)` to solve the following problem:
Get center and scale of bounding box from bounding box annotations. The expected format is [top_left(x), top_left(y), width, height].
Here is the function:
def bbox_from_json(bbox_file):
"""Get center and scale of bounding box from bounding box annotations.
The expected format is [top_left(x), top_left(y), width, height].
"""
with open(bbox_file, 'r') as f:
bbox = np.array(json.load(f)['bbox']).astype(np.float32)
ul_corner = bbox[:2]
center = ul_corner + 0.5 * bbox[2:]
width = max(bbox[2], bbox[3])
scale = width / 200.0
# make sure the bounding box is rectangular
return center, scale | Get center and scale of bounding box from bounding box annotations. The expected format is [top_left(x), top_left(y), width, height]. |
180,806 | import torch
import numpy as np
import scipy.misc
import cv2
from bodymocap import constants
from torchvision.transforms import Normalize
def crop_bboxInfo(img, center, scale, res =(224,224)):
"""Crop image according to the supplied bounding box."""
# Upper left point
ul = np.array(transform([1, 1], center, scale, res, invert=1))-1
# Bottom right point
br = np.array(transform([res[0]+1,
res[1]+1], center, scale, res, invert=1))-1
# Padding so that when rotated proper amount of context is included
pad = int(np.linalg.norm(br - ul) / 2 - float(br[1] - ul[1]) / 2)
new_shape = [br[1] - ul[1], br[0] - ul[0]]
if len(img.shape) > 2:
new_shape += [img.shape[2]]
# new_img = np.zeros(new_shape)
if new_shape[0] <1 or new_shape[1] <1:
return None, None, None
new_img = np.zeros(new_shape, dtype=np.uint8)
if new_img.shape[0] ==0:
return None, None, None
#Compute bbox for Han's format
bboxScale_o2n = res[0]/new_img.shape[0] #224/ 531
# Range to fill new array
new_x = max(0, -ul[0]), min(br[0], len(img[0])) - ul[0]
new_y = max(0, -ul[1]), min(br[1], len(img)) - ul[1]
# Range to sample from original image
old_x = max(0, ul[0]), min(len(img[0]), br[0])
old_y = max(0, ul[1]), min(len(img), br[1])
if new_y[0] <0 or new_y[1]<0 or new_x[0] <0 or new_x[1]<0 :
return None, None, None
new_img[new_y[0]:new_y[1], new_x[0]:new_x[1]] = img[old_y[0]:old_y[1],
old_x[0]:old_x[1]]
bboxTopLeft_inOriginal = (ul[0], ul[1] )
if new_img.shape[0] <20 or new_img.shape[1]<20:
return None, None, None
# print(bboxTopLeft_inOriginal)
# from renderer import viewer2D
# viewer2D.ImShow(new_img.astype(np.uint8),name='cropped')
new_img = cv2.resize(new_img, res)
# viewer2D.ImShow(new_img.astype(np.uint8),name='original')
return new_img, bboxScale_o2n, np.array(bboxTopLeft_inOriginal)
def bbox_from_bbr(bbox_XYWH, rescale=1.2, detection_thresh=0.2, imageHeight= None):
"""Get center and scale for bounding box from openpose detections."""
# bbox= bbr
# if imageHeight is not None:
# if valid[10]==False and valid[13] == False: # No knees ub ioeb
# max_pt[1] = min(max_pt[1] + (max_pt[1]- min_pt[1]), imageHeight )
# bbox= [ min_pt[0], min_pt[1], max_pt[0] - min_pt[0], max_pt[1] - min_pt[1]]
# valid_keypoints = np.vstack( (valid_keypoints, np.array(max_pt)) )
# elif valid[11]==False and valid[14] == False: #No foot
# max_pt[1] = min(max_pt[1] + (max_pt[1]- min_pt[1])*0.2, imageHeight )
# bbox= [ min_pt[0], min_pt[1], max_pt[0] - min_pt[0], max_pt[1] - min_pt[1]]
# valid_keypoints = np.vstack( (valid_keypoints, np.array(max_pt)) )
center = bbox_XYWH[:2] + 0.5 * bbox_XYWH[2:]
bbox_size = max(bbox_XYWH[2:])
# adjust bounding box tightness
scale = bbox_size / 200.0
scale *= rescale
return center, scale#, bbox_XYWH
The provided code snippet includes necessary dependencies for implementing the `process_image_bbox` function. Write a Python function `def process_image_bbox(img_original, bbox_XYWH, input_res=224)` to solve the following problem:
Read image, do preprocessing and possibly crop it according to the bounding box. If there are bounding box annotations, use them to crop the image. If no bounding box is specified but openpose detections are available, use them to get the bounding box.
Here is the function:
def process_image_bbox(img_original, bbox_XYWH, input_res=224):
"""Read image, do preprocessing and possibly crop it according to the bounding box.
If there are bounding box annotations, use them to crop the image.
If no bounding box is specified but openpose detections are available, use them to get the bounding box.
"""
normalize_img = Normalize(mean=constants.IMG_NORM_MEAN, std=constants.IMG_NORM_STD)
img_original = img_original[:,:,::-1].copy() # PyTorch does not support negative stride at the moment
img = img_original.copy()
center, scale = bbox_from_bbr(bbox_XYWH, imageHeight = img.shape[0])
if center is None:
return None, None, None, None, None
img, boxScale_o2n, bboxTopLeft = crop_bboxInfo(img, center, scale, (input_res, input_res))
# viewer2D.ImShow(img, name='cropped', waitTime=1) #224,224,3
if img is None:
return None, None, None, None, None
# unCropped = uncrop(img, center, scale, (input_res, input_res))
# if True:
# viewer2D.ImShow(img)
norm_img = (img.copy()).astype(np.float32) / 255.
norm_img = torch.from_numpy(norm_img).permute(2,0,1)
norm_img = normalize_img(norm_img.clone())[None]
bboxInfo ={"center": center, "scale": scale, "bboxXYWH":bbox_XYWH}
return img, norm_img, boxScale_o2n, bboxTopLeft, bboxInfo | Read image, do preprocessing and possibly crop it according to the bounding box. If there are bounding box annotations, use them to crop the image. If no bounding box is specified but openpose detections are available, use them to get the bounding box. |
180,807 | import torch
import numpy as np
import scipy.misc
import cv2
from bodymocap import constants
from torchvision.transforms import Normalize
g_de_normalize_img = Normalize(mean=[ -constants.IMG_NORM_MEAN[0]/constants.IMG_NORM_STD[0] , -constants.IMG_NORM_MEAN[1]/constants.IMG_NORM_STD[1], -constants.IMG_NORM_MEAN[2]/constants.IMG_NORM_STD[2]], std=[1/constants.IMG_NORM_STD[0], 1/constants.IMG_NORM_STD[1], 1/constants.IMG_NORM_STD[2]])
The provided code snippet includes necessary dependencies for implementing the `deNormalizeBatchImg` function. Write a Python function `def deNormalizeBatchImg(normTensorImg)` to solve the following problem:
Normalized Batch Img to original image Input: normImg: normTensorImg in cpu Input: deNormImg: numpy form
Here is the function:
def deNormalizeBatchImg(normTensorImg):
"""
Normalized Batch Img to original image
Input:
normImg: normTensorImg in cpu
Input:
deNormImg: numpy form
"""
deNormImg = g_de_normalize_img(normTensorImg).numpy()
deNormImg = np.transpose(deNormImg , (1,2,0) )*255.0
deNormImg = deNormImg[:,:,[2,1,0]]
deNormImg = np.ascontiguousarray(deNormImg, dtype=np.uint8)
return deNormImg | Normalized Batch Img to original image Input: normImg: normTensorImg in cpu Input: deNormImg: numpy form |
180,808 | import os, sys, shutil
import os.path as osp
import ry_utils
import cv2
import numpy as np
def check_keywords(subdir, keywords):
if len(keywords) == 0:
return True
else:
for keyword in keywords:
if subdir.find(keyword)>=0:
return True
return False | null |
180,809 | import os, sys, shutil
import os.path as osp
import subprocess as sp
import general_utils as gnu
def extract_frame(video_dir, frame_dir):
for file in os.listdir(video_dir):
if file.endswith((".mov", ".mp4")):
file_path = osp.join(video_dir, file)
file_name = file[:-4]
# if file_name != 'legao_02_01': continue
res_dir = osp.join(frame_dir, file_name)
gnu.build_dir(res_dir)
command = f"ffmpeg -i {file_path} {res_dir}/{file_name}_%05d.png"
command = command.split()
sp.run(command) | null |
180,810 | import os, sys, shutil
import os.path as osp
import cv2
from collections import OrderedDict
import mocap_utils.general_utils as gnu
import numpy as np
import json
import subprocess as sp
def setup_render_out(out_dir):
if out_dir is not None:
gnu.build_dir(out_dir)
outputFileName = 'scene_%08d.jpg' # Hardcoded in glViewer.py
overlaidImageFolder= osp.join(out_dir, 'overlaid')
gnu.build_dir(overlaidImageFolder)
sideImageFolder= osp.join(out_dir, 'side')
gnu.build_dir(sideImageFolder)
mergedImageFolder= osp.join(out_dir, 'merged')
gnu.build_dir(mergedImageFolder)
res_subdirs = \
[outputFileName, overlaidImageFolder, sideImageFolder, mergedImageFolder]
return res_subdirs
else:
return None | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.