id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
180,610
from flask import jsonify, g from sqlalchemy_utils.types.arrow import arrow from app.api.base import api_bp, require_api_sudo, require_api_auth from app import config from app.extensions import limiter from app.log import LOG from app.models import Job, ApiToCookieToken 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}>" The provided code snippet includes necessary dependencies for implementing the `delete_user` function. Write a Python function `def delete_user()` to solve the following problem: Delete the user. Requires sudo mode. Here is the function: def delete_user(): """ Delete the user. Requires sudo mode. """ # Schedule delete account job LOG.w("schedule delete account job for %s", g.user) Job.create( name=config.JOB_DELETE_ACCOUNT, payload={"user_id": g.user.id}, run_at=arrow.now(), commit=True, ) return jsonify(ok=True)
Delete the user. Requires sudo mode.
180,611
from flask import jsonify, g from sqlalchemy_utils.types.arrow import arrow from app.api.base import api_bp, require_api_sudo, require_api_auth from app import config from app.extensions import limiter from app.log import LOG from app.models import Job, ApiToCookieToken class ApiToCookieToken(Base, ModelMixin): __tablename__ = "api_cookie_token" code = sa.Column(sa.String(128), unique=True, nullable=False) user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False) api_key_id = sa.Column(sa.ForeignKey(ApiKey.id, ondelete="cascade"), nullable=False) user = orm.relationship(User) api_key = orm.relationship(ApiKey) def create(cls, **kwargs): code = secrets.token_urlsafe(32) return super().create(code=code, **kwargs) The provided code snippet includes necessary dependencies for implementing the `get_api_session_token` function. Write a Python function `def get_api_session_token()` to solve the following problem: Get a temporary token to exchange it for a cookie based session Output: 200 and a temporary random token { token: "asdli3ldq39h9hd3", } Here is the function: def get_api_session_token(): """ Get a temporary token to exchange it for a cookie based session Output: 200 and a temporary random token { token: "asdli3ldq39h9hd3", } """ token = ApiToCookieToken.create( user=g.user, api_key_id=g.api_key.id, commit=True, ) return jsonify({"token": token.code})
Get a temporary token to exchange it for a cookie based session Output: 200 and a temporary random token { token: "asdli3ldq39h9hd3", }
180,612
from flask import g, request from flask import jsonify from app.api.base import api_bp, require_api_auth from app.db import Session from app.models import CustomDomain, DomainDeletedAlias, Mailbox, DomainMailbox def custom_domain_to_dict(custom_domain: CustomDomain): return { "id": custom_domain.id, "domain_name": custom_domain.domain, "is_verified": custom_domain.verified, "nb_alias": custom_domain.nb_alias(), "creation_date": custom_domain.created_at.format(), "creation_timestamp": custom_domain.created_at.timestamp, "catch_all": custom_domain.catch_all, "name": custom_domain.name, "random_prefix_generation": custom_domain.random_prefix_generation, "mailboxes": [ {"id": mb.id, "email": mb.email} for mb in custom_domain.mailboxes ], } 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 get_custom_domains(): user = g.user custom_domains = CustomDomain.filter_by( user_id=user.id, is_sl_subdomain=False ).all() return jsonify(custom_domains=[custom_domain_to_dict(cd) for cd in custom_domains])
null
180,613
from flask import g, request from flask import jsonify from app.api.base import api_bp, require_api_auth from app.db import Session from app.models import CustomDomain, DomainDeletedAlias, Mailbox, DomainMailbox 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}>" def get_custom_domain_trash(custom_domain_id: int): user = g.user custom_domain = CustomDomain.get(custom_domain_id) if not custom_domain or custom_domain.user_id != user.id: return jsonify(error="Forbidden"), 403 domain_deleted_aliases = DomainDeletedAlias.filter_by( domain_id=custom_domain.id ).all() return jsonify( aliases=[ { "alias": dda.email, "deletion_timestamp": dda.created_at.timestamp, } for dda in domain_deleted_aliases ] )
null
180,614
from flask import g, request from flask import jsonify from app.api.base import api_bp, require_api_auth from app.db import Session from app.models import CustomDomain, DomainDeletedAlias, Mailbox, DomainMailbox def custom_domain_to_dict(custom_domain: CustomDomain): return { "id": custom_domain.id, "domain_name": custom_domain.domain, "is_verified": custom_domain.verified, "nb_alias": custom_domain.nb_alias(), "creation_date": custom_domain.created_at.format(), "creation_timestamp": custom_domain.created_at.timestamp, "catch_all": custom_domain.catch_all, "name": custom_domain.name, "random_prefix_generation": custom_domain.random_prefix_generation, "mailboxes": [ {"id": mb.id, "email": mb.email} for mb in custom_domain.mailboxes ], } 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 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 ) The provided code snippet includes necessary dependencies for implementing the `update_custom_domain` function. Write a Python function `def update_custom_domain(custom_domain_id)` to solve the following problem: Update alias note Input: custom_domain_id: in url In body: catch_all (optional): boolean random_prefix_generation (optional): boolean name (optional): in body mailbox_ids (optional): array of mailbox_id Output: 200 Here is the function: def update_custom_domain(custom_domain_id): """ Update alias note Input: custom_domain_id: in url In body: catch_all (optional): boolean random_prefix_generation (optional): boolean name (optional): in body mailbox_ids (optional): array of mailbox_id Output: 200 """ data = request.get_json() if not data: return jsonify(error="request body cannot be empty"), 400 user = g.user custom_domain: CustomDomain = CustomDomain.get(custom_domain_id) if not custom_domain or custom_domain.user_id != user.id: return jsonify(error="Forbidden"), 403 changed = False if "catch_all" in data: catch_all = data.get("catch_all") custom_domain.catch_all = catch_all changed = True if "random_prefix_generation" in data: random_prefix_generation = data.get("random_prefix_generation") custom_domain.random_prefix_generation = random_prefix_generation changed = True if "name" in data: name = data.get("name") custom_domain.name = name changed = True if "mailbox_ids" in data: mailbox_ids = [int(m_id) for m_id in data.get("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 != user.id or not mailbox.verified: return jsonify(error="Forbidden"), 400 mailboxes.append(mailbox) # 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) changed = True if changed: Session.commit() # refresh custom_domain = CustomDomain.get(custom_domain_id) return jsonify(custom_domain=custom_domain_to_dict(custom_domain)), 200
Update alias note Input: custom_domain_id: in url In body: catch_all (optional): boolean random_prefix_generation (optional): boolean name (optional): in body mailbox_ids (optional): array of mailbox_id Output: 200
180,615
from typing import Optional import arrow import requests from flask import g from flask import jsonify from flask import request from requests import RequestException from app.api.base import api_bp, require_api_auth from app.config import APPLE_API_SECRET, MACAPP_APPLE_API_SECRET from app.subscription_webhook import execute_subscription_webhook from app.db import Session from app.log import LOG from app.models import PlanEnum, AppleSubscription def verify_receipt(receipt_data, user, password) -> Optional[AppleSubscription]: """ Call https://buy.itunes.apple.com/verifyReceipt and create/update AppleSubscription table Call the production URL for verifyReceipt first, use sandbox URL if receive a 21007 status code. Return AppleSubscription object if success https://developer.apple.com/documentation/appstorereceipts/verifyreceipt """ LOG.d("start verify_receipt") try: r = requests.post( _PROD_URL, json={"receipt-data": receipt_data, "password": password} ) except RequestException: LOG.w("cannot call Apple server %s", _PROD_URL) return None if r.status_code >= 500: LOG.w("Apple server error, response:%s %s", r, r.content) return None if r.json() == {"status": 21007}: # try sandbox_url LOG.w("Use the sandbox url instead") r = requests.post( _SANDBOX_URL, json={"receipt-data": receipt_data, "password": password}, ) data = r.json() # data has the following format # { # "status": 0, # "environment": "Sandbox", # "receipt": { # "receipt_type": "ProductionSandbox", # "adam_id": 0, # "app_item_id": 0, # "bundle_id": "io.simplelogin.ios-app", # "application_version": "2", # "download_id": 0, # "version_external_identifier": 0, # "receipt_creation_date": "2020-04-18 16:36:34 Etc/GMT", # "receipt_creation_date_ms": "1587227794000", # "receipt_creation_date_pst": "2020-04-18 09:36:34 America/Los_Angeles", # "request_date": "2020-04-18 16:46:36 Etc/GMT", # "request_date_ms": "1587228396496", # "request_date_pst": "2020-04-18 09:46:36 America/Los_Angeles", # "original_purchase_date": "2013-08-01 07:00:00 Etc/GMT", # "original_purchase_date_ms": "1375340400000", # "original_purchase_date_pst": "2013-08-01 00:00:00 America/Los_Angeles", # "original_application_version": "1.0", # "in_app": [ # { # "quantity": "1", # "product_id": "io.simplelogin.ios_app.subscription.premium.monthly", # "transaction_id": "1000000653584474", # "original_transaction_id": "1000000653584474", # "purchase_date": "2020-04-18 16:27:42 Etc/GMT", # "purchase_date_ms": "1587227262000", # "purchase_date_pst": "2020-04-18 09:27:42 America/Los_Angeles", # "original_purchase_date": "2020-04-18 16:27:44 Etc/GMT", # "original_purchase_date_ms": "1587227264000", # "original_purchase_date_pst": "2020-04-18 09:27:44 America/Los_Angeles", # "expires_date": "2020-04-18 16:32:42 Etc/GMT", # "expires_date_ms": "1587227562000", # "expires_date_pst": "2020-04-18 09:32:42 America/Los_Angeles", # "web_order_line_item_id": "1000000051847459", # "is_trial_period": "false", # "is_in_intro_offer_period": "false", # }, # { # "quantity": "1", # "product_id": "io.simplelogin.ios_app.subscription.premium.monthly", # "transaction_id": "1000000653584861", # "original_transaction_id": "1000000653584474", # "purchase_date": "2020-04-18 16:32:42 Etc/GMT", # "purchase_date_ms": "1587227562000", # "purchase_date_pst": "2020-04-18 09:32:42 America/Los_Angeles", # "original_purchase_date": "2020-04-18 16:27:44 Etc/GMT", # "original_purchase_date_ms": "1587227264000", # "original_purchase_date_pst": "2020-04-18 09:27:44 America/Los_Angeles", # "expires_date": "2020-04-18 16:37:42 Etc/GMT", # "expires_date_ms": "1587227862000", # "expires_date_pst": "2020-04-18 09:37:42 America/Los_Angeles", # "web_order_line_item_id": "1000000051847461", # "is_trial_period": "false", # "is_in_intro_offer_period": "false", # }, # ], # }, # "latest_receipt_info": [ # { # "quantity": "1", # "product_id": "io.simplelogin.ios_app.subscription.premium.monthly", # "transaction_id": "1000000653584474", # "original_transaction_id": "1000000653584474", # "purchase_date": "2020-04-18 16:27:42 Etc/GMT", # "purchase_date_ms": "1587227262000", # "purchase_date_pst": "2020-04-18 09:27:42 America/Los_Angeles", # "original_purchase_date": "2020-04-18 16:27:44 Etc/GMT", # "original_purchase_date_ms": "1587227264000", # "original_purchase_date_pst": "2020-04-18 09:27:44 America/Los_Angeles", # "expires_date": "2020-04-18 16:32:42 Etc/GMT", # "expires_date_ms": "1587227562000", # "expires_date_pst": "2020-04-18 09:32:42 America/Los_Angeles", # "web_order_line_item_id": "1000000051847459", # "is_trial_period": "false", # "is_in_intro_offer_period": "false", # "subscription_group_identifier": "20624274", # }, # { # "quantity": "1", # "product_id": "io.simplelogin.ios_app.subscription.premium.monthly", # "transaction_id": "1000000653584861", # "original_transaction_id": "1000000653584474", # "purchase_date": "2020-04-18 16:32:42 Etc/GMT", # "purchase_date_ms": "1587227562000", # "purchase_date_pst": "2020-04-18 09:32:42 America/Los_Angeles", # "original_purchase_date": "2020-04-18 16:27:44 Etc/GMT", # "original_purchase_date_ms": "1587227264000", # "original_purchase_date_pst": "2020-04-18 09:27:44 America/Los_Angeles", # "expires_date": "2020-04-18 16:37:42 Etc/GMT", # "expires_date_ms": "1587227862000", # "expires_date_pst": "2020-04-18 09:37:42 America/Los_Angeles", # "web_order_line_item_id": "1000000051847461", # "is_trial_period": "false", # "is_in_intro_offer_period": "false", # "subscription_group_identifier": "20624274", # }, # { # "quantity": "1", # "product_id": "io.simplelogin.ios_app.subscription.premium.monthly", # "transaction_id": "1000000653585235", # "original_transaction_id": "1000000653584474", # "purchase_date": "2020-04-18 16:38:16 Etc/GMT", # "purchase_date_ms": "1587227896000", # "purchase_date_pst": "2020-04-18 09:38:16 America/Los_Angeles", # "original_purchase_date": "2020-04-18 16:27:44 Etc/GMT", # "original_purchase_date_ms": "1587227264000", # "original_purchase_date_pst": "2020-04-18 09:27:44 America/Los_Angeles", # "expires_date": "2020-04-18 16:43:16 Etc/GMT", # "expires_date_ms": "1587228196000", # "expires_date_pst": "2020-04-18 09:43:16 America/Los_Angeles", # "web_order_line_item_id": "1000000051847500", # "is_trial_period": "false", # "is_in_intro_offer_period": "false", # "subscription_group_identifier": "20624274", # }, # { # "quantity": "1", # "product_id": "io.simplelogin.ios_app.subscription.premium.monthly", # "transaction_id": "1000000653585760", # "original_transaction_id": "1000000653584474", # "purchase_date": "2020-04-18 16:44:25 Etc/GMT", # "purchase_date_ms": "1587228265000", # "purchase_date_pst": "2020-04-18 09:44:25 America/Los_Angeles", # "original_purchase_date": "2020-04-18 16:27:44 Etc/GMT", # "original_purchase_date_ms": "1587227264000", # "original_purchase_date_pst": "2020-04-18 09:27:44 America/Los_Angeles", # "expires_date": "2020-04-18 16:49:25 Etc/GMT", # "expires_date_ms": "1587228565000", # "expires_date_pst": "2020-04-18 09:49:25 America/Los_Angeles", # "web_order_line_item_id": "1000000051847566", # "is_trial_period": "false", # "is_in_intro_offer_period": "false", # "subscription_group_identifier": "20624274", # }, # ], # "latest_receipt": "very long string", # "pending_renewal_info": [ # { # "auto_renew_product_id": "io.simplelogin.ios_app.subscription.premium.monthly", # "original_transaction_id": "1000000653584474", # "product_id": "io.simplelogin.ios_app.subscription.premium.monthly", # "auto_renew_status": "1", # } # ], # } if data["status"] != 0: LOG.e( "verifyReceipt status !=0, probably invalid receipt. User %s, data %s", user, data, ) return None # use responseBody.Latest_receipt_info and not responseBody.Receipt.In_app # as recommended on https://developer.apple.com/documentation/appstorereceipts/responsebody/receipt/in_app # each item in data["latest_receipt_info"] has the following format # { # "quantity": "1", # "product_id": "io.simplelogin.ios_app.subscription.premium.monthly", # "transaction_id": "1000000653584474", # "original_transaction_id": "1000000653584474", # "purchase_date": "2020-04-18 16:27:42 Etc/GMT", # "purchase_date_ms": "1587227262000", # "purchase_date_pst": "2020-04-18 09:27:42 America/Los_Angeles", # "original_purchase_date": "2020-04-18 16:27:44 Etc/GMT", # "original_purchase_date_ms": "1587227264000", # "original_purchase_date_pst": "2020-04-18 09:27:44 America/Los_Angeles", # "expires_date": "2020-04-18 16:32:42 Etc/GMT", # "expires_date_ms": "1587227562000", # "expires_date_pst": "2020-04-18 09:32:42 America/Los_Angeles", # "web_order_line_item_id": "1000000051847459", # "is_trial_period": "false", # "is_in_intro_offer_period": "false", # } transactions = data.get("latest_receipt_info") if not transactions: LOG.i("Empty transactions in data %s", data) return None latest_transaction = max(transactions, key=lambda t: int(t["expires_date_ms"])) original_transaction_id = latest_transaction["original_transaction_id"] expires_date = arrow.get(int(latest_transaction["expires_date_ms"]) / 1000) plan = ( PlanEnum.monthly if latest_transaction["product_id"] in ( _MONTHLY_PRODUCT_ID, _MACAPP_MONTHLY_PRODUCT_ID, _MACAPP_MONTHLY_PRODUCT_ID_NEW, ) else PlanEnum.yearly ) apple_sub: AppleSubscription = AppleSubscription.get_by(user_id=user.id) if apple_sub: LOG.d( "Update AppleSubscription for user %s, expired at %s (%s), plan %s", user, expires_date, expires_date.humanize(), plan, ) apple_sub.receipt_data = receipt_data apple_sub.expires_date = expires_date apple_sub.original_transaction_id = original_transaction_id apple_sub.product_id = latest_transaction["product_id"] apple_sub.plan = plan else: # the same original_transaction_id has been used on another account if AppleSubscription.get_by(original_transaction_id=original_transaction_id): LOG.e("Same Apple Sub has been used before, current user %s", user) return None LOG.d( "Create new AppleSubscription for user %s, expired at %s, plan %s", user, expires_date, plan, ) apple_sub = AppleSubscription.create( user_id=user.id, receipt_data=receipt_data, expires_date=expires_date, original_transaction_id=original_transaction_id, plan=plan, product_id=latest_transaction["product_id"], ) execute_subscription_webhook(user) Session.commit() return apple_sub APPLE_API_SECRET = os.environ.get("APPLE_API_SECRET") MACAPP_APPLE_API_SECRET = os.environ.get("MACAPP_APPLE_API_SECRET") def execute_subscription_webhook(user: User): webhook_url = config.SUBSCRIPTION_CHANGE_WEBHOOK if webhook_url is None: return subscription_end = user.get_active_subscription_end( include_partner_subscription=False ) sl_subscription_end = None if subscription_end: sl_subscription_end = subscription_end.timestamp payload = { "user_id": user.id, "is_premium": user.is_premium(), "active_subscription_end": sl_subscription_end, } try: response = requests.post(webhook_url, json=payload, timeout=2) if response.status_code == 200: LOG.i("Sent request to subscription update webhook successfully") else: LOG.i( f"Request to webhook failed with statue {response.status_code}: {response.text}" ) except RequestException as e: LOG.error(f"Subscription request exception: {e}") LOG = _get_logger("SL") The provided code snippet includes necessary dependencies for implementing the `apple_process_payment` function. Write a Python function `def apple_process_payment()` to solve the following problem: Process payment Input: receipt_data: in body (optional) is_macapp: in body Output: 200 of the payment is successful, i.e. user is upgraded to premium Here is the function: def apple_process_payment(): """ Process payment Input: receipt_data: in body (optional) is_macapp: in body Output: 200 of the payment is successful, i.e. user is upgraded to premium """ user = g.user LOG.d("request for /apple/process_payment from %s", user) data = request.get_json() receipt_data = data.get("receipt_data") is_macapp = "is_macapp" in data and data["is_macapp"] is True if is_macapp: LOG.d("Use Macapp secret") password = MACAPP_APPLE_API_SECRET else: password = APPLE_API_SECRET apple_sub = verify_receipt(receipt_data, user, password) if apple_sub: execute_subscription_webhook(user) return jsonify(ok=True), 200 return jsonify(error="Processing failed"), 400
Process payment Input: receipt_data: in body (optional) is_macapp: in body Output: 200 of the payment is successful, i.e. user is upgraded to premium
180,616
from typing import Optional import arrow import requests from flask import g from flask import jsonify from flask import request from requests import RequestException from app.api.base import api_bp, require_api_auth from app.config import APPLE_API_SECRET, MACAPP_APPLE_API_SECRET from app.subscription_webhook import execute_subscription_webhook from app.db import Session from app.log import LOG from app.models import PlanEnum, AppleSubscription _MONTHLY_PRODUCT_ID = "io.simplelogin.ios_app.subscription.premium.monthly" _MACAPP_MONTHLY_PRODUCT_ID = "io.simplelogin.macapp.subscription.premium.monthly" _MACAPP_MONTHLY_PRODUCT_ID_NEW = "me.proton.simplelogin.macos.premium.monthly" def execute_subscription_webhook(user: User): webhook_url = config.SUBSCRIPTION_CHANGE_WEBHOOK if webhook_url is None: return subscription_end = user.get_active_subscription_end( include_partner_subscription=False ) sl_subscription_end = None if subscription_end: sl_subscription_end = subscription_end.timestamp payload = { "user_id": user.id, "is_premium": user.is_premium(), "active_subscription_end": sl_subscription_end, } try: response = requests.post(webhook_url, json=payload, timeout=2) if response.status_code == 200: LOG.i("Sent request to subscription update webhook successfully") else: LOG.i( f"Request to webhook failed with statue {response.status_code}: {response.text}" ) except RequestException as e: LOG.error(f"Subscription request exception: {e}") Session = scoped_session(sessionmaker(bind=connection)) Session: sqlalchemy.orm.Session LOG = _get_logger("SL") class PlanEnum(EnumE): monthly = 2 yearly = 3 class AppleSubscription(Base, ModelMixin): """ For users who have subscribed via Apple in-app payment """ __tablename__ = "apple_subscription" user_id = sa.Column( sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, unique=True ) expires_date = sa.Column(ArrowType, nullable=False) # to avoid using "Restore Purchase" on another account original_transaction_id = sa.Column(sa.String(256), nullable=False, unique=True) receipt_data = sa.Column(sa.Text(), nullable=False) plan = sa.Column(sa.Enum(PlanEnum), nullable=False) # to know what subscription user has bought # e.g. io.simplelogin.ios_app.subscription.premium.monthly product_id = sa.Column(sa.String(256), nullable=True) user = orm.relationship(User) def is_valid(self): return self.expires_date > arrow.now().shift(days=-_APPLE_GRACE_PERIOD_DAYS) The provided code snippet includes necessary dependencies for implementing the `apple_update_notification` function. Write a Python function `def apple_update_notification()` to solve the following problem: The "Subscription Status URL" to receive update notifications from Apple Here is the function: def apple_update_notification(): """ The "Subscription Status URL" to receive update notifications from Apple """ # request.json looks like this # will use unified_receipt.latest_receipt_info and NOT latest_expired_receipt_info # more info on https://developer.apple.com/documentation/appstoreservernotifications/responsebody # { # "unified_receipt": { # "latest_receipt": "long string", # "pending_renewal_info": [ # { # "is_in_billing_retry_period": "0", # "auto_renew_status": "0", # "original_transaction_id": "1000000654277043", # "product_id": "io.simplelogin.ios_app.subscription.premium.yearly", # "expiration_intent": "1", # "auto_renew_product_id": "io.simplelogin.ios_app.subscription.premium.yearly", # } # ], # "environment": "Sandbox", # "status": 0, # "latest_receipt_info": [ # { # "expires_date_pst": "2020-04-20 21:11:57 America/Los_Angeles", # "purchase_date": "2020-04-21 03:11:57 Etc/GMT", # "purchase_date_ms": "1587438717000", # "original_purchase_date_ms": "1587420715000", # "transaction_id": "1000000654329911", # "original_transaction_id": "1000000654277043", # "quantity": "1", # "expires_date_ms": "1587442317000", # "original_purchase_date_pst": "2020-04-20 15:11:55 America/Los_Angeles", # "product_id": "io.simplelogin.ios_app.subscription.premium.yearly", # "subscription_group_identifier": "20624274", # "web_order_line_item_id": "1000000051891577", # "expires_date": "2020-04-21 04:11:57 Etc/GMT", # "is_in_intro_offer_period": "false", # "original_purchase_date": "2020-04-20 22:11:55 Etc/GMT", # "purchase_date_pst": "2020-04-20 20:11:57 America/Los_Angeles", # "is_trial_period": "false", # }, # { # "expires_date_pst": "2020-04-20 20:11:57 America/Los_Angeles", # "purchase_date": "2020-04-21 02:11:57 Etc/GMT", # "purchase_date_ms": "1587435117000", # "original_purchase_date_ms": "1587420715000", # "transaction_id": "1000000654313889", # "original_transaction_id": "1000000654277043", # "quantity": "1", # "expires_date_ms": "1587438717000", # "original_purchase_date_pst": "2020-04-20 15:11:55 America/Los_Angeles", # "product_id": "io.simplelogin.ios_app.subscription.premium.yearly", # "subscription_group_identifier": "20624274", # "web_order_line_item_id": "1000000051890729", # "expires_date": "2020-04-21 03:11:57 Etc/GMT", # "is_in_intro_offer_period": "false", # "original_purchase_date": "2020-04-20 22:11:55 Etc/GMT", # "purchase_date_pst": "2020-04-20 19:11:57 America/Los_Angeles", # "is_trial_period": "false", # }, # { # "expires_date_pst": "2020-04-20 19:11:54 America/Los_Angeles", # "purchase_date": "2020-04-21 01:11:54 Etc/GMT", # "purchase_date_ms": "1587431514000", # "original_purchase_date_ms": "1587420715000", # "transaction_id": "1000000654300800", # "original_transaction_id": "1000000654277043", # "quantity": "1", # "expires_date_ms": "1587435114000", # "original_purchase_date_pst": "2020-04-20 15:11:55 America/Los_Angeles", # "product_id": "io.simplelogin.ios_app.subscription.premium.yearly", # "subscription_group_identifier": "20624274", # "web_order_line_item_id": "1000000051890161", # "expires_date": "2020-04-21 02:11:54 Etc/GMT", # "is_in_intro_offer_period": "false", # "original_purchase_date": "2020-04-20 22:11:55 Etc/GMT", # "purchase_date_pst": "2020-04-20 18:11:54 America/Los_Angeles", # "is_trial_period": "false", # }, # { # "expires_date_pst": "2020-04-20 18:11:54 America/Los_Angeles", # "purchase_date": "2020-04-21 00:11:54 Etc/GMT", # "purchase_date_ms": "1587427914000", # "original_purchase_date_ms": "1587420715000", # "transaction_id": "1000000654293615", # "original_transaction_id": "1000000654277043", # "quantity": "1", # "expires_date_ms": "1587431514000", # "original_purchase_date_pst": "2020-04-20 15:11:55 America/Los_Angeles", # "product_id": "io.simplelogin.ios_app.subscription.premium.yearly", # "subscription_group_identifier": "20624274", # "web_order_line_item_id": "1000000051889539", # "expires_date": "2020-04-21 01:11:54 Etc/GMT", # "is_in_intro_offer_period": "false", # "original_purchase_date": "2020-04-20 22:11:55 Etc/GMT", # "purchase_date_pst": "2020-04-20 17:11:54 America/Los_Angeles", # "is_trial_period": "false", # }, # { # "expires_date_pst": "2020-04-20 17:11:54 America/Los_Angeles", # "purchase_date": "2020-04-20 23:11:54 Etc/GMT", # "purchase_date_ms": "1587424314000", # "original_purchase_date_ms": "1587420715000", # "transaction_id": "1000000654285464", # "original_transaction_id": "1000000654277043", # "quantity": "1", # "expires_date_ms": "1587427914000", # "original_purchase_date_pst": "2020-04-20 15:11:55 America/Los_Angeles", # "product_id": "io.simplelogin.ios_app.subscription.premium.yearly", # "subscription_group_identifier": "20624274", # "web_order_line_item_id": "1000000051888827", # "expires_date": "2020-04-21 00:11:54 Etc/GMT", # "is_in_intro_offer_period": "false", # "original_purchase_date": "2020-04-20 22:11:55 Etc/GMT", # "purchase_date_pst": "2020-04-20 16:11:54 America/Los_Angeles", # "is_trial_period": "false", # }, # { # "expires_date_pst": "2020-04-20 16:11:54 America/Los_Angeles", # "purchase_date": "2020-04-20 22:11:54 Etc/GMT", # "purchase_date_ms": "1587420714000", # "original_purchase_date_ms": "1587420715000", # "transaction_id": "1000000654277043", # "original_transaction_id": "1000000654277043", # "quantity": "1", # "expires_date_ms": "1587424314000", # "original_purchase_date_pst": "2020-04-20 15:11:55 America/Los_Angeles", # "product_id": "io.simplelogin.ios_app.subscription.premium.yearly", # "subscription_group_identifier": "20624274", # "web_order_line_item_id": "1000000051888825", # "expires_date": "2020-04-20 23:11:54 Etc/GMT", # "is_in_intro_offer_period": "false", # "original_purchase_date": "2020-04-20 22:11:55 Etc/GMT", # "purchase_date_pst": "2020-04-20 15:11:54 America/Los_Angeles", # "is_trial_period": "false", # }, # ], # }, # "auto_renew_status_change_date": "2020-04-21 04:11:33 Etc/GMT", # "environment": "Sandbox", # "auto_renew_status": "false", # "auto_renew_status_change_date_pst": "2020-04-20 21:11:33 America/Los_Angeles", # "latest_expired_receipt": "long string", # "latest_expired_receipt_info": { # "original_purchase_date_pst": "2020-04-20 15:11:55 America/Los_Angeles", # "quantity": "1", # "subscription_group_identifier": "20624274", # "unique_vendor_identifier": "4C4DF6BA-DE2A-4737-9A68-5992338886DC", # "original_purchase_date_ms": "1587420715000", # "expires_date_formatted": "2020-04-21 04:11:57 Etc/GMT", # "is_in_intro_offer_period": "false", # "purchase_date_ms": "1587438717000", # "expires_date_formatted_pst": "2020-04-20 21:11:57 America/Los_Angeles", # "is_trial_period": "false", # "item_id": "1508744966", # "unique_identifier": "b55fc3dcc688e979115af0697a0195be78be7cbd", # "original_transaction_id": "1000000654277043", # "expires_date": "1587442317000", # "transaction_id": "1000000654329911", # "bvrs": "3", # "web_order_line_item_id": "1000000051891577", # "version_external_identifier": "834289833", # "bid": "io.simplelogin.ios-app", # "product_id": "io.simplelogin.ios_app.subscription.premium.yearly", # "purchase_date": "2020-04-21 03:11:57 Etc/GMT", # "purchase_date_pst": "2020-04-20 20:11:57 America/Los_Angeles", # "original_purchase_date": "2020-04-20 22:11:55 Etc/GMT", # }, # "password": "22b9d5a110dd4344a1681631f1f95f55", # "auto_renew_status_change_date_ms": "1587442293000", # "auto_renew_product_id": "io.simplelogin.ios_app.subscription.premium.yearly", # "notification_type": "DID_CHANGE_RENEWAL_STATUS", # } LOG.d("request for /api/apple/update_notification") data = request.get_json() if not ( data and data.get("unified_receipt") and data["unified_receipt"].get("latest_receipt_info") ): LOG.d("Invalid data %s", data) return jsonify(error="Empty Response"), 400 transactions = data["unified_receipt"]["latest_receipt_info"] # dict of original_transaction_id and transaction latest_transactions = {} for transaction in transactions: original_transaction_id = transaction["original_transaction_id"] if not latest_transactions.get(original_transaction_id): latest_transactions[original_transaction_id] = transaction if ( transaction["expires_date_ms"] > latest_transactions[original_transaction_id]["expires_date_ms"] ): latest_transactions[original_transaction_id] = transaction for original_transaction_id, transaction in latest_transactions.items(): expires_date = arrow.get(int(transaction["expires_date_ms"]) / 1000) plan = ( PlanEnum.monthly if transaction["product_id"] in ( _MONTHLY_PRODUCT_ID, _MACAPP_MONTHLY_PRODUCT_ID, _MACAPP_MONTHLY_PRODUCT_ID_NEW, ) else PlanEnum.yearly ) apple_sub: AppleSubscription = AppleSubscription.get_by( original_transaction_id=original_transaction_id ) if apple_sub: user = apple_sub.user LOG.d( "Update AppleSubscription for user %s, expired at %s, plan %s", user, expires_date, plan, ) apple_sub.receipt_data = data["unified_receipt"]["latest_receipt"] apple_sub.expires_date = expires_date apple_sub.plan = plan apple_sub.product_id = transaction["product_id"] Session.commit() execute_subscription_webhook(user) return jsonify(ok=True), 200 else: LOG.w( "No existing AppleSub for original_transaction_id %s", original_transaction_id, ) LOG.d("request data %s", data) return jsonify(error="Processing failed"), 400
The "Subscription Status URL" to receive update notifications from Apple
180,617
from flask import g from flask import jsonify from flask import request from app.api.base import api_bp, require_api_auth from app.config import PAGE_LIMIT 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, ) The provided code snippet includes necessary dependencies for implementing the `get_notifications` function. Write a Python function `def get_notifications()` to solve the following problem: Get notifications Input: - page: in url. Starts at 0 Output: - more: boolean. Whether there's more notification to load - notifications: list of notifications. - id - message - title - read - created_at Here is the function: def get_notifications(): """ Get notifications Input: - page: in url. Starts at 0 Output: - more: boolean. Whether there's more notification to load - notifications: list of notifications. - id - message - title - read - created_at """ user = g.user try: page = int(request.args.get("page")) except (ValueError, TypeError): return jsonify(error="page must be provided in request query"), 400 notifications = ( Notification.filter_by(user_id=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() ) have_more = len(notifications) > PAGE_LIMIT return ( jsonify( more=have_more, notifications=[ { "id": notification.id, "message": notification.message, "title": notification.title, "read": notification.read, "created_at": notification.created_at.humanize(), } for notification in notifications[:PAGE_LIMIT] ], ), 200, )
Get notifications Input: - page: in url. Starts at 0 Output: - more: boolean. Whether there's more notification to load - notifications: list of notifications. - id - message - title - read - created_at
180,618
from flask import g from flask import jsonify from flask import request from app.api.base import api_bp, require_api_auth from app.config import PAGE_LIMIT from app.db import Session from app.models import Notification Session = scoped_session(sessionmaker(bind=connection)) Session: sqlalchemy.orm.Session 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, ) The provided code snippet includes necessary dependencies for implementing the `mark_as_read` function. Write a Python function `def mark_as_read(notification_id)` to solve the following problem: Mark a notification as read Input: notification_id: in url Output: 200 if updated successfully Here is the function: def mark_as_read(notification_id): """ Mark a notification as read Input: notification_id: in url Output: 200 if updated successfully """ user = g.user notification = Notification.get(notification_id) if not notification or notification.user_id != user.id: return jsonify(error="Forbidden"), 403 notification.read = True Session.commit() return jsonify(done=True), 200
Mark a notification as read Input: notification_id: in url Output: 200 if updated successfully
180,619
import secrets import string import facebook import google.oauth2.credentials import googleapiclient.discovery from flask import jsonify, request from flask_login import login_user from itsdangerous import Signer from app import email_utils from app.api.base import api_bp from app.config import FLASK_SECRET, DISABLE_REGISTRATION from app.dashboard.views.account_setting import send_reset_password_email from app.db import Session from app.email_utils import ( email_can_be_used_as_mailbox, personal_email_already_used, send_email, render, ) from app.events.auth_event import LoginEvent, RegisterEvent from app.extensions import limiter from app.log import LOG from app.models import User, ApiKey, SocialAuth, AccountActivation from app.utils import sanitize_email, canonicalize_email def auth_payload(user, device) -> dict: ret = {"name": user.name or "", "email": user.email, "mfa_enabled": user.enable_otp} # do not give api_key, user can only obtain api_key after OTP verification if user.enable_otp: s = Signer(FLASK_SECRET) ret["mfa_key"] = s.sign(str(user.id)) ret["api_key"] = None else: api_key = ApiKey.get_by(user_id=user.id, name=device) if not api_key: LOG.d("create new api key for %s and %s", user, device) api_key = ApiKey.create(user.id, device) Session.commit() ret["mfa_key"] = None ret["api_key"] = api_key.code # so user is automatically logged in on the web login_user(user) return ret class LoginEvent: class ActionType(EnumE): success = 0 failed = 1 disabled_login = 2 not_activated = 3 scheduled_to_be_deleted = 4 class Source(EnumE): web = 0 api = 1 def __init__(self, action: ActionType, source: Source = Source.web): self.action = action self.source = source def send(self): newrelic.agent.record_custom_event( "LoginEvent", {"action": self.action.name, "source": self.source.name} ) 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}>" 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", "") The provided code snippet includes necessary dependencies for implementing the `auth_login` function. Write a Python function `def auth_login()` to solve the following problem: Authenticate user Input: email password device: to create an ApiKey associated with this device Output: 200 and user info containing: { name: "John Wick", mfa_enabled: true, mfa_key: "a long string", api_key: "a long string" } Here is the function: def auth_login(): """ Authenticate user Input: email password device: to create an ApiKey associated with this device Output: 200 and user info containing: { name: "John Wick", mfa_enabled: true, mfa_key: "a long string", api_key: "a long string" } """ data = request.get_json() if not data: return jsonify(error="request body cannot be empty"), 400 password = data.get("password") device = data.get("device") email = sanitize_email(data.get("email")) canonical_email = canonicalize_email(data.get("email")) user = User.get_by(email=email) or User.get_by(email=canonical_email) if not user or not user.check_password(password): LoginEvent(LoginEvent.ActionType.failed, LoginEvent.Source.api).send() return jsonify(error="Email or password incorrect"), 400 elif user.disabled: LoginEvent(LoginEvent.ActionType.disabled_login, LoginEvent.Source.api).send() return jsonify(error="Account disabled"), 400 elif user.delete_on is not None: LoginEvent( LoginEvent.ActionType.scheduled_to_be_deleted, LoginEvent.Source.api ).send() return jsonify(error="Account scheduled for deletion"), 400 elif not user.activated: LoginEvent(LoginEvent.ActionType.not_activated, LoginEvent.Source.api).send() return jsonify(error="Account not activated"), 422 elif user.fido_enabled(): # allow user who has TOTP enabled to continue using the mobile app if not user.enable_otp: return jsonify(error="Currently we don't support FIDO on mobile yet"), 403 LoginEvent(LoginEvent.ActionType.success, LoginEvent.Source.api).send() return jsonify(**auth_payload(user, device)), 200
Authenticate user Input: email password device: to create an ApiKey associated with this device Output: 200 and user info containing: { name: "John Wick", mfa_enabled: true, mfa_key: "a long string", api_key: "a long string" }
180,620
import secrets import string import facebook import google.oauth2.credentials import googleapiclient.discovery from flask import jsonify, request from flask_login import login_user from itsdangerous import Signer from app import email_utils from app.api.base import api_bp from app.config import FLASK_SECRET, DISABLE_REGISTRATION from app.dashboard.views.account_setting import send_reset_password_email from app.db import Session from app.email_utils import ( email_can_be_used_as_mailbox, personal_email_already_used, send_email, render, ) from app.events.auth_event import LoginEvent, RegisterEvent from app.extensions import limiter from app.log import LOG from app.models import User, ApiKey, SocialAuth, AccountActivation from app.utils import sanitize_email, canonicalize_email DISABLE_REGISTRATION = "DISABLE_REGISTRATION" in os.environ 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 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 RegisterEvent: class ActionType(EnumE): success = 0 failed = 1 catpcha_failed = 2 email_in_use = 3 invalid_email = 4 class Source(EnumE): web = 0 api = 1 def __init__(self, action: ActionType, source: Source = Source.web): self.action = action self.source = source def send(self): newrelic.agent.record_custom_event( "RegisterEvent", {"action": self.action.name, "source": self.source.name} ) 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 AccountActivation(Base, ModelMixin): """contains code to activate the user account when they sign up on mobile""" __tablename__ = "account_activation" user_id = sa.Column( sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, unique=True ) # the activation code is usually 6 digits code = sa.Column(sa.String(10), nullable=False) # nb tries decrements each time user enters wrong code tries = sa.Column(sa.Integer, default=3, nullable=False) __table_args__ = ( CheckConstraint(tries >= 0, name="account_activation_tries_positive"), {}, ) 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() The provided code snippet includes necessary dependencies for implementing the `auth_register` function. Write a Python function `def auth_register()` to solve the following problem: User signs up - will need to activate their account with an activation code. Input: email password Output: 200: user needs to confirm their account Here is the function: def auth_register(): """ User signs up - will need to activate their account with an activation code. Input: email password Output: 200: user needs to confirm their account """ data = request.get_json() if not data: return jsonify(error="request body cannot be empty"), 400 dirty_email = data.get("email") email = canonicalize_email(dirty_email) password = data.get("password") if DISABLE_REGISTRATION: RegisterEvent(RegisterEvent.ActionType.failed, RegisterEvent.Source.api).send() return jsonify(error="registration is closed"), 400 if not email_can_be_used_as_mailbox(email) or personal_email_already_used(email): RegisterEvent( RegisterEvent.ActionType.invalid_email, RegisterEvent.Source.api ).send() return jsonify(error=f"cannot use {email} as personal inbox"), 400 if not password or len(password) < 8: RegisterEvent(RegisterEvent.ActionType.failed, RegisterEvent.Source.api).send() return jsonify(error="password too short"), 400 if len(password) > 100: RegisterEvent(RegisterEvent.ActionType.failed, RegisterEvent.Source.api).send() return jsonify(error="password too long"), 400 LOG.d("create user %s", email) user = User.create(email=email, name=dirty_email, password=password) Session.flush() # create activation code code = "".join([str(secrets.choice(string.digits)) for _ in range(6)]) AccountActivation.create(user_id=user.id, code=code) Session.commit() send_email( email, "Just one more step to join SimpleLogin", render("transactional/code-activation.txt.jinja2", code=code), render("transactional/code-activation.html", code=code), ) RegisterEvent(RegisterEvent.ActionType.success, RegisterEvent.Source.api).send() return jsonify(msg="User needs to confirm their account"), 200
User signs up - will need to activate their account with an activation code. Input: email password Output: 200: user needs to confirm their account
180,621
import secrets import string import facebook import google.oauth2.credentials import googleapiclient.discovery from flask import jsonify, request from flask_login import login_user from itsdangerous import Signer from app import email_utils from app.api.base import api_bp from app.config import FLASK_SECRET, DISABLE_REGISTRATION from app.dashboard.views.account_setting import send_reset_password_email from app.db import Session from app.email_utils import ( email_can_be_used_as_mailbox, personal_email_already_used, send_email, render, ) from app.events.auth_event import LoginEvent, RegisterEvent from app.extensions import limiter from app.log import LOG from app.models import User, ApiKey, SocialAuth, AccountActivation from app.utils import sanitize_email, canonicalize_email Session = scoped_session(sessionmaker(bind=connection)) Session: sqlalchemy.orm.Session LOG = _get_logger("SL") class User(Base, ModelMixin, UserMixin, PasswordOracle): __tablename__ = "users" FLAG_FREE_DISABLE_CREATE_ALIAS = 1 << 0 FLAG_CREATED_FROM_PARTNER = 1 << 1 FLAG_FREE_OLD_ALIAS_LIMIT = 1 << 2 email = sa.Column(sa.String(256), unique=True, nullable=False) name = sa.Column(sa.String(128), nullable=True) is_admin = sa.Column(sa.Boolean, nullable=False, default=False) alias_generator = sa.Column( sa.Integer, nullable=False, default=AliasGeneratorEnum.word.value, server_default=str(AliasGeneratorEnum.word.value), ) notification = sa.Column( sa.Boolean, default=True, nullable=False, server_default="1" ) activated = sa.Column(sa.Boolean, default=False, nullable=False, index=True) # an account can be disabled if having harmful behavior disabled = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0") profile_picture_id = sa.Column(sa.ForeignKey(File.id), nullable=True) otp_secret = sa.Column(sa.String(16), nullable=True) enable_otp = sa.Column( sa.Boolean, nullable=False, default=False, server_default="0" ) last_otp = sa.Column(sa.String(12), nullable=True, default=False) # Fields for WebAuthn fido_uuid = sa.Column(sa.String(), nullable=True, unique=True) # the default domain that's used when user creates a new random alias # default_alias_custom_domain_id XOR default_alias_public_domain_id default_alias_custom_domain_id = sa.Column( sa.ForeignKey("custom_domain.id", ondelete="SET NULL"), nullable=True, default=None, ) default_alias_public_domain_id = sa.Column( sa.ForeignKey("public_domain.id", ondelete="SET NULL"), nullable=True, default=None, ) # some users could have lifetime premium lifetime = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0") paid_lifetime = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) lifetime_coupon_id = sa.Column( sa.ForeignKey("lifetime_coupon.id", ondelete="SET NULL"), nullable=True, default=None, ) # user can use all premium features until this date trial_end = sa.Column( ArrowType, default=lambda: arrow.now().shift(days=7, hours=1), nullable=True ) # the mailbox used when create random alias # this field is nullable but in practice, it's always set # it cannot be set to non-nullable though # as this will create foreign key cycle between User and Mailbox default_mailbox_id = sa.Column( sa.ForeignKey("mailbox.id"), nullable=True, default=None ) profile_picture = orm.relationship(File, foreign_keys=[profile_picture_id]) # Specify the format for sender address # for the full list, see SenderFormatEnum sender_format = sa.Column( sa.Integer, default="0", nullable=False, server_default="0" ) # to know whether user has explicitly chosen a sender format as opposed to those who use the default ones. # users who haven't chosen a sender format and are using 1 or 3 format, their sender format will be set to 0 sender_format_updated_at = sa.Column(ArrowType, default=None) replace_reverse_alias = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) referral_id = sa.Column( sa.ForeignKey("referral.id", ondelete="SET NULL"), nullable=True, default=None, index=True, ) referral = orm.relationship("Referral", foreign_keys=[referral_id]) # whether intro has been shown to user intro_shown = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) default_mailbox = orm.relationship("Mailbox", foreign_keys=[default_mailbox_id]) # user can set a more strict max_spam score to block spams more aggressively max_spam_score = sa.Column(sa.Integer, nullable=True) # newsletter is sent to this address newsletter_alias_id = sa.Column( sa.ForeignKey("alias.id", ondelete="SET NULL"), nullable=True, default=None, index=True, ) # whether to include the sender address in reverse-alias include_sender_in_reverse_alias = sa.Column( sa.Boolean, default=True, nullable=False, server_default="0" ) # whether to use random string or random word as suffix # Random word from dictionary file -> 0 # Completely random string -> 1 random_alias_suffix = sa.Column( sa.Integer, nullable=False, default=AliasSuffixEnum.word.value, server_default=str(AliasSuffixEnum.random_string.value), ) # always expand the alias info, i.e. without needing to press "More" expand_alias_info = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # ignore emails send from a mailbox to its alias. This can happen when replying all to a forwarded email # can automatically re-includes the alias ignore_loop_email = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # used for flask-login as an "alternative token" # cf https://flask-login.readthedocs.io/en/latest/#alternative-tokens alternative_id = sa.Column(sa.String(128), unique=True, nullable=True) # by default, when an alias is automatically created, a note like "Created with ...." is created # If this field is True, the note won't be created. disable_automatic_alias_note = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # By default, the one-click unsubscribe disable the alias # If set to true, it will block the sender instead one_click_unsubscribe_block_sender = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # automatically include the website name when user creates an alias via the SimpleLogin icon in the email field include_website_in_one_click_alias = sa.Column( sa.Boolean, # new user will have this option turned on automatically default=True, nullable=False, # old user will have this option turned off server_default="0", ) _directory_quota = sa.Column( "directory_quota", sa.Integer, default=50, nullable=False, server_default="50" ) _subdomain_quota = sa.Column( "subdomain_quota", sa.Integer, default=5, nullable=False, server_default="5" ) # user can use import to import too many aliases disable_import = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # user can use the phone feature can_use_phone = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # in minutes phone_quota = sa.Column(sa.Integer, nullable=True) # Status code to return if is blocked block_behaviour = sa.Column( sa.Enum(BlockBehaviourEnum), nullable=False, server_default=BlockBehaviourEnum.return_2xx.name, ) include_header_email_header = sa.Column( sa.Boolean, default=True, nullable=False, server_default="1" ) # bitwise flags. Allow for future expansion flags = sa.Column( sa.BigInteger, default=FLAG_FREE_DISABLE_CREATE_ALIAS, server_default="0", nullable=False, ) # Keep original unsub behaviour unsub_behaviour = sa.Column( IntEnumType(UnsubscribeBehaviourEnum), default=UnsubscribeBehaviourEnum.PreserveOriginal, server_default=str(UnsubscribeBehaviourEnum.DisableAlias.value), nullable=False, ) # Trigger hard deletion of the account at this time delete_on = sa.Column(ArrowType, default=None) __table_args__ = ( sa.Index( "ix_users_activated_trial_end_lifetime", activated, trial_end, lifetime ), sa.Index("ix_users_delete_on", delete_on), ) def directory_quota(self): return min( self._directory_quota, config.MAX_NB_DIRECTORY - Directory.filter_by(user_id=self.id).count(), ) def subdomain_quota(self): return min( self._subdomain_quota, config.MAX_NB_SUBDOMAIN - CustomDomain.filter_by(user_id=self.id, is_sl_subdomain=True).count(), ) def created_by_partner(self): return User.FLAG_CREATED_FROM_PARTNER == ( self.flags & User.FLAG_CREATED_FROM_PARTNER ) def subdomain_is_available(): return SLDomain.filter_by(can_use_subdomain=True).count() > 0 # implement flask-login "alternative token" def get_id(self): if self.alternative_id: return self.alternative_id else: return str(self.id) def create(cls, email, name="", password=None, from_partner=False, **kwargs): email = sanitize_email(email) user: User = super(User, cls).create(email=email, name=name[:100], **kwargs) if password: user.set_password(password) Session.flush() mb = Mailbox.create(user_id=user.id, email=user.email, verified=True) Session.flush() user.default_mailbox_id = mb.id # generate an alternative_id if needed if "alternative_id" not in kwargs: user.alternative_id = str(uuid.uuid4()) # If the user is created from partner, do not notify # nor give a trial if from_partner: user.flags = User.FLAG_CREATED_FROM_PARTNER user.notification = False user.trial_end = None Job.create( name=config.JOB_SEND_PROTON_WELCOME_1, payload={"user_id": user.id}, run_at=arrow.now(), ) Session.flush() return user # create a first alias mail to show user how to use when they login alias = Alias.create_new( user, prefix="simplelogin-newsletter", mailbox_id=mb.id, note="This is your first alias. It's used to receive SimpleLogin communications " "like new features announcements, newsletters.", ) Session.flush() user.newsletter_alias_id = alias.id Session.flush() if config.DISABLE_ONBOARDING: LOG.d("Disable onboarding emails") return user # Schedule onboarding emails Job.create( name=config.JOB_ONBOARDING_1, payload={"user_id": user.id}, run_at=arrow.now().shift(days=1), ) Job.create( name=config.JOB_ONBOARDING_2, payload={"user_id": user.id}, run_at=arrow.now().shift(days=2), ) Job.create( name=config.JOB_ONBOARDING_4, payload={"user_id": user.id}, run_at=arrow.now().shift(days=3), ) Session.flush() return user def get_active_subscription( self, include_partner_subscription: bool = True ) -> Optional[ Union[ Subscription | AppleSubscription | ManualSubscription | CoinbaseSubscription | PartnerSubscription ] ]: sub: Subscription = self.get_paddle_subscription() if sub: return sub apple_sub: AppleSubscription = AppleSubscription.get_by(user_id=self.id) if apple_sub and apple_sub.is_valid(): return apple_sub manual_sub: ManualSubscription = ManualSubscription.get_by(user_id=self.id) if manual_sub and manual_sub.is_active(): return manual_sub coinbase_subscription: CoinbaseSubscription = CoinbaseSubscription.get_by( user_id=self.id ) if coinbase_subscription and coinbase_subscription.is_active(): return coinbase_subscription if include_partner_subscription: partner_sub: PartnerSubscription = PartnerSubscription.find_by_user_id( self.id ) if partner_sub and partner_sub.is_active(): return partner_sub return None def get_active_subscription_end( self, include_partner_subscription: bool = True ) -> Optional[arrow.Arrow]: sub = self.get_active_subscription( include_partner_subscription=include_partner_subscription ) if isinstance(sub, Subscription): return arrow.get(sub.next_bill_date) if isinstance(sub, AppleSubscription): return sub.expires_date if isinstance(sub, ManualSubscription): return sub.end_at if isinstance(sub, CoinbaseSubscription): return sub.end_at return None # region Billing def lifetime_or_active_subscription( self, include_partner_subscription: bool = True ) -> bool: """True if user has lifetime licence or active subscription""" if self.lifetime: return True return self.get_active_subscription(include_partner_subscription) is not None def is_paid(self) -> bool: """same as _lifetime_or_active_subscription but not include free manual subscription""" sub = self.get_active_subscription() if sub is None: return False if isinstance(sub, ManualSubscription) and sub.is_giveaway: return False return True def is_active(self) -> bool: if self.delete_on is None: return True return self.delete_on < arrow.now() def in_trial(self): """return True if user does not have lifetime licence or an active subscription AND is in trial period""" if self.lifetime_or_active_subscription(): return False if self.trial_end and arrow.now() < self.trial_end: return True return False def should_show_upgrade_button(self): if self.lifetime_or_active_subscription(): return False return True def is_premium(self, include_partner_subscription: bool = True) -> bool: """ user is premium if they: - have a lifetime deal or - in trial period or - active subscription """ if self.lifetime_or_active_subscription(include_partner_subscription): return True if self.trial_end and arrow.now() < self.trial_end: return True return False def upgrade_channel(self) -> str: """Used on admin dashboard""" # user can have multiple subscription channel channels = [] if self.lifetime: channels.append("Lifetime") sub: Subscription = self.get_paddle_subscription() if sub: if sub.cancelled: channels.append( f"""Cancelled Paddle Subscription <a href="https://vendors.paddle.com/subscriptions/customers/manage/{sub.subscription_id}">{sub.subscription_id}</a> {sub.plan_name()} ends at {sub.next_bill_date}""" ) else: channels.append( f"""Active Paddle Subscription <a href="https://vendors.paddle.com/subscriptions/customers/manage/{sub.subscription_id}">{sub.subscription_id}</a> {sub.plan_name()}, renews at {sub.next_bill_date}""" ) apple_sub: AppleSubscription = AppleSubscription.get_by(user_id=self.id) if apple_sub and apple_sub.is_valid(): channels.append(f"Apple Subscription {apple_sub.expires_date.humanize()}") manual_sub: ManualSubscription = ManualSubscription.get_by(user_id=self.id) if manual_sub and manual_sub.is_active(): mode = "Giveaway" if manual_sub.is_giveaway else "Paid" channels.append( f"Manual Subscription {manual_sub.comment} {mode} {manual_sub.end_at.humanize()}" ) coinbase_subscription: CoinbaseSubscription = CoinbaseSubscription.get_by( user_id=self.id ) if coinbase_subscription and coinbase_subscription.is_active(): channels.append( f"Coinbase Subscription ends {coinbase_subscription.end_at.humanize()}" ) r = ( Session.query(PartnerSubscription, PartnerUser, Partner) .filter( PartnerSubscription.partner_user_id == PartnerUser.id, PartnerUser.user_id == self.id, Partner.id == PartnerUser.partner_id, ) .first() ) if r and r[0].is_active(): channels.append( f"Subscription via {r[2].name} partner , ends {r[0].end_at.humanize()}" ) return ".\n".join(channels) # endregion def max_alias_for_free_account(self) -> int: if ( self.FLAG_FREE_OLD_ALIAS_LIMIT == self.flags & self.FLAG_FREE_OLD_ALIAS_LIMIT ): return config.MAX_NB_EMAIL_OLD_FREE_PLAN else: return config.MAX_NB_EMAIL_FREE_PLAN def can_create_new_alias(self) -> bool: """ Whether user can create a new alias. User can't create a new alias if - has more than 15 aliases in the free plan, *even in the free trial* """ if not self.is_active(): return False if self.disabled: return False if self.lifetime_or_active_subscription(): return True else: return ( Alias.filter_by(user_id=self.id).count() < self.max_alias_for_free_account() ) def can_send_or_receive(self) -> bool: if self.disabled: LOG.i(f"User {self} is disabled. Cannot receive or send emails") return False if self.delete_on is not None: LOG.i( f"User {self} is scheduled to be deleted. Cannot receive or send emails" ) return False return True def profile_picture_url(self): if self.profile_picture_id: return self.profile_picture.get_url() else: return url_for("static", filename="default-avatar.png") def suggested_emails(self, website_name) -> (str, [str]): """return suggested email and other email choices""" website_name = convert_to_id(website_name) all_aliases = [ ge.email for ge in Alias.filter_by(user_id=self.id, enabled=True) ] if self.can_create_new_alias(): suggested_alias = Alias.create_new(self, prefix=website_name).email else: # pick an email from the list of gen emails suggested_alias = random.choice(all_aliases) return ( suggested_alias, list(set(all_aliases).difference({suggested_alias})), ) def suggested_names(self) -> (str, [str]): """return suggested name and other name choices""" other_name = convert_to_id(self.name) return self.name, [other_name, "Anonymous", "whoami"] def get_name_initial(self) -> str: if not self.name: return "" names = self.name.split(" ") return "".join([n[0].upper() for n in names if n]) def get_paddle_subscription(self) -> Optional["Subscription"]: """return *active* Paddle subscription Return None if the subscription is already expired TODO: support user unsubscribe and re-subscribe """ sub = Subscription.get_by(user_id=self.id) if sub: # grace period is 14 days # sub is active until the next billing_date + PADDLE_SUBSCRIPTION_GRACE_DAYS if ( sub.next_bill_date >= arrow.now().shift(days=-PADDLE_SUBSCRIPTION_GRACE_DAYS).date() ): return sub # past subscription, user is considered not having a subscription = free plan else: return None else: return sub def verified_custom_domains(self) -> List["CustomDomain"]: return ( CustomDomain.filter_by(user_id=self.id, ownership_verified=True) .order_by(CustomDomain.domain.asc()) .all() ) def mailboxes(self) -> List["Mailbox"]: """list of mailbox that user own""" mailboxes = [] for mailbox in Mailbox.filter_by(user_id=self.id, verified=True): mailboxes.append(mailbox) return mailboxes def nb_directory(self): return Directory.filter_by(user_id=self.id).count() def has_custom_domain(self): return CustomDomain.filter_by(user_id=self.id, verified=True).count() > 0 def custom_domains(self): return CustomDomain.filter_by(user_id=self.id, verified=True).all() def available_domains_for_random_alias( self, alias_options: Optional[AliasOptions] = None ) -> List[Tuple[bool, str]]: """Return available domains for user to create random aliases Each result record contains: - whether the domain belongs to SimpleLogin - the domain """ res = [] for domain in self.available_sl_domains(alias_options=alias_options): res.append((True, domain)) for custom_domain in self.verified_custom_domains(): res.append((False, custom_domain.domain)) return res def default_random_alias_domain(self) -> str: """return the domain used for the random alias""" if self.default_alias_custom_domain_id: custom_domain = CustomDomain.get(self.default_alias_custom_domain_id) # sanity check if ( not custom_domain or not custom_domain.verified or custom_domain.user_id != self.id ): LOG.w("Problem with %s default random alias domain", self) return config.FIRST_ALIAS_DOMAIN return custom_domain.domain if self.default_alias_public_domain_id: sl_domain = SLDomain.get(self.default_alias_public_domain_id) # sanity check if not sl_domain: LOG.e("Problem with %s public random alias domain", self) return config.FIRST_ALIAS_DOMAIN if sl_domain.premium_only and not self.is_premium(): LOG.w( "%s is not premium and cannot use %s. Reset default random alias domain setting", self, sl_domain, ) self.default_alias_custom_domain_id = None self.default_alias_public_domain_id = None Session.commit() return config.FIRST_ALIAS_DOMAIN return sl_domain.domain return config.FIRST_ALIAS_DOMAIN def fido_enabled(self) -> bool: if self.fido_uuid is not None: return True return False def two_factor_authentication_enabled(self) -> bool: return self.enable_otp or self.fido_enabled() def get_communication_email(self) -> (Optional[str], str, bool): """ Return - the email that user uses to receive email communication. None if user unsubscribes from newsletter - the unsubscribe URL - whether the unsubscribe method is via sending email (mailto:) or Http POST """ if self.notification and self.activated and not self.disabled: if self.newsletter_alias_id: alias = Alias.get(self.newsletter_alias_id) if alias.enabled: unsub = UnsubscribeEncoder.encode( UnsubscribeAction.DisableAlias, alias.id ) return alias.email, unsub.link, unsub.via_email # alias disabled -> user doesn't want to receive newsletter else: return None, "", False else: # do not handle http POST unsubscribe if config.UNSUBSCRIBER: # use * as suffix instead of = as for alias unsubscribe return ( self.email, UnsubscribeEncoder.encode_mailto( UnsubscribeAction.UnsubscribeNewsletter, self.id ), True, ) return None, "", False def available_sl_domains( self, alias_options: Optional[AliasOptions] = None ) -> [str]: """ Return all SimpleLogin domains that user can use when creating a new alias, including: - SimpleLogin public domains, available for all users (ALIAS_DOMAIN) - SimpleLogin premium domains, only available for Premium accounts (PREMIUM_ALIAS_DOMAIN) """ return [ sl_domain.domain for sl_domain in self.get_sl_domains(alias_options=alias_options) ] def get_sl_domains( self, alias_options: Optional[AliasOptions] = None ) -> list["SLDomain"]: if alias_options is None: alias_options = AliasOptions() top_conds = [SLDomain.hidden == False] # noqa: E712 or_conds = [] # noqa:E711 if self.default_alias_public_domain_id is not None: default_domain_conds = [SLDomain.id == self.default_alias_public_domain_id] if not self.is_premium(): default_domain_conds.append( SLDomain.premium_only == False # noqa: E712 ) or_conds.append(and_(*default_domain_conds).self_group()) if alias_options.show_partner_domains is not None: partner_user = PartnerUser.filter_by( user_id=self.id, partner_id=alias_options.show_partner_domains.id ).first() if partner_user is not None: partner_domain_cond = [SLDomain.partner_id == partner_user.partner_id] if alias_options.show_partner_premium is None: alias_options.show_partner_premium = self.is_premium() if not alias_options.show_partner_premium: partner_domain_cond.append( SLDomain.premium_only == False # noqa: E712 ) or_conds.append(and_(*partner_domain_cond).self_group()) if alias_options.show_sl_domains: sl_conds = [SLDomain.partner_id == None] # noqa: E711 if not self.is_premium(): sl_conds.append(SLDomain.premium_only == False) # noqa: E712 or_conds.append(and_(*sl_conds).self_group()) top_conds.append(or_(*or_conds)) query = Session.query(SLDomain).filter(*top_conds).order_by(SLDomain.order) return query.all() def available_alias_domains( self, alias_options: Optional[AliasOptions] = None ) -> [str]: """return all domains that user can use when creating a new alias, including: - SimpleLogin public domains, available for all users (ALIAS_DOMAIN) - SimpleLogin premium domains, only available for Premium accounts (PREMIUM_ALIAS_DOMAIN) - Verified custom domains """ domains = self.available_sl_domains(alias_options=alias_options) for custom_domain in self.verified_custom_domains(): domains.append(custom_domain.domain) # can have duplicate where a "root" user has a domain that's also listed in SL domains return list(set(domains)) def should_show_app_page(self) -> bool: """whether to show the app page""" return ( # when user has used the "Sign in with SL" button before ClientUser.filter(ClientUser.user_id == self.id).count() # or when user has created an app + Client.filter(Client.user_id == self.id).count() > 0 ) def get_random_alias_suffix(self, custom_domain: Optional["CustomDomain"] = None): """Get random suffix for an alias based on user's preference. Use a shorter suffix in case of custom domain Returns: str: the random suffix generated """ if self.random_alias_suffix == AliasSuffixEnum.random_string.value: return random_string(config.ALIAS_RANDOM_SUFFIX_LENGTH, include_digits=True) if custom_domain is None: return random_words(1, 3) return random_words(1) def can_create_contacts(self) -> bool: if self.is_premium(): return True if self.flags & User.FLAG_FREE_DISABLE_CREATE_ALIAS == 0: return True return not config.DISABLE_CREATE_CONTACTS_FOR_FREE_USERS def __repr__(self): return f"<User {self.id} {self.name} {self.email}>" class AccountActivation(Base, ModelMixin): """contains code to activate the user account when they sign up on mobile""" __tablename__ = "account_activation" user_id = sa.Column( sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, unique=True ) # the activation code is usually 6 digits code = sa.Column(sa.String(10), nullable=False) # nb tries decrements each time user enters wrong code tries = sa.Column(sa.Integer, default=3, nullable=False) __table_args__ = ( CheckConstraint(tries >= 0, name="account_activation_tries_positive"), {}, ) 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", "") The provided code snippet includes necessary dependencies for implementing the `auth_activate` function. Write a Python function `def auth_activate()` to solve the following problem: User enters the activation code to confirm their account. Input: email code Output: 200: user account is now activated, user can login now 400: wrong email, code 410: wrong code too many times Here is the function: def auth_activate(): """ User enters the activation code to confirm their account. Input: email code Output: 200: user account is now activated, user can login now 400: wrong email, code 410: wrong code too many times """ data = request.get_json() if not data: return jsonify(error="request body cannot be empty"), 400 email = sanitize_email(data.get("email")) canonical_email = canonicalize_email(data.get("email")) code = data.get("code") user = User.get_by(email=email) or User.get_by(email=canonical_email) # do not use a different message to avoid exposing existing email if not user or user.activated: return jsonify(error="Wrong email or code"), 400 account_activation = AccountActivation.get_by(user_id=user.id) if not account_activation: return jsonify(error="Wrong email or code"), 400 if account_activation.code != code: # decrement nb tries account_activation.tries -= 1 Session.commit() if account_activation.tries == 0: AccountActivation.delete(account_activation.id) Session.commit() return jsonify(error="Too many wrong tries"), 410 return jsonify(error="Wrong email or code"), 400 LOG.d("activate user %s", user) user.activated = True AccountActivation.delete(account_activation.id) Session.commit() return jsonify(msg="Account is activated, user can login now"), 200
User enters the activation code to confirm their account. Input: email code Output: 200: user account is now activated, user can login now 400: wrong email, code 410: wrong code too many times
180,622
import secrets import string import facebook import google.oauth2.credentials import googleapiclient.discovery from flask import jsonify, request from flask_login import login_user from itsdangerous import Signer from app import email_utils from app.api.base import api_bp from app.config import FLASK_SECRET, DISABLE_REGISTRATION from app.dashboard.views.account_setting import send_reset_password_email from app.db import Session from app.email_utils import ( email_can_be_used_as_mailbox, personal_email_already_used, send_email, render, ) from app.events.auth_event import LoginEvent, RegisterEvent from app.extensions import limiter from app.log import LOG from app.models import User, ApiKey, SocialAuth, AccountActivation from app.utils import sanitize_email, canonicalize_email 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, ) 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 AccountActivation(Base, ModelMixin): """contains code to activate the user account when they sign up on mobile""" __tablename__ = "account_activation" user_id = sa.Column( sa.ForeignKey(User.id, ondelete="cascade"), nullable=False, unique=True ) # the activation code is usually 6 digits code = sa.Column(sa.String(10), nullable=False) # nb tries decrements each time user enters wrong code tries = sa.Column(sa.Integer, default=3, nullable=False) __table_args__ = ( CheckConstraint(tries >= 0, name="account_activation_tries_positive"), {}, ) 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", "") The provided code snippet includes necessary dependencies for implementing the `auth_reactivate` function. Write a Python function `def auth_reactivate()` to solve the following problem: User asks for another activation code Input: email Output: 200: user is going to receive an email for activate their account Here is the function: def auth_reactivate(): """ User asks for another activation code Input: email Output: 200: user is going to receive an email for activate their account """ data = request.get_json() if not data: return jsonify(error="request body cannot be empty"), 400 email = sanitize_email(data.get("email")) canonical_email = canonicalize_email(data.get("email")) user = User.get_by(email=email) or User.get_by(email=canonical_email) # do not use a different message to avoid exposing existing email if not user or user.activated: return jsonify(error="Something went wrong"), 400 account_activation = AccountActivation.get_by(user_id=user.id) if account_activation: AccountActivation.delete(account_activation.id) Session.commit() # create activation code code = "".join([str(secrets.choice(string.digits)) for _ in range(6)]) AccountActivation.create(user_id=user.id, code=code) Session.commit() send_email( email, "Just one more step to join SimpleLogin", render("transactional/code-activation.txt.jinja2", code=code), render("transactional/code-activation.html", code=code), ) return jsonify(msg="User needs to confirm their account"), 200
User asks for another activation code Input: email Output: 200: user is going to receive an email for activate their account
180,623
import secrets import string import facebook import google.oauth2.credentials import googleapiclient.discovery from flask import jsonify, request from flask_login import login_user from itsdangerous import Signer from app import email_utils from app.api.base import api_bp from app.config import FLASK_SECRET, DISABLE_REGISTRATION from app.dashboard.views.account_setting import send_reset_password_email from app.db import Session from app.email_utils import ( email_can_be_used_as_mailbox, personal_email_already_used, send_email, render, ) from app.events.auth_event import LoginEvent, RegisterEvent from app.extensions import limiter from app.log import LOG from app.models import User, ApiKey, SocialAuth, AccountActivation from app.utils import sanitize_email, canonicalize_email def auth_payload(user, device) -> dict: ret = {"name": user.name or "", "email": user.email, "mfa_enabled": user.enable_otp} # do not give api_key, user can only obtain api_key after OTP verification if user.enable_otp: s = Signer(FLASK_SECRET) ret["mfa_key"] = s.sign(str(user.id)) ret["api_key"] = None else: api_key = ApiKey.get_by(user_id=user.id, name=device) if not api_key: LOG.d("create new api key for %s and %s", user, device) api_key = ApiKey.create(user.id, device) Session.commit() ret["mfa_key"] = None ret["api_key"] = api_key.code # so user is automatically logged in on the web login_user(user) return ret 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 DISABLE_REGISTRATION = "DISABLE_REGISTRATION" in os.environ Session = scoped_session(sessionmaker(bind=connection)) Session: sqlalchemy.orm.Session LOG = _get_logger("SL") class User(Base, ModelMixin, UserMixin, PasswordOracle): __tablename__ = "users" FLAG_FREE_DISABLE_CREATE_ALIAS = 1 << 0 FLAG_CREATED_FROM_PARTNER = 1 << 1 FLAG_FREE_OLD_ALIAS_LIMIT = 1 << 2 email = sa.Column(sa.String(256), unique=True, nullable=False) name = sa.Column(sa.String(128), nullable=True) is_admin = sa.Column(sa.Boolean, nullable=False, default=False) alias_generator = sa.Column( sa.Integer, nullable=False, default=AliasGeneratorEnum.word.value, server_default=str(AliasGeneratorEnum.word.value), ) notification = sa.Column( sa.Boolean, default=True, nullable=False, server_default="1" ) activated = sa.Column(sa.Boolean, default=False, nullable=False, index=True) # an account can be disabled if having harmful behavior disabled = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0") profile_picture_id = sa.Column(sa.ForeignKey(File.id), nullable=True) otp_secret = sa.Column(sa.String(16), nullable=True) enable_otp = sa.Column( sa.Boolean, nullable=False, default=False, server_default="0" ) last_otp = sa.Column(sa.String(12), nullable=True, default=False) # Fields for WebAuthn fido_uuid = sa.Column(sa.String(), nullable=True, unique=True) # the default domain that's used when user creates a new random alias # default_alias_custom_domain_id XOR default_alias_public_domain_id default_alias_custom_domain_id = sa.Column( sa.ForeignKey("custom_domain.id", ondelete="SET NULL"), nullable=True, default=None, ) default_alias_public_domain_id = sa.Column( sa.ForeignKey("public_domain.id", ondelete="SET NULL"), nullable=True, default=None, ) # some users could have lifetime premium lifetime = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0") paid_lifetime = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) lifetime_coupon_id = sa.Column( sa.ForeignKey("lifetime_coupon.id", ondelete="SET NULL"), nullable=True, default=None, ) # user can use all premium features until this date trial_end = sa.Column( ArrowType, default=lambda: arrow.now().shift(days=7, hours=1), nullable=True ) # the mailbox used when create random alias # this field is nullable but in practice, it's always set # it cannot be set to non-nullable though # as this will create foreign key cycle between User and Mailbox default_mailbox_id = sa.Column( sa.ForeignKey("mailbox.id"), nullable=True, default=None ) profile_picture = orm.relationship(File, foreign_keys=[profile_picture_id]) # Specify the format for sender address # for the full list, see SenderFormatEnum sender_format = sa.Column( sa.Integer, default="0", nullable=False, server_default="0" ) # to know whether user has explicitly chosen a sender format as opposed to those who use the default ones. # users who haven't chosen a sender format and are using 1 or 3 format, their sender format will be set to 0 sender_format_updated_at = sa.Column(ArrowType, default=None) replace_reverse_alias = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) referral_id = sa.Column( sa.ForeignKey("referral.id", ondelete="SET NULL"), nullable=True, default=None, index=True, ) referral = orm.relationship("Referral", foreign_keys=[referral_id]) # whether intro has been shown to user intro_shown = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) default_mailbox = orm.relationship("Mailbox", foreign_keys=[default_mailbox_id]) # user can set a more strict max_spam score to block spams more aggressively max_spam_score = sa.Column(sa.Integer, nullable=True) # newsletter is sent to this address newsletter_alias_id = sa.Column( sa.ForeignKey("alias.id", ondelete="SET NULL"), nullable=True, default=None, index=True, ) # whether to include the sender address in reverse-alias include_sender_in_reverse_alias = sa.Column( sa.Boolean, default=True, nullable=False, server_default="0" ) # whether to use random string or random word as suffix # Random word from dictionary file -> 0 # Completely random string -> 1 random_alias_suffix = sa.Column( sa.Integer, nullable=False, default=AliasSuffixEnum.word.value, server_default=str(AliasSuffixEnum.random_string.value), ) # always expand the alias info, i.e. without needing to press "More" expand_alias_info = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # ignore emails send from a mailbox to its alias. This can happen when replying all to a forwarded email # can automatically re-includes the alias ignore_loop_email = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # used for flask-login as an "alternative token" # cf https://flask-login.readthedocs.io/en/latest/#alternative-tokens alternative_id = sa.Column(sa.String(128), unique=True, nullable=True) # by default, when an alias is automatically created, a note like "Created with ...." is created # If this field is True, the note won't be created. disable_automatic_alias_note = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # By default, the one-click unsubscribe disable the alias # If set to true, it will block the sender instead one_click_unsubscribe_block_sender = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # automatically include the website name when user creates an alias via the SimpleLogin icon in the email field include_website_in_one_click_alias = sa.Column( sa.Boolean, # new user will have this option turned on automatically default=True, nullable=False, # old user will have this option turned off server_default="0", ) _directory_quota = sa.Column( "directory_quota", sa.Integer, default=50, nullable=False, server_default="50" ) _subdomain_quota = sa.Column( "subdomain_quota", sa.Integer, default=5, nullable=False, server_default="5" ) # user can use import to import too many aliases disable_import = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # user can use the phone feature can_use_phone = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # in minutes phone_quota = sa.Column(sa.Integer, nullable=True) # Status code to return if is blocked block_behaviour = sa.Column( sa.Enum(BlockBehaviourEnum), nullable=False, server_default=BlockBehaviourEnum.return_2xx.name, ) include_header_email_header = sa.Column( sa.Boolean, default=True, nullable=False, server_default="1" ) # bitwise flags. Allow for future expansion flags = sa.Column( sa.BigInteger, default=FLAG_FREE_DISABLE_CREATE_ALIAS, server_default="0", nullable=False, ) # Keep original unsub behaviour unsub_behaviour = sa.Column( IntEnumType(UnsubscribeBehaviourEnum), default=UnsubscribeBehaviourEnum.PreserveOriginal, server_default=str(UnsubscribeBehaviourEnum.DisableAlias.value), nullable=False, ) # Trigger hard deletion of the account at this time delete_on = sa.Column(ArrowType, default=None) __table_args__ = ( sa.Index( "ix_users_activated_trial_end_lifetime", activated, trial_end, lifetime ), sa.Index("ix_users_delete_on", delete_on), ) def directory_quota(self): return min( self._directory_quota, config.MAX_NB_DIRECTORY - Directory.filter_by(user_id=self.id).count(), ) def subdomain_quota(self): return min( self._subdomain_quota, config.MAX_NB_SUBDOMAIN - CustomDomain.filter_by(user_id=self.id, is_sl_subdomain=True).count(), ) def created_by_partner(self): return User.FLAG_CREATED_FROM_PARTNER == ( self.flags & User.FLAG_CREATED_FROM_PARTNER ) def subdomain_is_available(): return SLDomain.filter_by(can_use_subdomain=True).count() > 0 # implement flask-login "alternative token" def get_id(self): if self.alternative_id: return self.alternative_id else: return str(self.id) def create(cls, email, name="", password=None, from_partner=False, **kwargs): email = sanitize_email(email) user: User = super(User, cls).create(email=email, name=name[:100], **kwargs) if password: user.set_password(password) Session.flush() mb = Mailbox.create(user_id=user.id, email=user.email, verified=True) Session.flush() user.default_mailbox_id = mb.id # generate an alternative_id if needed if "alternative_id" not in kwargs: user.alternative_id = str(uuid.uuid4()) # If the user is created from partner, do not notify # nor give a trial if from_partner: user.flags = User.FLAG_CREATED_FROM_PARTNER user.notification = False user.trial_end = None Job.create( name=config.JOB_SEND_PROTON_WELCOME_1, payload={"user_id": user.id}, run_at=arrow.now(), ) Session.flush() return user # create a first alias mail to show user how to use when they login alias = Alias.create_new( user, prefix="simplelogin-newsletter", mailbox_id=mb.id, note="This is your first alias. It's used to receive SimpleLogin communications " "like new features announcements, newsletters.", ) Session.flush() user.newsletter_alias_id = alias.id Session.flush() if config.DISABLE_ONBOARDING: LOG.d("Disable onboarding emails") return user # Schedule onboarding emails Job.create( name=config.JOB_ONBOARDING_1, payload={"user_id": user.id}, run_at=arrow.now().shift(days=1), ) Job.create( name=config.JOB_ONBOARDING_2, payload={"user_id": user.id}, run_at=arrow.now().shift(days=2), ) Job.create( name=config.JOB_ONBOARDING_4, payload={"user_id": user.id}, run_at=arrow.now().shift(days=3), ) Session.flush() return user def get_active_subscription( self, include_partner_subscription: bool = True ) -> Optional[ Union[ Subscription | AppleSubscription | ManualSubscription | CoinbaseSubscription | PartnerSubscription ] ]: sub: Subscription = self.get_paddle_subscription() if sub: return sub apple_sub: AppleSubscription = AppleSubscription.get_by(user_id=self.id) if apple_sub and apple_sub.is_valid(): return apple_sub manual_sub: ManualSubscription = ManualSubscription.get_by(user_id=self.id) if manual_sub and manual_sub.is_active(): return manual_sub coinbase_subscription: CoinbaseSubscription = CoinbaseSubscription.get_by( user_id=self.id ) if coinbase_subscription and coinbase_subscription.is_active(): return coinbase_subscription if include_partner_subscription: partner_sub: PartnerSubscription = PartnerSubscription.find_by_user_id( self.id ) if partner_sub and partner_sub.is_active(): return partner_sub return None def get_active_subscription_end( self, include_partner_subscription: bool = True ) -> Optional[arrow.Arrow]: sub = self.get_active_subscription( include_partner_subscription=include_partner_subscription ) if isinstance(sub, Subscription): return arrow.get(sub.next_bill_date) if isinstance(sub, AppleSubscription): return sub.expires_date if isinstance(sub, ManualSubscription): return sub.end_at if isinstance(sub, CoinbaseSubscription): return sub.end_at return None # region Billing def lifetime_or_active_subscription( self, include_partner_subscription: bool = True ) -> bool: """True if user has lifetime licence or active subscription""" if self.lifetime: return True return self.get_active_subscription(include_partner_subscription) is not None def is_paid(self) -> bool: """same as _lifetime_or_active_subscription but not include free manual subscription""" sub = self.get_active_subscription() if sub is None: return False if isinstance(sub, ManualSubscription) and sub.is_giveaway: return False return True def is_active(self) -> bool: if self.delete_on is None: return True return self.delete_on < arrow.now() def in_trial(self): """return True if user does not have lifetime licence or an active subscription AND is in trial period""" if self.lifetime_or_active_subscription(): return False if self.trial_end and arrow.now() < self.trial_end: return True return False def should_show_upgrade_button(self): if self.lifetime_or_active_subscription(): return False return True def is_premium(self, include_partner_subscription: bool = True) -> bool: """ user is premium if they: - have a lifetime deal or - in trial period or - active subscription """ if self.lifetime_or_active_subscription(include_partner_subscription): return True if self.trial_end and arrow.now() < self.trial_end: return True return False def upgrade_channel(self) -> str: """Used on admin dashboard""" # user can have multiple subscription channel channels = [] if self.lifetime: channels.append("Lifetime") sub: Subscription = self.get_paddle_subscription() if sub: if sub.cancelled: channels.append( f"""Cancelled Paddle Subscription <a href="https://vendors.paddle.com/subscriptions/customers/manage/{sub.subscription_id}">{sub.subscription_id}</a> {sub.plan_name()} ends at {sub.next_bill_date}""" ) else: channels.append( f"""Active Paddle Subscription <a href="https://vendors.paddle.com/subscriptions/customers/manage/{sub.subscription_id}">{sub.subscription_id}</a> {sub.plan_name()}, renews at {sub.next_bill_date}""" ) apple_sub: AppleSubscription = AppleSubscription.get_by(user_id=self.id) if apple_sub and apple_sub.is_valid(): channels.append(f"Apple Subscription {apple_sub.expires_date.humanize()}") manual_sub: ManualSubscription = ManualSubscription.get_by(user_id=self.id) if manual_sub and manual_sub.is_active(): mode = "Giveaway" if manual_sub.is_giveaway else "Paid" channels.append( f"Manual Subscription {manual_sub.comment} {mode} {manual_sub.end_at.humanize()}" ) coinbase_subscription: CoinbaseSubscription = CoinbaseSubscription.get_by( user_id=self.id ) if coinbase_subscription and coinbase_subscription.is_active(): channels.append( f"Coinbase Subscription ends {coinbase_subscription.end_at.humanize()}" ) r = ( Session.query(PartnerSubscription, PartnerUser, Partner) .filter( PartnerSubscription.partner_user_id == PartnerUser.id, PartnerUser.user_id == self.id, Partner.id == PartnerUser.partner_id, ) .first() ) if r and r[0].is_active(): channels.append( f"Subscription via {r[2].name} partner , ends {r[0].end_at.humanize()}" ) return ".\n".join(channels) # endregion def max_alias_for_free_account(self) -> int: if ( self.FLAG_FREE_OLD_ALIAS_LIMIT == self.flags & self.FLAG_FREE_OLD_ALIAS_LIMIT ): return config.MAX_NB_EMAIL_OLD_FREE_PLAN else: return config.MAX_NB_EMAIL_FREE_PLAN def can_create_new_alias(self) -> bool: """ Whether user can create a new alias. User can't create a new alias if - has more than 15 aliases in the free plan, *even in the free trial* """ if not self.is_active(): return False if self.disabled: return False if self.lifetime_or_active_subscription(): return True else: return ( Alias.filter_by(user_id=self.id).count() < self.max_alias_for_free_account() ) def can_send_or_receive(self) -> bool: if self.disabled: LOG.i(f"User {self} is disabled. Cannot receive or send emails") return False if self.delete_on is not None: LOG.i( f"User {self} is scheduled to be deleted. Cannot receive or send emails" ) return False return True def profile_picture_url(self): if self.profile_picture_id: return self.profile_picture.get_url() else: return url_for("static", filename="default-avatar.png") def suggested_emails(self, website_name) -> (str, [str]): """return suggested email and other email choices""" website_name = convert_to_id(website_name) all_aliases = [ ge.email for ge in Alias.filter_by(user_id=self.id, enabled=True) ] if self.can_create_new_alias(): suggested_alias = Alias.create_new(self, prefix=website_name).email else: # pick an email from the list of gen emails suggested_alias = random.choice(all_aliases) return ( suggested_alias, list(set(all_aliases).difference({suggested_alias})), ) def suggested_names(self) -> (str, [str]): """return suggested name and other name choices""" other_name = convert_to_id(self.name) return self.name, [other_name, "Anonymous", "whoami"] def get_name_initial(self) -> str: if not self.name: return "" names = self.name.split(" ") return "".join([n[0].upper() for n in names if n]) def get_paddle_subscription(self) -> Optional["Subscription"]: """return *active* Paddle subscription Return None if the subscription is already expired TODO: support user unsubscribe and re-subscribe """ sub = Subscription.get_by(user_id=self.id) if sub: # grace period is 14 days # sub is active until the next billing_date + PADDLE_SUBSCRIPTION_GRACE_DAYS if ( sub.next_bill_date >= arrow.now().shift(days=-PADDLE_SUBSCRIPTION_GRACE_DAYS).date() ): return sub # past subscription, user is considered not having a subscription = free plan else: return None else: return sub def verified_custom_domains(self) -> List["CustomDomain"]: return ( CustomDomain.filter_by(user_id=self.id, ownership_verified=True) .order_by(CustomDomain.domain.asc()) .all() ) def mailboxes(self) -> List["Mailbox"]: """list of mailbox that user own""" mailboxes = [] for mailbox in Mailbox.filter_by(user_id=self.id, verified=True): mailboxes.append(mailbox) return mailboxes def nb_directory(self): return Directory.filter_by(user_id=self.id).count() def has_custom_domain(self): return CustomDomain.filter_by(user_id=self.id, verified=True).count() > 0 def custom_domains(self): return CustomDomain.filter_by(user_id=self.id, verified=True).all() def available_domains_for_random_alias( self, alias_options: Optional[AliasOptions] = None ) -> List[Tuple[bool, str]]: """Return available domains for user to create random aliases Each result record contains: - whether the domain belongs to SimpleLogin - the domain """ res = [] for domain in self.available_sl_domains(alias_options=alias_options): res.append((True, domain)) for custom_domain in self.verified_custom_domains(): res.append((False, custom_domain.domain)) return res def default_random_alias_domain(self) -> str: """return the domain used for the random alias""" if self.default_alias_custom_domain_id: custom_domain = CustomDomain.get(self.default_alias_custom_domain_id) # sanity check if ( not custom_domain or not custom_domain.verified or custom_domain.user_id != self.id ): LOG.w("Problem with %s default random alias domain", self) return config.FIRST_ALIAS_DOMAIN return custom_domain.domain if self.default_alias_public_domain_id: sl_domain = SLDomain.get(self.default_alias_public_domain_id) # sanity check if not sl_domain: LOG.e("Problem with %s public random alias domain", self) return config.FIRST_ALIAS_DOMAIN if sl_domain.premium_only and not self.is_premium(): LOG.w( "%s is not premium and cannot use %s. Reset default random alias domain setting", self, sl_domain, ) self.default_alias_custom_domain_id = None self.default_alias_public_domain_id = None Session.commit() return config.FIRST_ALIAS_DOMAIN return sl_domain.domain return config.FIRST_ALIAS_DOMAIN def fido_enabled(self) -> bool: if self.fido_uuid is not None: return True return False def two_factor_authentication_enabled(self) -> bool: return self.enable_otp or self.fido_enabled() def get_communication_email(self) -> (Optional[str], str, bool): """ Return - the email that user uses to receive email communication. None if user unsubscribes from newsletter - the unsubscribe URL - whether the unsubscribe method is via sending email (mailto:) or Http POST """ if self.notification and self.activated and not self.disabled: if self.newsletter_alias_id: alias = Alias.get(self.newsletter_alias_id) if alias.enabled: unsub = UnsubscribeEncoder.encode( UnsubscribeAction.DisableAlias, alias.id ) return alias.email, unsub.link, unsub.via_email # alias disabled -> user doesn't want to receive newsletter else: return None, "", False else: # do not handle http POST unsubscribe if config.UNSUBSCRIBER: # use * as suffix instead of = as for alias unsubscribe return ( self.email, UnsubscribeEncoder.encode_mailto( UnsubscribeAction.UnsubscribeNewsletter, self.id ), True, ) return None, "", False def available_sl_domains( self, alias_options: Optional[AliasOptions] = None ) -> [str]: """ Return all SimpleLogin domains that user can use when creating a new alias, including: - SimpleLogin public domains, available for all users (ALIAS_DOMAIN) - SimpleLogin premium domains, only available for Premium accounts (PREMIUM_ALIAS_DOMAIN) """ return [ sl_domain.domain for sl_domain in self.get_sl_domains(alias_options=alias_options) ] def get_sl_domains( self, alias_options: Optional[AliasOptions] = None ) -> list["SLDomain"]: if alias_options is None: alias_options = AliasOptions() top_conds = [SLDomain.hidden == False] # noqa: E712 or_conds = [] # noqa:E711 if self.default_alias_public_domain_id is not None: default_domain_conds = [SLDomain.id == self.default_alias_public_domain_id] if not self.is_premium(): default_domain_conds.append( SLDomain.premium_only == False # noqa: E712 ) or_conds.append(and_(*default_domain_conds).self_group()) if alias_options.show_partner_domains is not None: partner_user = PartnerUser.filter_by( user_id=self.id, partner_id=alias_options.show_partner_domains.id ).first() if partner_user is not None: partner_domain_cond = [SLDomain.partner_id == partner_user.partner_id] if alias_options.show_partner_premium is None: alias_options.show_partner_premium = self.is_premium() if not alias_options.show_partner_premium: partner_domain_cond.append( SLDomain.premium_only == False # noqa: E712 ) or_conds.append(and_(*partner_domain_cond).self_group()) if alias_options.show_sl_domains: sl_conds = [SLDomain.partner_id == None] # noqa: E711 if not self.is_premium(): sl_conds.append(SLDomain.premium_only == False) # noqa: E712 or_conds.append(and_(*sl_conds).self_group()) top_conds.append(or_(*or_conds)) query = Session.query(SLDomain).filter(*top_conds).order_by(SLDomain.order) return query.all() def available_alias_domains( self, alias_options: Optional[AliasOptions] = None ) -> [str]: """return all domains that user can use when creating a new alias, including: - SimpleLogin public domains, available for all users (ALIAS_DOMAIN) - SimpleLogin premium domains, only available for Premium accounts (PREMIUM_ALIAS_DOMAIN) - Verified custom domains """ domains = self.available_sl_domains(alias_options=alias_options) for custom_domain in self.verified_custom_domains(): domains.append(custom_domain.domain) # can have duplicate where a "root" user has a domain that's also listed in SL domains return list(set(domains)) def should_show_app_page(self) -> bool: """whether to show the app page""" return ( # when user has used the "Sign in with SL" button before ClientUser.filter(ClientUser.user_id == self.id).count() # or when user has created an app + Client.filter(Client.user_id == self.id).count() > 0 ) def get_random_alias_suffix(self, custom_domain: Optional["CustomDomain"] = None): """Get random suffix for an alias based on user's preference. Use a shorter suffix in case of custom domain Returns: str: the random suffix generated """ if self.random_alias_suffix == AliasSuffixEnum.random_string.value: return random_string(config.ALIAS_RANDOM_SUFFIX_LENGTH, include_digits=True) if custom_domain is None: return random_words(1, 3) return random_words(1) def can_create_contacts(self) -> bool: if self.is_premium(): return True if self.flags & User.FLAG_FREE_DISABLE_CREATE_ALIAS == 0: return True return not config.DISABLE_CREATE_CONTACTS_FOR_FREE_USERS def __repr__(self): return f"<User {self.id} {self.name} {self.email}>" class 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"),) def sanitize_email(email_address: str, not_lower=False) -> str: if email_address: email_address = email_address.strip().replace(" ", "").replace("\n", " ") if not not_lower: email_address = email_address.lower() return email_address.replace("\u200f", "") The provided code snippet includes necessary dependencies for implementing the `auth_facebook` function. Write a Python function `def auth_facebook()` to solve the following problem: Authenticate user with Facebook Input: facebook_token: facebook access token device: to create an ApiKey associated with this device Output: 200 and user info containing: { name: "John Wick", mfa_enabled: true, mfa_key: "a long string", api_key: "a long string" } Here is the function: def auth_facebook(): """ Authenticate user with Facebook Input: facebook_token: facebook access token device: to create an ApiKey associated with this device Output: 200 and user info containing: { name: "John Wick", mfa_enabled: true, mfa_key: "a long string", api_key: "a long string" } """ data = request.get_json() if not data: return jsonify(error="request body cannot be empty"), 400 facebook_token = data.get("facebook_token") device = data.get("device") graph = facebook.GraphAPI(access_token=facebook_token) user_info = graph.get_object("me", fields="email,name") email = sanitize_email(user_info.get("email")) user = User.get_by(email=email) if not user: if DISABLE_REGISTRATION: return jsonify(error="registration is closed"), 400 if not email_can_be_used_as_mailbox(email) or personal_email_already_used( email ): return jsonify(error=f"cannot use {email} as personal inbox"), 400 LOG.d("create facebook user with %s", user_info) user = User.create(email=email, name=user_info["name"], activated=True) Session.commit() email_utils.send_welcome_email(user) if not SocialAuth.get_by(user_id=user.id, social="facebook"): SocialAuth.create(user_id=user.id, social="facebook") Session.commit() return jsonify(**auth_payload(user, device)), 200
Authenticate user with Facebook Input: facebook_token: facebook access token device: to create an ApiKey associated with this device Output: 200 and user info containing: { name: "John Wick", mfa_enabled: true, mfa_key: "a long string", api_key: "a long string" }
180,624
import secrets import string import facebook import google.oauth2.credentials import googleapiclient.discovery from flask import jsonify, request from flask_login import login_user from itsdangerous import Signer from app import email_utils from app.api.base import api_bp from app.config import FLASK_SECRET, DISABLE_REGISTRATION from app.dashboard.views.account_setting import send_reset_password_email from app.db import Session from app.email_utils import ( email_can_be_used_as_mailbox, personal_email_already_used, send_email, render, ) from app.events.auth_event import LoginEvent, RegisterEvent from app.extensions import limiter from app.log import LOG from app.models import User, ApiKey, SocialAuth, AccountActivation from app.utils import sanitize_email, canonicalize_email def auth_payload(user, device) -> dict: ret = {"name": user.name or "", "email": user.email, "mfa_enabled": user.enable_otp} # do not give api_key, user can only obtain api_key after OTP verification if user.enable_otp: s = Signer(FLASK_SECRET) ret["mfa_key"] = s.sign(str(user.id)) ret["api_key"] = None else: api_key = ApiKey.get_by(user_id=user.id, name=device) if not api_key: LOG.d("create new api key for %s and %s", user, device) api_key = ApiKey.create(user.id, device) Session.commit() ret["mfa_key"] = None ret["api_key"] = api_key.code # so user is automatically logged in on the web login_user(user) return ret 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 DISABLE_REGISTRATION = "DISABLE_REGISTRATION" in os.environ Session = scoped_session(sessionmaker(bind=connection)) Session: sqlalchemy.orm.Session LOG = _get_logger("SL") class User(Base, ModelMixin, UserMixin, PasswordOracle): __tablename__ = "users" FLAG_FREE_DISABLE_CREATE_ALIAS = 1 << 0 FLAG_CREATED_FROM_PARTNER = 1 << 1 FLAG_FREE_OLD_ALIAS_LIMIT = 1 << 2 email = sa.Column(sa.String(256), unique=True, nullable=False) name = sa.Column(sa.String(128), nullable=True) is_admin = sa.Column(sa.Boolean, nullable=False, default=False) alias_generator = sa.Column( sa.Integer, nullable=False, default=AliasGeneratorEnum.word.value, server_default=str(AliasGeneratorEnum.word.value), ) notification = sa.Column( sa.Boolean, default=True, nullable=False, server_default="1" ) activated = sa.Column(sa.Boolean, default=False, nullable=False, index=True) # an account can be disabled if having harmful behavior disabled = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0") profile_picture_id = sa.Column(sa.ForeignKey(File.id), nullable=True) otp_secret = sa.Column(sa.String(16), nullable=True) enable_otp = sa.Column( sa.Boolean, nullable=False, default=False, server_default="0" ) last_otp = sa.Column(sa.String(12), nullable=True, default=False) # Fields for WebAuthn fido_uuid = sa.Column(sa.String(), nullable=True, unique=True) # the default domain that's used when user creates a new random alias # default_alias_custom_domain_id XOR default_alias_public_domain_id default_alias_custom_domain_id = sa.Column( sa.ForeignKey("custom_domain.id", ondelete="SET NULL"), nullable=True, default=None, ) default_alias_public_domain_id = sa.Column( sa.ForeignKey("public_domain.id", ondelete="SET NULL"), nullable=True, default=None, ) # some users could have lifetime premium lifetime = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0") paid_lifetime = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) lifetime_coupon_id = sa.Column( sa.ForeignKey("lifetime_coupon.id", ondelete="SET NULL"), nullable=True, default=None, ) # user can use all premium features until this date trial_end = sa.Column( ArrowType, default=lambda: arrow.now().shift(days=7, hours=1), nullable=True ) # the mailbox used when create random alias # this field is nullable but in practice, it's always set # it cannot be set to non-nullable though # as this will create foreign key cycle between User and Mailbox default_mailbox_id = sa.Column( sa.ForeignKey("mailbox.id"), nullable=True, default=None ) profile_picture = orm.relationship(File, foreign_keys=[profile_picture_id]) # Specify the format for sender address # for the full list, see SenderFormatEnum sender_format = sa.Column( sa.Integer, default="0", nullable=False, server_default="0" ) # to know whether user has explicitly chosen a sender format as opposed to those who use the default ones. # users who haven't chosen a sender format and are using 1 or 3 format, their sender format will be set to 0 sender_format_updated_at = sa.Column(ArrowType, default=None) replace_reverse_alias = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) referral_id = sa.Column( sa.ForeignKey("referral.id", ondelete="SET NULL"), nullable=True, default=None, index=True, ) referral = orm.relationship("Referral", foreign_keys=[referral_id]) # whether intro has been shown to user intro_shown = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) default_mailbox = orm.relationship("Mailbox", foreign_keys=[default_mailbox_id]) # user can set a more strict max_spam score to block spams more aggressively max_spam_score = sa.Column(sa.Integer, nullable=True) # newsletter is sent to this address newsletter_alias_id = sa.Column( sa.ForeignKey("alias.id", ondelete="SET NULL"), nullable=True, default=None, index=True, ) # whether to include the sender address in reverse-alias include_sender_in_reverse_alias = sa.Column( sa.Boolean, default=True, nullable=False, server_default="0" ) # whether to use random string or random word as suffix # Random word from dictionary file -> 0 # Completely random string -> 1 random_alias_suffix = sa.Column( sa.Integer, nullable=False, default=AliasSuffixEnum.word.value, server_default=str(AliasSuffixEnum.random_string.value), ) # always expand the alias info, i.e. without needing to press "More" expand_alias_info = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # ignore emails send from a mailbox to its alias. This can happen when replying all to a forwarded email # can automatically re-includes the alias ignore_loop_email = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # used for flask-login as an "alternative token" # cf https://flask-login.readthedocs.io/en/latest/#alternative-tokens alternative_id = sa.Column(sa.String(128), unique=True, nullable=True) # by default, when an alias is automatically created, a note like "Created with ...." is created # If this field is True, the note won't be created. disable_automatic_alias_note = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # By default, the one-click unsubscribe disable the alias # If set to true, it will block the sender instead one_click_unsubscribe_block_sender = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # automatically include the website name when user creates an alias via the SimpleLogin icon in the email field include_website_in_one_click_alias = sa.Column( sa.Boolean, # new user will have this option turned on automatically default=True, nullable=False, # old user will have this option turned off server_default="0", ) _directory_quota = sa.Column( "directory_quota", sa.Integer, default=50, nullable=False, server_default="50" ) _subdomain_quota = sa.Column( "subdomain_quota", sa.Integer, default=5, nullable=False, server_default="5" ) # user can use import to import too many aliases disable_import = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # user can use the phone feature can_use_phone = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # in minutes phone_quota = sa.Column(sa.Integer, nullable=True) # Status code to return if is blocked block_behaviour = sa.Column( sa.Enum(BlockBehaviourEnum), nullable=False, server_default=BlockBehaviourEnum.return_2xx.name, ) include_header_email_header = sa.Column( sa.Boolean, default=True, nullable=False, server_default="1" ) # bitwise flags. Allow for future expansion flags = sa.Column( sa.BigInteger, default=FLAG_FREE_DISABLE_CREATE_ALIAS, server_default="0", nullable=False, ) # Keep original unsub behaviour unsub_behaviour = sa.Column( IntEnumType(UnsubscribeBehaviourEnum), default=UnsubscribeBehaviourEnum.PreserveOriginal, server_default=str(UnsubscribeBehaviourEnum.DisableAlias.value), nullable=False, ) # Trigger hard deletion of the account at this time delete_on = sa.Column(ArrowType, default=None) __table_args__ = ( sa.Index( "ix_users_activated_trial_end_lifetime", activated, trial_end, lifetime ), sa.Index("ix_users_delete_on", delete_on), ) def directory_quota(self): return min( self._directory_quota, config.MAX_NB_DIRECTORY - Directory.filter_by(user_id=self.id).count(), ) def subdomain_quota(self): return min( self._subdomain_quota, config.MAX_NB_SUBDOMAIN - CustomDomain.filter_by(user_id=self.id, is_sl_subdomain=True).count(), ) def created_by_partner(self): return User.FLAG_CREATED_FROM_PARTNER == ( self.flags & User.FLAG_CREATED_FROM_PARTNER ) def subdomain_is_available(): return SLDomain.filter_by(can_use_subdomain=True).count() > 0 # implement flask-login "alternative token" def get_id(self): if self.alternative_id: return self.alternative_id else: return str(self.id) def create(cls, email, name="", password=None, from_partner=False, **kwargs): email = sanitize_email(email) user: User = super(User, cls).create(email=email, name=name[:100], **kwargs) if password: user.set_password(password) Session.flush() mb = Mailbox.create(user_id=user.id, email=user.email, verified=True) Session.flush() user.default_mailbox_id = mb.id # generate an alternative_id if needed if "alternative_id" not in kwargs: user.alternative_id = str(uuid.uuid4()) # If the user is created from partner, do not notify # nor give a trial if from_partner: user.flags = User.FLAG_CREATED_FROM_PARTNER user.notification = False user.trial_end = None Job.create( name=config.JOB_SEND_PROTON_WELCOME_1, payload={"user_id": user.id}, run_at=arrow.now(), ) Session.flush() return user # create a first alias mail to show user how to use when they login alias = Alias.create_new( user, prefix="simplelogin-newsletter", mailbox_id=mb.id, note="This is your first alias. It's used to receive SimpleLogin communications " "like new features announcements, newsletters.", ) Session.flush() user.newsletter_alias_id = alias.id Session.flush() if config.DISABLE_ONBOARDING: LOG.d("Disable onboarding emails") return user # Schedule onboarding emails Job.create( name=config.JOB_ONBOARDING_1, payload={"user_id": user.id}, run_at=arrow.now().shift(days=1), ) Job.create( name=config.JOB_ONBOARDING_2, payload={"user_id": user.id}, run_at=arrow.now().shift(days=2), ) Job.create( name=config.JOB_ONBOARDING_4, payload={"user_id": user.id}, run_at=arrow.now().shift(days=3), ) Session.flush() return user def get_active_subscription( self, include_partner_subscription: bool = True ) -> Optional[ Union[ Subscription | AppleSubscription | ManualSubscription | CoinbaseSubscription | PartnerSubscription ] ]: sub: Subscription = self.get_paddle_subscription() if sub: return sub apple_sub: AppleSubscription = AppleSubscription.get_by(user_id=self.id) if apple_sub and apple_sub.is_valid(): return apple_sub manual_sub: ManualSubscription = ManualSubscription.get_by(user_id=self.id) if manual_sub and manual_sub.is_active(): return manual_sub coinbase_subscription: CoinbaseSubscription = CoinbaseSubscription.get_by( user_id=self.id ) if coinbase_subscription and coinbase_subscription.is_active(): return coinbase_subscription if include_partner_subscription: partner_sub: PartnerSubscription = PartnerSubscription.find_by_user_id( self.id ) if partner_sub and partner_sub.is_active(): return partner_sub return None def get_active_subscription_end( self, include_partner_subscription: bool = True ) -> Optional[arrow.Arrow]: sub = self.get_active_subscription( include_partner_subscription=include_partner_subscription ) if isinstance(sub, Subscription): return arrow.get(sub.next_bill_date) if isinstance(sub, AppleSubscription): return sub.expires_date if isinstance(sub, ManualSubscription): return sub.end_at if isinstance(sub, CoinbaseSubscription): return sub.end_at return None # region Billing def lifetime_or_active_subscription( self, include_partner_subscription: bool = True ) -> bool: """True if user has lifetime licence or active subscription""" if self.lifetime: return True return self.get_active_subscription(include_partner_subscription) is not None def is_paid(self) -> bool: """same as _lifetime_or_active_subscription but not include free manual subscription""" sub = self.get_active_subscription() if sub is None: return False if isinstance(sub, ManualSubscription) and sub.is_giveaway: return False return True def is_active(self) -> bool: if self.delete_on is None: return True return self.delete_on < arrow.now() def in_trial(self): """return True if user does not have lifetime licence or an active subscription AND is in trial period""" if self.lifetime_or_active_subscription(): return False if self.trial_end and arrow.now() < self.trial_end: return True return False def should_show_upgrade_button(self): if self.lifetime_or_active_subscription(): return False return True def is_premium(self, include_partner_subscription: bool = True) -> bool: """ user is premium if they: - have a lifetime deal or - in trial period or - active subscription """ if self.lifetime_or_active_subscription(include_partner_subscription): return True if self.trial_end and arrow.now() < self.trial_end: return True return False def upgrade_channel(self) -> str: """Used on admin dashboard""" # user can have multiple subscription channel channels = [] if self.lifetime: channels.append("Lifetime") sub: Subscription = self.get_paddle_subscription() if sub: if sub.cancelled: channels.append( f"""Cancelled Paddle Subscription <a href="https://vendors.paddle.com/subscriptions/customers/manage/{sub.subscription_id}">{sub.subscription_id}</a> {sub.plan_name()} ends at {sub.next_bill_date}""" ) else: channels.append( f"""Active Paddle Subscription <a href="https://vendors.paddle.com/subscriptions/customers/manage/{sub.subscription_id}">{sub.subscription_id}</a> {sub.plan_name()}, renews at {sub.next_bill_date}""" ) apple_sub: AppleSubscription = AppleSubscription.get_by(user_id=self.id) if apple_sub and apple_sub.is_valid(): channels.append(f"Apple Subscription {apple_sub.expires_date.humanize()}") manual_sub: ManualSubscription = ManualSubscription.get_by(user_id=self.id) if manual_sub and manual_sub.is_active(): mode = "Giveaway" if manual_sub.is_giveaway else "Paid" channels.append( f"Manual Subscription {manual_sub.comment} {mode} {manual_sub.end_at.humanize()}" ) coinbase_subscription: CoinbaseSubscription = CoinbaseSubscription.get_by( user_id=self.id ) if coinbase_subscription and coinbase_subscription.is_active(): channels.append( f"Coinbase Subscription ends {coinbase_subscription.end_at.humanize()}" ) r = ( Session.query(PartnerSubscription, PartnerUser, Partner) .filter( PartnerSubscription.partner_user_id == PartnerUser.id, PartnerUser.user_id == self.id, Partner.id == PartnerUser.partner_id, ) .first() ) if r and r[0].is_active(): channels.append( f"Subscription via {r[2].name} partner , ends {r[0].end_at.humanize()}" ) return ".\n".join(channels) # endregion def max_alias_for_free_account(self) -> int: if ( self.FLAG_FREE_OLD_ALIAS_LIMIT == self.flags & self.FLAG_FREE_OLD_ALIAS_LIMIT ): return config.MAX_NB_EMAIL_OLD_FREE_PLAN else: return config.MAX_NB_EMAIL_FREE_PLAN def can_create_new_alias(self) -> bool: """ Whether user can create a new alias. User can't create a new alias if - has more than 15 aliases in the free plan, *even in the free trial* """ if not self.is_active(): return False if self.disabled: return False if self.lifetime_or_active_subscription(): return True else: return ( Alias.filter_by(user_id=self.id).count() < self.max_alias_for_free_account() ) def can_send_or_receive(self) -> bool: if self.disabled: LOG.i(f"User {self} is disabled. Cannot receive or send emails") return False if self.delete_on is not None: LOG.i( f"User {self} is scheduled to be deleted. Cannot receive or send emails" ) return False return True def profile_picture_url(self): if self.profile_picture_id: return self.profile_picture.get_url() else: return url_for("static", filename="default-avatar.png") def suggested_emails(self, website_name) -> (str, [str]): """return suggested email and other email choices""" website_name = convert_to_id(website_name) all_aliases = [ ge.email for ge in Alias.filter_by(user_id=self.id, enabled=True) ] if self.can_create_new_alias(): suggested_alias = Alias.create_new(self, prefix=website_name).email else: # pick an email from the list of gen emails suggested_alias = random.choice(all_aliases) return ( suggested_alias, list(set(all_aliases).difference({suggested_alias})), ) def suggested_names(self) -> (str, [str]): """return suggested name and other name choices""" other_name = convert_to_id(self.name) return self.name, [other_name, "Anonymous", "whoami"] def get_name_initial(self) -> str: if not self.name: return "" names = self.name.split(" ") return "".join([n[0].upper() for n in names if n]) def get_paddle_subscription(self) -> Optional["Subscription"]: """return *active* Paddle subscription Return None if the subscription is already expired TODO: support user unsubscribe and re-subscribe """ sub = Subscription.get_by(user_id=self.id) if sub: # grace period is 14 days # sub is active until the next billing_date + PADDLE_SUBSCRIPTION_GRACE_DAYS if ( sub.next_bill_date >= arrow.now().shift(days=-PADDLE_SUBSCRIPTION_GRACE_DAYS).date() ): return sub # past subscription, user is considered not having a subscription = free plan else: return None else: return sub def verified_custom_domains(self) -> List["CustomDomain"]: return ( CustomDomain.filter_by(user_id=self.id, ownership_verified=True) .order_by(CustomDomain.domain.asc()) .all() ) def mailboxes(self) -> List["Mailbox"]: """list of mailbox that user own""" mailboxes = [] for mailbox in Mailbox.filter_by(user_id=self.id, verified=True): mailboxes.append(mailbox) return mailboxes def nb_directory(self): return Directory.filter_by(user_id=self.id).count() def has_custom_domain(self): return CustomDomain.filter_by(user_id=self.id, verified=True).count() > 0 def custom_domains(self): return CustomDomain.filter_by(user_id=self.id, verified=True).all() def available_domains_for_random_alias( self, alias_options: Optional[AliasOptions] = None ) -> List[Tuple[bool, str]]: """Return available domains for user to create random aliases Each result record contains: - whether the domain belongs to SimpleLogin - the domain """ res = [] for domain in self.available_sl_domains(alias_options=alias_options): res.append((True, domain)) for custom_domain in self.verified_custom_domains(): res.append((False, custom_domain.domain)) return res def default_random_alias_domain(self) -> str: """return the domain used for the random alias""" if self.default_alias_custom_domain_id: custom_domain = CustomDomain.get(self.default_alias_custom_domain_id) # sanity check if ( not custom_domain or not custom_domain.verified or custom_domain.user_id != self.id ): LOG.w("Problem with %s default random alias domain", self) return config.FIRST_ALIAS_DOMAIN return custom_domain.domain if self.default_alias_public_domain_id: sl_domain = SLDomain.get(self.default_alias_public_domain_id) # sanity check if not sl_domain: LOG.e("Problem with %s public random alias domain", self) return config.FIRST_ALIAS_DOMAIN if sl_domain.premium_only and not self.is_premium(): LOG.w( "%s is not premium and cannot use %s. Reset default random alias domain setting", self, sl_domain, ) self.default_alias_custom_domain_id = None self.default_alias_public_domain_id = None Session.commit() return config.FIRST_ALIAS_DOMAIN return sl_domain.domain return config.FIRST_ALIAS_DOMAIN def fido_enabled(self) -> bool: if self.fido_uuid is not None: return True return False def two_factor_authentication_enabled(self) -> bool: return self.enable_otp or self.fido_enabled() def get_communication_email(self) -> (Optional[str], str, bool): """ Return - the email that user uses to receive email communication. None if user unsubscribes from newsletter - the unsubscribe URL - whether the unsubscribe method is via sending email (mailto:) or Http POST """ if self.notification and self.activated and not self.disabled: if self.newsletter_alias_id: alias = Alias.get(self.newsletter_alias_id) if alias.enabled: unsub = UnsubscribeEncoder.encode( UnsubscribeAction.DisableAlias, alias.id ) return alias.email, unsub.link, unsub.via_email # alias disabled -> user doesn't want to receive newsletter else: return None, "", False else: # do not handle http POST unsubscribe if config.UNSUBSCRIBER: # use * as suffix instead of = as for alias unsubscribe return ( self.email, UnsubscribeEncoder.encode_mailto( UnsubscribeAction.UnsubscribeNewsletter, self.id ), True, ) return None, "", False def available_sl_domains( self, alias_options: Optional[AliasOptions] = None ) -> [str]: """ Return all SimpleLogin domains that user can use when creating a new alias, including: - SimpleLogin public domains, available for all users (ALIAS_DOMAIN) - SimpleLogin premium domains, only available for Premium accounts (PREMIUM_ALIAS_DOMAIN) """ return [ sl_domain.domain for sl_domain in self.get_sl_domains(alias_options=alias_options) ] def get_sl_domains( self, alias_options: Optional[AliasOptions] = None ) -> list["SLDomain"]: if alias_options is None: alias_options = AliasOptions() top_conds = [SLDomain.hidden == False] # noqa: E712 or_conds = [] # noqa:E711 if self.default_alias_public_domain_id is not None: default_domain_conds = [SLDomain.id == self.default_alias_public_domain_id] if not self.is_premium(): default_domain_conds.append( SLDomain.premium_only == False # noqa: E712 ) or_conds.append(and_(*default_domain_conds).self_group()) if alias_options.show_partner_domains is not None: partner_user = PartnerUser.filter_by( user_id=self.id, partner_id=alias_options.show_partner_domains.id ).first() if partner_user is not None: partner_domain_cond = [SLDomain.partner_id == partner_user.partner_id] if alias_options.show_partner_premium is None: alias_options.show_partner_premium = self.is_premium() if not alias_options.show_partner_premium: partner_domain_cond.append( SLDomain.premium_only == False # noqa: E712 ) or_conds.append(and_(*partner_domain_cond).self_group()) if alias_options.show_sl_domains: sl_conds = [SLDomain.partner_id == None] # noqa: E711 if not self.is_premium(): sl_conds.append(SLDomain.premium_only == False) # noqa: E712 or_conds.append(and_(*sl_conds).self_group()) top_conds.append(or_(*or_conds)) query = Session.query(SLDomain).filter(*top_conds).order_by(SLDomain.order) return query.all() def available_alias_domains( self, alias_options: Optional[AliasOptions] = None ) -> [str]: """return all domains that user can use when creating a new alias, including: - SimpleLogin public domains, available for all users (ALIAS_DOMAIN) - SimpleLogin premium domains, only available for Premium accounts (PREMIUM_ALIAS_DOMAIN) - Verified custom domains """ domains = self.available_sl_domains(alias_options=alias_options) for custom_domain in self.verified_custom_domains(): domains.append(custom_domain.domain) # can have duplicate where a "root" user has a domain that's also listed in SL domains return list(set(domains)) def should_show_app_page(self) -> bool: """whether to show the app page""" return ( # when user has used the "Sign in with SL" button before ClientUser.filter(ClientUser.user_id == self.id).count() # or when user has created an app + Client.filter(Client.user_id == self.id).count() > 0 ) def get_random_alias_suffix(self, custom_domain: Optional["CustomDomain"] = None): """Get random suffix for an alias based on user's preference. Use a shorter suffix in case of custom domain Returns: str: the random suffix generated """ if self.random_alias_suffix == AliasSuffixEnum.random_string.value: return random_string(config.ALIAS_RANDOM_SUFFIX_LENGTH, include_digits=True) if custom_domain is None: return random_words(1, 3) return random_words(1) def can_create_contacts(self) -> bool: if self.is_premium(): return True if self.flags & User.FLAG_FREE_DISABLE_CREATE_ALIAS == 0: return True return not config.DISABLE_CREATE_CONTACTS_FOR_FREE_USERS def __repr__(self): return f"<User {self.id} {self.name} {self.email}>" class 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"),) def sanitize_email(email_address: str, not_lower=False) -> str: if email_address: email_address = email_address.strip().replace(" ", "").replace("\n", " ") if not not_lower: email_address = email_address.lower() return email_address.replace("\u200f", "") The provided code snippet includes necessary dependencies for implementing the `auth_google` function. Write a Python function `def auth_google()` to solve the following problem: Authenticate user with Google Input: google_token: Google access token device: to create an ApiKey associated with this device Output: 200 and user info containing: { name: "John Wick", mfa_enabled: true, mfa_key: "a long string", api_key: "a long string" } Here is the function: def auth_google(): """ Authenticate user with Google Input: google_token: Google access token device: to create an ApiKey associated with this device Output: 200 and user info containing: { name: "John Wick", mfa_enabled: true, mfa_key: "a long string", api_key: "a long string" } """ data = request.get_json() if not data: return jsonify(error="request body cannot be empty"), 400 google_token = data.get("google_token") device = data.get("device") cred = google.oauth2.credentials.Credentials(token=google_token) build = googleapiclient.discovery.build("oauth2", "v2", credentials=cred) user_info = build.userinfo().get().execute() email = sanitize_email(user_info.get("email")) user = User.get_by(email=email) if not user: if DISABLE_REGISTRATION: return jsonify(error="registration is closed"), 400 if not email_can_be_used_as_mailbox(email) or personal_email_already_used( email ): return jsonify(error=f"cannot use {email} as personal inbox"), 400 LOG.d("create Google user with %s", user_info) user = User.create(email=email, name="", activated=True) Session.commit() email_utils.send_welcome_email(user) if not SocialAuth.get_by(user_id=user.id, social="google"): SocialAuth.create(user_id=user.id, social="google") Session.commit() return jsonify(**auth_payload(user, device)), 200
Authenticate user with Google Input: google_token: Google access token device: to create an ApiKey associated with this device Output: 200 and user info containing: { name: "John Wick", mfa_enabled: true, mfa_key: "a long string", api_key: "a long string" }
180,625
import secrets import string import facebook import google.oauth2.credentials import googleapiclient.discovery from flask import jsonify, request from flask_login import login_user from itsdangerous import Signer from app import email_utils from app.api.base import api_bp from app.config import FLASK_SECRET, DISABLE_REGISTRATION from app.dashboard.views.account_setting import send_reset_password_email from app.db import Session from app.email_utils import ( email_can_be_used_as_mailbox, personal_email_already_used, send_email, render, ) from app.events.auth_event import LoginEvent, RegisterEvent from app.extensions import limiter from app.log import LOG from app.models import User, ApiKey, SocialAuth, AccountActivation from app.utils import sanitize_email, 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) 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}>" 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", "") The provided code snippet includes necessary dependencies for implementing the `forgot_password` function. Write a Python function `def forgot_password()` to solve the following problem: User forgot password Input: email Output: 200 and a reset password email is sent to user 400 if email not exist Here is the function: def forgot_password(): """ User forgot password Input: email Output: 200 and a reset password email is sent to user 400 if email not exist """ data = request.get_json() if not data or not data.get("email"): return jsonify(error="request body must contain email"), 400 email = sanitize_email(data.get("email")) canonical_email = canonicalize_email(data.get("email")) user = User.get_by(email=email) or User.get_by(email=canonical_email) if user: send_reset_password_email(user) return jsonify(ok=True)
User forgot password Input: email Output: 200 and a reset password email is sent to user 400 if email not exist
180,626
import pyotp from flask import jsonify, request from flask_login import login_user from itsdangerous import Signer from app.api.base import api_bp from app.config import FLASK_SECRET from app.db import Session from app.email_utils import send_invalid_totp_login_email from app.extensions import limiter from app.log import LOG from app.models import User, ApiKey FLASK_SECRET = os.environ["FLASK_SECRET"] if not FLASK_SECRET: raise RuntimeError("FLASK_SECRET is empty. Please define it.") Session = scoped_session(sessionmaker(bind=connection)) Session: sqlalchemy.orm.Session def send_invalid_totp_login_email(user, totp_type): send_email_with_rate_control( user, config.ALERT_INVALID_TOTP_LOGIN, user.email, "Unsuccessful attempt to login to your SimpleLogin account", render( "transactional/invalid-totp-login.txt", type=totp_type, ), render( "transactional/invalid-totp-login.html", type=totp_type, ), 1, ) 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 ApiKey(Base, ModelMixin): """used in browser extension to identify user""" __tablename__ = "api_key" user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False) code = sa.Column(sa.String(128), unique=True, nullable=False) name = sa.Column(sa.String(128), nullable=True) last_used = sa.Column(ArrowType, default=None) times = sa.Column(sa.Integer, default=0, nullable=False) sudo_mode_at = sa.Column(ArrowType, default=None) user = orm.relationship(User) def create(cls, user_id, name=None, **kwargs): code = random_string(60) if cls.get_by(code=code): code = str(uuid.uuid4()) return super().create(user_id=user_id, name=name, code=code, **kwargs) def delete_all(cls, user_id): Session.query(cls).filter(cls.user_id == user_id).delete() The provided code snippet includes necessary dependencies for implementing the `auth_mfa` function. Write a Python function `def auth_mfa()` to solve the following problem: Validate the OTP Token Input: mfa_token: OTP token that user enters mfa_key: MFA key obtained in previous auth request, e.g. /api/auth/login device: the device name, used to create an ApiKey associated with this device Output: 200 and user info containing: { name: "John Wick", api_key: "a long string", email: "user email" } Here is the function: def auth_mfa(): """ Validate the OTP Token Input: mfa_token: OTP token that user enters mfa_key: MFA key obtained in previous auth request, e.g. /api/auth/login device: the device name, used to create an ApiKey associated with this device Output: 200 and user info containing: { name: "John Wick", api_key: "a long string", email: "user email" } """ data = request.get_json() if not data: return jsonify(error="request body cannot be empty"), 400 mfa_token = data.get("mfa_token") mfa_key = data.get("mfa_key") device = data.get("device") s = Signer(FLASK_SECRET) try: user_id = int(s.unsign(mfa_key)) except Exception: return jsonify(error="Invalid mfa_key"), 400 user = User.get(user_id) if not user: return jsonify(error="Invalid mfa_key"), 400 elif not user.enable_otp: return ( jsonify(error="This endpoint should only be used by user who enables MFA"), 400, ) totp = pyotp.TOTP(user.otp_secret) if not totp.verify(mfa_token, valid_window=2): send_invalid_totp_login_email(user, "TOTP") return jsonify(error="Wrong TOTP Token"), 400 ret = {"name": user.name or "", "email": user.email} api_key = ApiKey.get_by(user_id=user.id, name=device) if not api_key: LOG.d("create new api key for %s and %s", user, device) api_key = ApiKey.create(user.id, device) Session.commit() ret["api_key"] = api_key.code # so user is logged in automatically on the web login_user(user) return jsonify(**ret), 200
Validate the OTP Token Input: mfa_token: OTP token that user enters mfa_key: MFA key obtained in previous auth request, e.g. /api/auth/login device: the device name, used to create an ApiKey associated with this device Output: 200 and user info containing: { name: "John Wick", api_key: "a long string", email: "user email" }
180,627
from functools import wraps from typing import Tuple, Optional import arrow from flask import Blueprint, request, jsonify, g from flask_login import current_user from app.db import Session from app.models import ApiKey def authorize_request() -> Optional[Tuple[str, int]]: api_code = request.headers.get("Authentication") api_key = ApiKey.get_by(code=api_code) if not api_key: if current_user.is_authenticated: g.user = current_user else: return jsonify(error="Wrong api key"), 401 else: # Update api key stats api_key.last_used = arrow.now() api_key.times += 1 Session.commit() g.user = api_key.user if g.user.disabled: return jsonify(error="Disabled account"), 403 if not g.user.is_active(): return jsonify(error="Account does not exist"), 401 g.api_key = api_key return None def require_api_auth(f): @wraps(f) def decorated(*args, **kwargs): error_return = authorize_request() if error_return: return error_return return f(*args, **kwargs) return decorated
null
180,628
from functools import wraps from typing import Tuple, Optional import arrow from flask import Blueprint, request, jsonify, g from flask_login import current_user from app.db import Session from app.models import ApiKey def authorize_request() -> Optional[Tuple[str, int]]: api_code = request.headers.get("Authentication") api_key = ApiKey.get_by(code=api_code) if not api_key: if current_user.is_authenticated: g.user = current_user else: return jsonify(error="Wrong api key"), 401 else: # Update api key stats api_key.last_used = arrow.now() api_key.times += 1 Session.commit() g.user = api_key.user if g.user.disabled: return jsonify(error="Disabled account"), 403 if not g.user.is_active(): return jsonify(error="Account does not exist"), 401 g.api_key = api_key return None def check_sudo_mode_is_active(api_key: ApiKey) -> bool: return api_key.sudo_mode_at and g.api_key.sudo_mode_at >= arrow.now().shift( minutes=-SUDO_MODE_MINUTES_VALID ) def require_api_sudo(f): @wraps(f) def decorated(*args, **kwargs): error_return = authorize_request() if error_return: return error_return if not check_sudo_mode_is_active(g.api_key): return jsonify(error="Need sudo"), 440 return f(*args, **kwargs) return decorated
null
180,629
import csv from io import StringIO import re from typing import Optional, Tuple from email_validator import validate_email, EmailNotValidError from sqlalchemy.exc import IntegrityError, DataError from flask import make_response from app.config import ( BOUNCE_PREFIX_FOR_REPLY_PHASE, BOUNCE_PREFIX, BOUNCE_SUFFIX, VERP_PREFIX, ) from app.db import Session from app.email_utils import ( get_email_domain_part, send_cannot_create_directory_alias, can_create_directory_for_address, send_cannot_create_directory_alias_disabled, get_email_local_part, send_cannot_create_domain_alias, send_email, render, ) from app.errors import AliasInTrashError from app.log import LOG from app.models import ( Alias, CustomDomain, Directory, User, DeletedAlias, DomainDeletedAlias, AliasMailbox, Mailbox, EmailLog, Contact, AutoCreateRule, AliasUsedOn, ClientUser, ) from app.regex_utils import regex_match def check_if_alias_can_be_auto_created_for_custom_domain( address: str, notify_user: bool = True ) -> Optional[Tuple[CustomDomain, Optional[AutoCreateRule]]]: """ Check if this address would generate an auto created alias. If that's the case return the domain that would create it and the rule that triggered it. If there's no rule it's a catchall creation """ alias_domain = get_email_domain_part(address) custom_domain: CustomDomain = CustomDomain.get_by(domain=alias_domain) if not custom_domain: return None user: User = custom_domain.user if user.disabled: LOG.i("Disabled user %s can't create new alias via custom domain", user) return None if not user.can_create_new_alias(): LOG.d(f"{user} can't create new custom-domain alias {address}") if notify_user: send_cannot_create_domain_alias(custom_domain.user, address, alias_domain) return None if not custom_domain.catch_all: if len(custom_domain.auto_create_rules) == 0: return None local = get_email_local_part(address) for rule in custom_domain.auto_create_rules: if regex_match(rule.regex, local): LOG.d( "%s passes %s on %s", address, rule.regex, custom_domain, ) return custom_domain, rule else: # no rule passes LOG.d("no rule passed to create %s", local) return None LOG.d("Create alias via catchall") return custom_domain, None def check_if_alias_can_be_auto_created_for_a_directory( address: str, notify_user: bool = True ) -> Optional[Directory]: """ Try to create an alias with directory If an alias would be created, return the dictionary that would trigger the creation. Otherwise, return None. """ # check if alias belongs to a directory, ie having directory/anything@EMAIL_DOMAIN format if not can_create_directory_for_address(address): return None # alias contains one of the 3 special directory separator: "/", "+" or "#" if "/" in address: sep = "/" elif "+" in address: sep = "+" elif "#" in address: sep = "#" else: # if there's no directory separator in the alias, no way to auto-create it return None directory_name = address[: address.find(sep)] LOG.d("directory_name %s", directory_name) directory = Directory.get_by(name=directory_name) if not directory: return None user: User = directory.user if user.disabled: LOG.i("Disabled %s can't create new alias with directory", user) return None if not user.can_create_new_alias(): LOG.d(f"{user} can't create new directory alias {address}") if notify_user: send_cannot_create_directory_alias(user, address, directory_name) return None if directory.disabled: if notify_user: send_cannot_create_directory_alias_disabled(user, address, directory_name) return None return directory VERP_PREFIX = os.environ.get("VERP_PREFIX") or "sl" 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 DomainDeletedAlias(Base, ModelMixin): """Store all deleted alias for a domain""" __tablename__ = "domain_deleted_alias" __table_args__ = ( sa.UniqueConstraint("domain_id", "email", name="uq_domain_trash"), ) email = sa.Column(sa.String(256), nullable=False) domain_id = sa.Column( sa.ForeignKey("custom_domain.id", ondelete="cascade"), nullable=False ) user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False) domain = orm.relationship(CustomDomain) user = orm.relationship(User, foreign_keys=[user_id]) def create(cls, **kw): raise Exception("should use delete_alias(alias,user) instead") def __repr__(self): return f"<DomainDeletedAlias {self.id} {self.email}>" def get_user_if_alias_would_auto_create( address: str, notify_user: bool = False ) -> Optional[User]: banned_prefix = f"{VERP_PREFIX}." if address.startswith(banned_prefix): LOG.w("alias %s can't start with %s", address, banned_prefix) return None try: # Prevent addresses with unicode characters (🤯) in them for now. validate_email(address, check_deliverability=False, allow_smtputf8=False) except EmailNotValidError: return None domain_and_rule = check_if_alias_can_be_auto_created_for_custom_domain( address, notify_user=notify_user ) if DomainDeletedAlias.get_by(email=address): return None if domain_and_rule: return domain_and_rule[0].user directory = check_if_alias_can_be_auto_created_for_a_directory( address, notify_user=notify_user ) if directory: return directory.user return None
null
180,630
import random import re import secrets import string import time import urllib.parse from functools import wraps from typing import List, Optional from flask_wtf import FlaskForm from unidecode import unidecode from .config import WORDS_FILE_PATH, ALLOWED_REDIRECT_DOMAINS from .log import LOG def random_word(): return secrets.choice(_words)
null
180,631
import random import re import secrets import string import time import urllib.parse from functools import wraps from typing import List, Optional from flask_wtf import FlaskForm from unidecode import unidecode from .config import WORDS_FILE_PATH, ALLOWED_REDIRECT_DOMAINS from .log import LOG def word_exist(word): return word in _words
null
180,632
import random import re import secrets import string import time import urllib.parse from functools import wraps from typing import List, Optional from flask_wtf import FlaskForm from unidecode import unidecode from .config import WORDS_FILE_PATH, ALLOWED_REDIRECT_DOMAINS from .log import LOG The provided code snippet includes necessary dependencies for implementing the `query2str` function. Write a Python function `def query2str(query)` to solve the following problem: Useful utility method to print out a SQLAlchemy query Here is the function: def query2str(query): """Useful utility method to print out a SQLAlchemy query""" return query.statement.compile(compile_kwargs={"literal_binds": True})
Useful utility method to print out a SQLAlchemy query
180,633
import random import re import secrets import string import time import urllib.parse from functools import wraps from typing import List, Optional from flask_wtf import FlaskForm from unidecode import unidecode from .config import WORDS_FILE_PATH, ALLOWED_REDIRECT_DOMAINS from .log import LOG LOG = _get_logger("SL") def debug_info(func): @wraps(func) def wrap(*args, **kwargs): start = time.time() LOG.d("start %s %s %s", func.__name__, args, kwargs) ret = func(*args, **kwargs) LOG.d("finish %s. Takes %s seconds", func.__name__, time.time() - start) return ret return wrap
null
180,634
import arrow from flask import make_response, render_template from flask_login import login_required from app.config import URL from app.onboarding.base import onboarding_bp URL = os.environ["URL"] def setup_done(): response = make_response(render_template("onboarding/setup_done.html")) # TODO: Remove when the extension is updated everywhere 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,635
from app.onboarding.base import onboarding_bp from app.onboarding.utils import get_extension_info from flask import redirect, render_template, url_for from flask_login import login_required def get_extension_info() -> Optional[ExtensionInfo]: browser = get_browser() if browser == Browser.Chrome: extension_link = CHROME_EXTENSION_LINK browser_name = "Chrome" elif browser == Browser.Firefox: extension_link = FIREFOX_EXTENSION_LINK browser_name = "Firefox" elif browser == Browser.Edge: extension_link = EDGE_EXTENSION_LINK browser_name = "Edge" else: return None return ExtensionInfo( browser=browser_name, url=extension_link, ) def account_activated(): info = get_extension_info() if not info: return redirect(url_for("dashboard.index")) return render_template( "onboarding/account_activated.html", extension_link=info.url, browser_name=info.browser, )
null
180,636
from app.onboarding.base import onboarding_bp from flask import render_template def index(): return render_template("onboarding/index.html")
null
180,637
from app.extensions import limiter from app.models import Alias from app.onboarding.base import onboarding_bp from app.email_utils import send_test_email_alias from flask import render_template, request, flash from flask_login import current_user, login_required from flask_wtf import FlaskForm from wtforms import StringField, validators class SendEmailForm(FlaskForm): email = StringField("Email", validators=[validators.DataRequired()]) 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 send_test_email_alias(email, name): send_email( email, f"This email is sent to {email}", render( "transactional/test-email.txt", name=name, alias=email, ), render( "transactional/test-email.html", name=name, alias=email, ), ) def final(): form = SendEmailForm(request.form) if form.validate_on_submit(): alias = Alias.get_by(email=form.email.data) if alias and alias.user_id == current_user.id: send_test_email_alias(alias.email, current_user.name) flash("An email is sent to your alias", "success") return render_template( "onboarding/final.html", form=form, )
null
180,638
from app.onboarding.base import onboarding_bp from app.onboarding.utils import get_extension_info from flask import redirect, url_for def get_extension_info() -> Optional[ExtensionInfo]: browser = get_browser() if browser == Browser.Chrome: extension_link = CHROME_EXTENSION_LINK browser_name = "Chrome" elif browser == Browser.Firefox: extension_link = FIREFOX_EXTENSION_LINK browser_name = "Firefox" elif browser == Browser.Edge: extension_link = EDGE_EXTENSION_LINK browser_name = "Edge" else: return None return ExtensionInfo( browser=browser_name, url=extension_link, ) def extension_redirect(): info = get_extension_info() if not info: return redirect(url_for("dashboard.index")) return redirect(info.url)
null
180,639
from typing import Optional import arrow import sqlalchemy from flask_admin.model.template import EndpointLinkRowAction from markupsafe import Markup from app import models, s3 from flask import redirect, url_for, request, flash, Response from flask_admin import expose, AdminIndexView from flask_admin.actions import action from flask_admin.contrib import sqla from flask_login import current_user from app.db import Session from app.models import ( User, ManualSubscription, Fido, Subscription, AppleSubscription, AdminAuditLog, AuditLogActionEnum, ProviderComplaintState, Phase, ProviderComplaint, Alias, Newsletter, PADDLE_SUBSCRIPTION_GRACE_DAYS, ) from app.newsletter_utils import send_newsletter_to_user, send_newsletter_to_address def _user_upgrade_channel_formatter(view, context, model, name): return Markup(model.upgrade_channel)
null
180,640
from typing import Optional import arrow import sqlalchemy from flask_admin.model.template import EndpointLinkRowAction from markupsafe import Markup from app import models, s3 from flask import redirect, url_for, request, flash, Response from flask_admin import expose, AdminIndexView from flask_admin.actions import action from flask_admin.contrib import sqla from flask_login import current_user from app.db import Session from app.models import ( User, ManualSubscription, Fido, Subscription, AppleSubscription, AdminAuditLog, AuditLogActionEnum, ProviderComplaintState, Phase, ProviderComplaint, Alias, Newsletter, PADDLE_SUBSCRIPTION_GRACE_DAYS, ) from app.newsletter_utils import send_newsletter_to_user, send_newsletter_to_address Session = scoped_session(sessionmaker(bind=connection)) Session: sqlalchemy.orm.Session 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 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 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 AdminAuditLog(Base): __tablename__ = "admin_audit_log" id = sa.Column(sa.Integer, primary_key=True, autoincrement=True) created_at = sa.Column(ArrowType, default=arrow.utcnow, nullable=False) admin_user_id = sa.Column( sa.ForeignKey("users.id", ondelete="cascade"), nullable=False, index=True ) action = sa.Column(sa.Integer, nullable=False) model = sa.Column(sa.Text, nullable=False) model_id = sa.Column(sa.Integer, nullable=True) data = sa.Column(sa.JSON, nullable=False) admin = orm.relationship(User, foreign_keys=[admin_user_id]) def create(cls, **kw): r = cls(**kw) Session.add(r) return r def create_manual_upgrade( cls, admin_user_id: int, upgrade_type: str, user_id: int, giveaway: bool ): cls.create( admin_user_id=admin_user_id, action=AuditLogActionEnum.manual_upgrade.value, model="User", model_id=user_id, data={ "upgrade_type": upgrade_type, "giveaway": giveaway, }, ) def extend_trial( cls, admin_user_id: int, user_id: int, trial_end: arrow.Arrow, extend_time: str ): cls.create( admin_user_id=admin_user_id, action=AuditLogActionEnum.extend_trial.value, model="User", model_id=user_id, data={ "trial_end": trial_end.format(arrow.FORMAT_RFC3339), "extend_time": extend_time, }, ) def stop_trial(cls, admin_user_id: int, user_id: int): cls.create( admin_user_id=admin_user_id, action=AuditLogActionEnum.stop_trial.value, model="User", model_id=user_id, ) def disable_otp_fido( cls, admin_user_id: int, user_id: int, had_otp: bool, had_fido: bool ): cls.create( admin_user_id=admin_user_id, action=AuditLogActionEnum.disable_2fa.value, model="User", model_id=user_id, data={"had_otp": had_otp, "had_fido": had_fido}, ) def logged_as_user(cls, admin_user_id: int, user_id: int): cls.create( admin_user_id=admin_user_id, action=AuditLogActionEnum.logged_as_user.value, model="User", model_id=user_id, data={}, ) def extend_subscription( cls, admin_user_id: int, user_id: int, subscription_end: arrow.Arrow, extend_time: str, ): cls.create( admin_user_id=admin_user_id, action=AuditLogActionEnum.extend_subscription.value, model="User", model_id=user_id, data={ "subscription_end": subscription_end.format(arrow.FORMAT_RFC3339), "extend_time": extend_time, }, ) def downloaded_provider_complaint(cls, admin_user_id: int, complaint_id: int): cls.create( admin_user_id=admin_user_id, action=AuditLogActionEnum.download_provider_complaint.value, model="ProviderComplaint", model_id=complaint_id, data={}, ) def disable_user(cls, admin_user_id: int, user_id: int): cls.create( admin_user_id=admin_user_id, action=AuditLogActionEnum.disable_user.value, model="User", model_id=user_id, data={}, ) def enable_user(cls, admin_user_id: int, user_id: int): cls.create( admin_user_id=admin_user_id, action=AuditLogActionEnum.enable_user.value, model="User", model_id=user_id, data={}, ) def manual_upgrade(way: str, ids: [int], is_giveaway: bool): for user in User.filter(User.id.in_(ids)).all(): if user.lifetime: flash(f"user {user} already has a lifetime license", "warning") continue sub: Subscription = user.get_paddle_subscription() if sub and not sub.cancelled: flash( f"user {user} already has a Paddle license, they have to cancel it first", "warning", ) continue apple_sub: AppleSubscription = AppleSubscription.get_by(user_id=user.id) if apple_sub and apple_sub.is_valid(): flash( f"user {user} already has a Apple subscription, they have to cancel it first", "warning", ) continue AdminAuditLog.create_manual_upgrade(current_user.id, way, user.id, is_giveaway) manual_sub: ManualSubscription = ManualSubscription.get_by(user_id=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=1) else: manual_sub.end_at = arrow.now().shift(years=1, days=1) flash(f"Subscription extended to {manual_sub.end_at.humanize()}", "success") continue ManualSubscription.create( user_id=user.id, end_at=arrow.now().shift(years=1, days=1), comment=way, is_giveaway=is_giveaway, ) flash(f"New {way} manual subscription for {user} is created", "success") Session.commit()
null
180,641
from typing import Optional import arrow import sqlalchemy from flask_admin.model.template import EndpointLinkRowAction from markupsafe import Markup from app import models, s3 from flask import redirect, url_for, request, flash, Response from flask_admin import expose, AdminIndexView from flask_admin.actions import action from flask_admin.contrib import sqla from flask_login import current_user from app.db import Session from app.models import ( User, ManualSubscription, Fido, Subscription, AppleSubscription, AdminAuditLog, AuditLogActionEnum, ProviderComplaintState, Phase, ProviderComplaint, Alias, Newsletter, PADDLE_SUBSCRIPTION_GRACE_DAYS, ) from app.newsletter_utils import send_newsletter_to_user, send_newsletter_to_address class AuditLogActionEnum(EnumE): create_object = 0 update_object = 1 delete_object = 2 manual_upgrade = 3 extend_trial = 4 disable_2fa = 5 logged_as_user = 6 extend_subscription = 7 download_provider_complaint = 8 disable_user = 9 enable_user = 10 stop_trial = 11 def _admin_action_formatter(view, context, model, name): action_name = AuditLogActionEnum.get_name(model.action) return "{} ({})".format(action_name, model.action)
null
180,642
from typing import Optional import arrow import sqlalchemy from flask_admin.model.template import EndpointLinkRowAction from markupsafe import Markup from app import models, s3 from flask import redirect, url_for, request, flash, Response from flask_admin import expose, AdminIndexView from flask_admin.actions import action from flask_admin.contrib import sqla from flask_login import current_user from app.db import Session from app.models import ( User, ManualSubscription, Fido, Subscription, AppleSubscription, AdminAuditLog, AuditLogActionEnum, ProviderComplaintState, Phase, ProviderComplaint, Alias, Newsletter, PADDLE_SUBSCRIPTION_GRACE_DAYS, ) from app.newsletter_utils import send_newsletter_to_user, send_newsletter_to_address def _admin_created_at_formatter(view, context, model, name): return model.created_at.format()
null
180,643
from typing import Optional import arrow import sqlalchemy from flask_admin.model.template import EndpointLinkRowAction from markupsafe import Markup from app import models, s3 from flask import redirect, url_for, request, flash, Response from flask_admin import expose, AdminIndexView from flask_admin.actions import action from flask_admin.contrib import sqla from flask_login import current_user from app.db import Session from app.models import ( User, ManualSubscription, Fido, Subscription, AppleSubscription, AdminAuditLog, AuditLogActionEnum, ProviderComplaintState, Phase, ProviderComplaint, Alias, Newsletter, PADDLE_SUBSCRIPTION_GRACE_DAYS, ) from app.newsletter_utils import send_newsletter_to_user, send_newsletter_to_address class ProviderComplaintState(EnumE): new = 0 reviewed = 1 def _transactionalcomplaint_state_formatter(view, context, model, name): return "{} ({})".format(ProviderComplaintState(model.state).name, model.state)
null
180,644
from typing import Optional import arrow import sqlalchemy from flask_admin.model.template import EndpointLinkRowAction from markupsafe import Markup from app import models, s3 from flask import redirect, url_for, request, flash, Response from flask_admin import expose, AdminIndexView from flask_admin.actions import action from flask_admin.contrib import sqla from flask_login import current_user from app.db import Session from app.models import ( User, ManualSubscription, Fido, Subscription, AppleSubscription, AdminAuditLog, AuditLogActionEnum, ProviderComplaintState, Phase, ProviderComplaint, Alias, Newsletter, PADDLE_SUBSCRIPTION_GRACE_DAYS, ) from app.newsletter_utils import send_newsletter_to_user, send_newsletter_to_address class Phase(EnumE): unknown = 0 forward = 1 reply = 2 def _transactionalcomplaint_phase_formatter(view, context, model, name): return Phase(model.phase).name
null
180,645
from typing import Optional import arrow import sqlalchemy from flask_admin.model.template import EndpointLinkRowAction from markupsafe import Markup from app import models, s3 from flask import redirect, url_for, request, flash, Response from flask_admin import expose, AdminIndexView from flask_admin.actions import action from flask_admin.contrib import sqla from flask_login import current_user from app.db import Session from app.models import ( User, ManualSubscription, Fido, Subscription, AppleSubscription, AdminAuditLog, AuditLogActionEnum, ProviderComplaintState, Phase, ProviderComplaint, Alias, Newsletter, PADDLE_SUBSCRIPTION_GRACE_DAYS, ) from app.newsletter_utils import send_newsletter_to_user, send_newsletter_to_address def _transactionalcomplaint_refused_email_id_formatter(view, context, model, name): markupstring = "<a href='{}'>{}</a>".format( url_for(".download_eml", id=model.id), model.refused_email.full_report_path ) return Markup(markupstring)
null
180,646
from typing import Optional import arrow import sqlalchemy from flask_admin.model.template import EndpointLinkRowAction from markupsafe import Markup from app import models, s3 from flask import redirect, url_for, request, flash, Response from flask_admin import expose, AdminIndexView from flask_admin.actions import action from flask_admin.contrib import sqla from flask_login import current_user from app.db import Session from app.models import ( User, ManualSubscription, Fido, Subscription, AppleSubscription, AdminAuditLog, AuditLogActionEnum, ProviderComplaintState, Phase, ProviderComplaint, Alias, Newsletter, PADDLE_SUBSCRIPTION_GRACE_DAYS, ) from app.newsletter_utils import send_newsletter_to_user, send_newsletter_to_address class Newsletter(Base, ModelMixin): def __repr__(self): def _newsletter_plain_text_formatter(view, context, model: Newsletter, name): # to display newsletter plain_text with linebreaks in the list view return Markup(model.plain_text.replace("\n", "<br>"))
null
180,647
from typing import Optional import arrow import sqlalchemy from flask_admin.model.template import EndpointLinkRowAction from markupsafe import Markup from app import models, s3 from flask import redirect, url_for, request, flash, Response from flask_admin import expose, AdminIndexView from flask_admin.actions import action from flask_admin.contrib import sqla from flask_login import current_user from app.db import Session from app.models import ( User, ManualSubscription, Fido, Subscription, AppleSubscription, AdminAuditLog, AuditLogActionEnum, ProviderComplaintState, Phase, ProviderComplaint, Alias, Newsletter, PADDLE_SUBSCRIPTION_GRACE_DAYS, ) from app.newsletter_utils import send_newsletter_to_user, send_newsletter_to_address class Newsletter(Base, ModelMixin): def __repr__(self): def _newsletter_html_formatter(view, context, model: Newsletter, name): # to display newsletter html with linebreaks in the list view return Markup(model.html.replace("\n", "<br>"))
null
180,648
import os from jinja2 import Environment, FileSystemLoader from app.config import ROOT_DIR, URL from app.email_utils import send_email from app.handler.unsubscribe_encoder import UnsubscribeEncoder, UnsubscribeAction from app.log import LOG from app.models import NewsletterUser, Alias ROOT_DIR = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) URL = os.environ["URL"] def send_email( to_email, subject, plaintext, html=None, unsubscribe_link=None, unsubscribe_via_email=False, retries=0, # by default no retry if sending fails ignore_smtp_error=False, from_name=None, from_addr=None, ): to_email = sanitize_email(to_email) LOG.d("send email to %s, subject '%s'", to_email, subject) from_name = from_name or config.NOREPLY from_addr = from_addr or config.NOREPLY from_domain = get_email_domain_part(from_addr) if html: msg = MIMEMultipart("alternative") msg.attach(MIMEText(plaintext)) msg.attach(MIMEText(html, "html")) else: msg = EmailMessage() msg.set_payload(plaintext) msg[headers.CONTENT_TYPE] = "text/plain" msg[headers.SUBJECT] = subject msg[headers.FROM] = f'"{from_name}" <{from_addr}>' msg[headers.TO] = to_email msg_id_header = make_msgid(domain=config.EMAIL_DOMAIN) msg[headers.MESSAGE_ID] = msg_id_header date_header = formatdate() msg[headers.DATE] = date_header if headers.MIME_VERSION not in msg: msg[headers.MIME_VERSION] = "1.0" if unsubscribe_link: add_or_replace_header(msg, headers.LIST_UNSUBSCRIBE, f"<{unsubscribe_link}>") if not unsubscribe_via_email: add_or_replace_header( msg, headers.LIST_UNSUBSCRIBE_POST, "List-Unsubscribe=One-Click" ) # add DKIM email_domain = from_addr[from_addr.find("@") + 1 :] add_dkim_signature(msg, email_domain) transaction = TransactionalEmail.create(email=to_email, commit=True) # use a different envelope sender for each transactional email (aka VERP) sl_sendmail( generate_verp_email(VerpType.transactional, transaction.id, from_domain), to_email, msg, retries=retries, ignore_smtp_error=ignore_smtp_error, ) LOG = _get_logger("SL") class NewsletterUser(Base, ModelMixin): """This model keeps track of what newsletter is sent to what user""" __tablename__ = "newsletter_user" user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=True) newsletter_id = sa.Column( sa.ForeignKey(Newsletter.id, ondelete="cascade"), nullable=True ) # not use created_at here as it should only used for auditting purpose sent_at = sa.Column(ArrowType, default=arrow.utcnow, nullable=False) user = orm.relationship(User) newsletter = orm.relationship(Newsletter) The provided code snippet includes necessary dependencies for implementing the `send_newsletter_to_address` function. Write a Python function `def send_newsletter_to_address(newsletter, user, to_address) -> (bool, str)` to solve the following problem: Return whether the newsletter is sent successfully and the error if not Here is the function: def send_newsletter_to_address(newsletter, user, to_address) -> (bool, str): """Return whether the newsletter is sent successfully and the error if not""" try: templates_dir = os.path.join(ROOT_DIR, "templates", "emails") env = Environment(loader=FileSystemLoader(templates_dir)) html_template = env.from_string(newsletter.html) text_template = env.from_string(newsletter.plain_text) send_email( to_address, newsletter.subject, text_template.render( user=user, URL=URL, ), html_template.render( user=user, URL=URL, ), ) NewsletterUser.create(newsletter_id=newsletter.id, user_id=user.id, commit=True) return True, "" except Exception as err: LOG.w(f"cannot send {newsletter} to {user}", exc_info=True) return False, str(err)
Return whether the newsletter is sent successfully and the error if not
180,649
import base64 import hashlib from typing import Optional import arrow from jwcrypto import jwk, jwt from app.config import OPENID_PRIVATE_KEY_PATH, URL from app.log import LOG from app.models import ClientUser LOG = _get_logger("SL") def verify_id_token(id_token) -> bool: try: jwt.JWT(key=_key, jwt=id_token) except Exception: LOG.e("id token not verified") return False else: return True
null
180,650
import base64 import hashlib from typing import Optional import arrow from jwcrypto import jwk, jwt from app.config import OPENID_PRIVATE_KEY_PATH, URL from app.log import LOG from app.models import ClientUser def decode_id_token(id_token) -> jwt.JWT: return jwt.JWT(key=_key, jwt=id_token)
null
180,651
from datetime import datetime from typing import Optional import newrelic.agent import redis.exceptions import werkzeug.exceptions from limits.storage import RedisStorage from app.log import LOG lock_redis: Optional[RedisStorage] = None LOG = _get_logger("SL") def check_bucket_limit( lock_name: Optional[str] = None, max_hits: int = 5, bucket_seconds: int = 3600, ): # Calculate current bucket time int_time = int(datetime.utcnow().timestamp()) bucket_id = int_time - (int_time % bucket_seconds) bucket_lock_name = f"bl:{lock_name}:{bucket_id}" if not lock_redis: return try: value = lock_redis.incr(bucket_lock_name, bucket_seconds) if value > max_hits: LOG.i(f"Rate limit hit for {bucket_lock_name} -> {value}/{max_hits}") newrelic.agent.record_custom_event( "BucketRateLimit", {"lock_name": lock_name, "bucket_seconds": bucket_seconds}, ) raise werkzeug.exceptions.TooManyRequests() except (redis.exceptions.RedisError, AttributeError): LOG.e("Cannot connect to redis")
null
180,652
from dataclasses import dataclass from enum import Enum from flask import url_for from typing import Optional from app.errors import LinkException from app.models import User, Partner from app.proton.proton_client import ProtonClient, ProtonUser from app.account_linking import ( process_login_case, process_link_case, PartnerLinkRequest, ) class ProtonCallbackResult: redirect_to_login: bool flash_message: Optional[str] flash_category: Optional[str] redirect: Optional[str] user: Optional[User] def generate_account_not_allowed_to_log_in() -> ProtonCallbackResult: return ProtonCallbackResult( redirect_to_login=True, flash_message="This account is not allowed to log in with Proton. Please convert your account to a full Proton account", flash_category="error", redirect=None, user=None, )
null
180,653
from newrelic import agent from typing import Optional from app.db import Session from app.errors import ProtonPartnerNotSetUp from app.models import Partner, PartnerUser, User PROTON_PARTNER_NAME = "Proton" 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 def is_proton_partner(partner: Partner) -> bool: return partner.name == PROTON_PARTNER_NAME
null
180,654
from abc import ABC, abstractmethod from arrow import Arrow from dataclasses import dataclass from http import HTTPStatus from requests import Response, Session from typing import Optional from app.account_linking import SLPlan, SLPlanType from app.config import PROTON_EXTRA_HEADER_NAME, PROTON_EXTRA_HEADER_VALUE from app.errors import ProtonAccountNotVerified from app.log import LOG PROTON_ERROR_CODE_HV_NEEDED = 9001 class ProtonAccountNotVerified(LinkException): def __init__(self): super().__init__( "The Proton account you are trying to use has not been verified" ) def handle_response_not_ok(status: int, body: dict, text: str) -> Exception: if status == HTTPStatus.UNPROCESSABLE_ENTITY: res_code = body.get("Code") if res_code == PROTON_ERROR_CODE_HV_NEEDED: return ProtonAccountNotVerified() return Exception(f"Unexpected status code. Wanted 200 and got {status}: " + text)
null
180,655
from __future__ import annotations import base64 import dataclasses import enum import hashlib import hmac import os import random import secrets import uuid from typing import List, Tuple, Optional, Union import arrow import sqlalchemy as sa from arrow import Arrow from email_validator import validate_email from flanker.addresslib import address from flask import url_for from flask_login import UserMixin from jinja2 import FileSystemLoader, Environment from sqlalchemy import orm, or_ from sqlalchemy import text, desc, CheckConstraint, Index, Column from sqlalchemy.dialects.postgresql import TSVECTOR from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import deferred from sqlalchemy.sql import and_ from sqlalchemy_utils import ArrowType from app import config, rate_limiter from app import s3 from app.db import Session from app.dns_utils import get_mx_domains from app.errors import ( AliasInTrashError, DirectoryInTrashError, SubdomainInTrashError, CannotCreateContactForReverseAlias, ) from app.handler.unsubscribe_encoder import UnsubscribeAction, UnsubscribeEncoder from app.log import LOG from app.oauth_models import Scope from app.pw_models import PasswordOracle from app.utils import ( convert_to_id, random_string, random_words, sanitize_email, ) def _expiration_1h(): return arrow.now().shift(hours=1)
null
180,656
from __future__ import annotations import base64 import dataclasses import enum import hashlib import hmac import os import random import secrets import uuid from typing import List, Tuple, Optional, Union import arrow import sqlalchemy as sa from arrow import Arrow from email_validator import validate_email from flanker.addresslib import address from flask import url_for from flask_login import UserMixin from jinja2 import FileSystemLoader, Environment from sqlalchemy import orm, or_ from sqlalchemy import text, desc, CheckConstraint, Index, Column from sqlalchemy.dialects.postgresql import TSVECTOR from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import deferred from sqlalchemy.sql import and_ from sqlalchemy_utils import ArrowType from app import config, rate_limiter from app import s3 from app.db import Session from app.dns_utils import get_mx_domains from app.errors import ( AliasInTrashError, DirectoryInTrashError, SubdomainInTrashError, CannotCreateContactForReverseAlias, ) from app.handler.unsubscribe_encoder import UnsubscribeAction, UnsubscribeEncoder from app.log import LOG from app.oauth_models import Scope from app.pw_models import PasswordOracle from app.utils import ( convert_to_id, random_string, random_words, sanitize_email, ) def _expiration_12h(): return arrow.now().shift(hours=12)
null
180,657
from __future__ import annotations import base64 import dataclasses import enum import hashlib import hmac import os import random import secrets import uuid from typing import List, Tuple, Optional, Union import arrow import sqlalchemy as sa from arrow import Arrow from email_validator import validate_email from flanker.addresslib import address from flask import url_for from flask_login import UserMixin from jinja2 import FileSystemLoader, Environment from sqlalchemy import orm, or_ from sqlalchemy import text, desc, CheckConstraint, Index, Column from sqlalchemy.dialects.postgresql import TSVECTOR from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import deferred from sqlalchemy.sql import and_ from sqlalchemy_utils import ArrowType from app import config, rate_limiter from app import s3 from app.db import Session from app.dns_utils import get_mx_domains from app.errors import ( AliasInTrashError, DirectoryInTrashError, SubdomainInTrashError, CannotCreateContactForReverseAlias, ) from app.handler.unsubscribe_encoder import UnsubscribeAction, UnsubscribeEncoder from app.log import LOG from app.oauth_models import Scope from app.pw_models import PasswordOracle from app.utils import ( convert_to_id, random_string, random_words, sanitize_email, ) def _expiration_5m(): return arrow.now().shift(minutes=5)
null
180,658
from __future__ import annotations import base64 import dataclasses import enum import hashlib import hmac import os import random import secrets import uuid from typing import List, Tuple, Optional, Union import arrow import sqlalchemy as sa from arrow import Arrow from email_validator import validate_email from flanker.addresslib import address from flask import url_for from flask_login import UserMixin from jinja2 import FileSystemLoader, Environment from sqlalchemy import orm, or_ from sqlalchemy import text, desc, CheckConstraint, Index, Column from sqlalchemy.dialects.postgresql import TSVECTOR from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import deferred from sqlalchemy.sql import and_ from sqlalchemy_utils import ArrowType from app import config, rate_limiter from app import s3 from app.db import Session from app.dns_utils import get_mx_domains from app.errors import ( AliasInTrashError, DirectoryInTrashError, SubdomainInTrashError, CannotCreateContactForReverseAlias, ) from app.handler.unsubscribe_encoder import UnsubscribeAction, UnsubscribeEncoder from app.log import LOG from app.oauth_models import Scope from app.pw_models import PasswordOracle from app.utils import ( convert_to_id, random_string, random_words, sanitize_email, ) def _expiration_7d(): return arrow.now().shift(days=7)
null
180,659
from __future__ import annotations import base64 import dataclasses import enum import hashlib import hmac import os import random import secrets import uuid from typing import List, Tuple, Optional, Union import arrow import sqlalchemy as sa from arrow import Arrow from email_validator import validate_email from flanker.addresslib import address from flask import url_for from flask_login import UserMixin from jinja2 import FileSystemLoader, Environment from sqlalchemy import orm, or_ from sqlalchemy import text, desc, CheckConstraint, Index, Column from sqlalchemy.dialects.postgresql import TSVECTOR from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import deferred from sqlalchemy.sql import and_ from sqlalchemy_utils import ArrowType from app import config, rate_limiter from app import s3 from app.db import Session from app.dns_utils import get_mx_domains from app.errors import ( AliasInTrashError, DirectoryInTrashError, SubdomainInTrashError, CannotCreateContactForReverseAlias, ) from app.handler.unsubscribe_encoder import UnsubscribeAction, UnsubscribeEncoder from app.log import LOG from app.oauth_models import Scope from app.pw_models import PasswordOracle from app.utils import ( convert_to_id, random_string, random_words, sanitize_email, ) 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 LOG = _get_logger("SL") 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 convert_to_id(s: str): """convert a string to id-like: remove space, remove special accent""" s = s.lower() s = unidecode(s) s = s.replace(" ", "") return s[:256] def generate_oauth_client_id(client_name) -> str: oauth_client_id = convert_to_id(client_name) + "-" + random_string() # check that the client does not exist yet if not Client.get_by(oauth_client_id=oauth_client_id): LOG.d("generate oauth_client_id %s", oauth_client_id) return oauth_client_id # Rerun the function LOG.w("client_id %s already exists, generate a new client_id", oauth_client_id) return generate_oauth_client_id(client_name)
null
180,660
from __future__ import annotations import base64 import dataclasses import enum import hashlib import hmac import os import random import secrets import uuid from typing import List, Tuple, Optional, Union import arrow import sqlalchemy as sa from arrow import Arrow from email_validator import validate_email from flanker.addresslib import address from flask import url_for from flask_login import UserMixin from jinja2 import FileSystemLoader, Environment from sqlalchemy import orm, or_ from sqlalchemy import text, desc, CheckConstraint, Index, Column from sqlalchemy.dialects.postgresql import TSVECTOR from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import deferred from sqlalchemy.sql import and_ from sqlalchemy_utils import ArrowType from app import config, rate_limiter from app import s3 from app.db import Session from app.dns_utils import get_mx_domains from app.errors import ( AliasInTrashError, DirectoryInTrashError, SubdomainInTrashError, CannotCreateContactForReverseAlias, ) from app.handler.unsubscribe_encoder import UnsubscribeAction, UnsubscribeEncoder from app.log import LOG from app.oauth_models import Scope from app.pw_models import PasswordOracle from app.utils import ( convert_to_id, random_string, random_words, sanitize_email, ) class AliasGeneratorEnum(EnumE): word = 1 # aliases are generated based on random words uuid = 2 # aliases are generated based on uuid def available_sl_email(email: str) -> bool: if ( Alias.get_by(email=email) or Contact.get_by(reply_email=email) or DeletedAlias.get_by(email=email) ): return False return True LOG = _get_logger("SL") def random_words(words: int = 2, numbers: int = 0): """Generate a random words. Used to generate user-facing string, for ex email addresses""" # nb_words = random.randint(2, 3) fields = [secrets.choice(_words) for i in range(words)] if numbers > 0: digits = "".join([str(random.randint(0, 9)) for i in range(numbers)]) return "_".join(fields) + digits else: return "_".join(fields) The provided code snippet includes necessary dependencies for implementing the `generate_random_alias_email` function. Write a Python function `def generate_random_alias_email( scheme: int = AliasGeneratorEnum.word.value, in_hex: bool = False, alias_domain: str = config.FIRST_ALIAS_DOMAIN, retries: int = 10, ) -> str` to solve the following problem: generate an email address that does not exist before :param alias_domain: the domain used to generate the alias. :param scheme: int, value of AliasGeneratorEnum, indicate how the email is generated :param retries: int, How many times we can try to generate an alias in case of collision :type in_hex: bool, if the generate scheme is uuid, is hex favorable? Here is the function: def generate_random_alias_email( scheme: int = AliasGeneratorEnum.word.value, in_hex: bool = False, alias_domain: str = config.FIRST_ALIAS_DOMAIN, retries: int = 10, ) -> str: """generate an email address that does not exist before :param alias_domain: the domain used to generate the alias. :param scheme: int, value of AliasGeneratorEnum, indicate how the email is generated :param retries: int, How many times we can try to generate an alias in case of collision :type in_hex: bool, if the generate scheme is uuid, is hex favorable? """ if retries <= 0: raise Exception("Cannot generate alias after many retries") if scheme == AliasGeneratorEnum.uuid.value: name = uuid.uuid4().hex if in_hex else uuid.uuid4().__str__() random_email = name + "@" + alias_domain else: random_email = random_words(2, 3) + "@" + alias_domain random_email = random_email.lower().strip() # check that the client does not exist yet if available_sl_email(random_email): LOG.d("generate email %s", random_email) return random_email # Rerun the function LOG.w("email %s already exists, generate a new email", random_email) return generate_random_alias_email( scheme=scheme, in_hex=in_hex, retries=retries - 1 )
generate an email address that does not exist before :param alias_domain: the domain used to generate the alias. :param scheme: int, value of AliasGeneratorEnum, indicate how the email is generated :param retries: int, How many times we can try to generate an alias in case of collision :type in_hex: bool, if the generate scheme is uuid, is hex favorable?
180,661
from __future__ import annotations import base64 import email import json import os import time import uuid from concurrent.futures import ThreadPoolExecutor from email.message import Message from functools import wraps from smtplib import SMTP, SMTPException from typing import Optional, Dict, List, Callable import newrelic.agent from attr import dataclass from app import config from app.email import headers from app.log import LOG from app.message_utils import message_to_bytes, message_format_base64_parts class SendRequest: def to_bytes(self) -> bytes: def load_from_file(file_path: str) -> SendRequest: def load_from_bytes(data: bytes) -> SendRequest: def save_request_to_unsent_dir(self, prefix: str = "DeliveryFail"): def save_request_to_failed_dir(self, prefix: str = "DeliveryRetryFail"): def save_request_to_file(self, file_path: str): mail_sender = MailSender() def save_request_to_failed_dir(exception_name: str, send_request: SendRequest): LOG = _get_logger("SL") def load_unsent_mails_from_fs_and_resend(): if not config.SAVE_UNSENT_DIR: return for filename in os.listdir(config.SAVE_UNSENT_DIR): (_, extension) = os.path.splitext(filename) if extension[1:] != SendRequest.SAVE_EXTENSION: LOG.i(f"Skipping {filename} does not have the proper extension") continue full_file_path = os.path.join(config.SAVE_UNSENT_DIR, filename) if not os.path.isfile(full_file_path): LOG.i(f"Skipping {filename} as it's not a file") continue LOG.i(f"Trying to re-deliver email {filename}") try: send_request = SendRequest.load_from_file(full_file_path) send_request.retries += 1 except Exception as e: LOG.e(f"Cannot load {filename}. Error {e}") continue try: send_request.ignore_smtp_errors = True if mail_sender.send(send_request, 2): os.unlink(full_file_path) newrelic.agent.record_custom_event( "DeliverUnsentEmail", {"delivered": "true"} ) else: if send_request.retries > 2: os.unlink(full_file_path) send_request.save_request_to_failed_dir() else: send_request.save_request_to_file(full_file_path) newrelic.agent.record_custom_event( "DeliverUnsentEmail", {"delivered": "false"} ) except Exception as e: # Unlink original file to avoid re-doing the same os.unlink(full_file_path) LOG.e( "email sending failed with error:%s " "envelope %s -> %s, mail %s -> %s saved to %s", e, send_request.envelope_from, send_request.envelope_to, send_request.msg[headers.FROM], send_request.msg[headers.TO], save_request_to_failed_dir(e.__class__.__name__, send_request), )
null
180,662
from flask import request, redirect, url_for, flash, render_template, g from flask_login import login_user, current_user from app import email_utils from app.auth.base import auth_bp from app.db import Session from app.extensions import limiter from app.log import LOG from app.models import ActivationCode from app.utils import sanitize_next_url Session = scoped_session(sessionmaker(bind=connection)) Session: sqlalchemy.orm.Session LOG = _get_logger("SL") class ActivationCode(Base, ModelMixin): """For activate user account""" __tablename__ = "activation_code" user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False) code = sa.Column(sa.String(128), unique=True, nullable=False) user = orm.relationship(User) expired = sa.Column(ArrowType, nullable=False, default=_expiration_1h) def is_expired(self): return self.expired < arrow.now() def sanitize_next_url(url: Optional[str]) -> Optional[str]: return NextUrlSanitizer.sanitize(url, ALLOWED_REDIRECT_DOMAINS) def activate(): if current_user.is_authenticated: return ( render_template("auth/activate.html", error="You are already logged in"), 400, ) code = request.args.get("code") activation_code: ActivationCode = ActivationCode.get_by(code=code) if not activation_code: # Trigger rate limiter g.deduct_limit = True return ( render_template( "auth/activate.html", error="Activation code cannot be found" ), 400, ) if activation_code.is_expired(): return ( render_template( "auth/activate.html", error="Activation code was expired", show_resend_activation=True, ), 400, ) user = activation_code.user user.activated = True login_user(user) # activation code is to be used only once ActivationCode.delete(activation_code.id) Session.commit() flash("Your account has been activated", "success") email_utils.send_welcome_email(user) # The activation link contains the original page, for ex authorize page if "next" in request.args: next_url = sanitize_next_url(request.args.get("next")) 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")) # todo: redirect to account_activated page when more features are added into the browser extension # return redirect(url_for("onboarding.account_activated"))
null
180,663
from flask import request, session, redirect, flash, url_for from requests_oauthlib import OAuth2Session from app.auth.base import auth_bp from app.auth.views.login_utils import after_login from app.config import GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET, URL from app.db import Session from app.log import LOG from app.models import User, SocialAuth from app.utils import encode_url, sanitize_email, sanitize_next_url _authorization_base_url = "https://github.com/login/oauth/authorize" _redirect_uri = URL + "/auth/github/callback" GITHUB_CLIENT_ID = os.environ.get("GITHUB_CLIENT_ID") def encode_url(url): return urllib.parse.quote(url, safe="") def sanitize_next_url(url: Optional[str]) -> Optional[str]: return NextUrlSanitizer.sanitize(url, ALLOWED_REDIRECT_DOMAINS) def github_login(): next_url = sanitize_next_url(request.args.get("next")) if next_url: redirect_uri = _redirect_uri + "?next=" + encode_url(next_url) else: redirect_uri = _redirect_uri github = OAuth2Session( GITHUB_CLIENT_ID, scope=["user:email"], redirect_uri=redirect_uri ) authorization_url, state = github.authorization_url(_authorization_base_url) # State is used to prevent CSRF, keep this for later. session["oauth_state"] = state return redirect(authorization_url)
null
180,664
from flask import request, session, redirect, flash, url_for from requests_oauthlib import OAuth2Session from app.auth.base import auth_bp from app.auth.views.login_utils import after_login from app.config import GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET, URL from app.db import Session from app.log import LOG from app.models import User, SocialAuth from app.utils import encode_url, sanitize_email, sanitize_next_url _token_url = "https://github.com/login/oauth/access_token" _redirect_uri = URL + "/auth/github/callback" def after_login(user, next_url, login_from_proton: bool = False): """ Redirect to the correct page after login. If the user is logged in with Proton, do not look at fido nor otp If user enables MFA: redirect user to MFA page Otherwise redirect to dashboard page if no next_url """ if not login_from_proton: if user.fido_enabled(): # Use the same session for FIDO so that we can easily # switch between these two 2FA option session[MFA_USER_ID] = user.id if next_url: return redirect(url_for("auth.fido", next=next_url)) else: return redirect(url_for("auth.fido")) elif user.enable_otp: session[MFA_USER_ID] = user.id if next_url: return redirect(url_for("auth.mfa", next=next_url)) else: return redirect(url_for("auth.mfa")) LOG.d("log user %s in", user) login_user(user) session["sudo_time"] = int(time()) # User comes to login page from another page 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")) GITHUB_CLIENT_ID = os.environ.get("GITHUB_CLIENT_ID") GITHUB_CLIENT_SECRET = os.environ.get("GITHUB_CLIENT_SECRET") Session = scoped_session(sessionmaker(bind=connection)) Session: sqlalchemy.orm.Session LOG = _get_logger("SL") class User(Base, ModelMixin, UserMixin, PasswordOracle): __tablename__ = "users" FLAG_FREE_DISABLE_CREATE_ALIAS = 1 << 0 FLAG_CREATED_FROM_PARTNER = 1 << 1 FLAG_FREE_OLD_ALIAS_LIMIT = 1 << 2 email = sa.Column(sa.String(256), unique=True, nullable=False) name = sa.Column(sa.String(128), nullable=True) is_admin = sa.Column(sa.Boolean, nullable=False, default=False) alias_generator = sa.Column( sa.Integer, nullable=False, default=AliasGeneratorEnum.word.value, server_default=str(AliasGeneratorEnum.word.value), ) notification = sa.Column( sa.Boolean, default=True, nullable=False, server_default="1" ) activated = sa.Column(sa.Boolean, default=False, nullable=False, index=True) # an account can be disabled if having harmful behavior disabled = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0") profile_picture_id = sa.Column(sa.ForeignKey(File.id), nullable=True) otp_secret = sa.Column(sa.String(16), nullable=True) enable_otp = sa.Column( sa.Boolean, nullable=False, default=False, server_default="0" ) last_otp = sa.Column(sa.String(12), nullable=True, default=False) # Fields for WebAuthn fido_uuid = sa.Column(sa.String(), nullable=True, unique=True) # the default domain that's used when user creates a new random alias # default_alias_custom_domain_id XOR default_alias_public_domain_id default_alias_custom_domain_id = sa.Column( sa.ForeignKey("custom_domain.id", ondelete="SET NULL"), nullable=True, default=None, ) default_alias_public_domain_id = sa.Column( sa.ForeignKey("public_domain.id", ondelete="SET NULL"), nullable=True, default=None, ) # some users could have lifetime premium lifetime = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0") paid_lifetime = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) lifetime_coupon_id = sa.Column( sa.ForeignKey("lifetime_coupon.id", ondelete="SET NULL"), nullable=True, default=None, ) # user can use all premium features until this date trial_end = sa.Column( ArrowType, default=lambda: arrow.now().shift(days=7, hours=1), nullable=True ) # the mailbox used when create random alias # this field is nullable but in practice, it's always set # it cannot be set to non-nullable though # as this will create foreign key cycle between User and Mailbox default_mailbox_id = sa.Column( sa.ForeignKey("mailbox.id"), nullable=True, default=None ) profile_picture = orm.relationship(File, foreign_keys=[profile_picture_id]) # Specify the format for sender address # for the full list, see SenderFormatEnum sender_format = sa.Column( sa.Integer, default="0", nullable=False, server_default="0" ) # to know whether user has explicitly chosen a sender format as opposed to those who use the default ones. # users who haven't chosen a sender format and are using 1 or 3 format, their sender format will be set to 0 sender_format_updated_at = sa.Column(ArrowType, default=None) replace_reverse_alias = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) referral_id = sa.Column( sa.ForeignKey("referral.id", ondelete="SET NULL"), nullable=True, default=None, index=True, ) referral = orm.relationship("Referral", foreign_keys=[referral_id]) # whether intro has been shown to user intro_shown = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) default_mailbox = orm.relationship("Mailbox", foreign_keys=[default_mailbox_id]) # user can set a more strict max_spam score to block spams more aggressively max_spam_score = sa.Column(sa.Integer, nullable=True) # newsletter is sent to this address newsletter_alias_id = sa.Column( sa.ForeignKey("alias.id", ondelete="SET NULL"), nullable=True, default=None, index=True, ) # whether to include the sender address in reverse-alias include_sender_in_reverse_alias = sa.Column( sa.Boolean, default=True, nullable=False, server_default="0" ) # whether to use random string or random word as suffix # Random word from dictionary file -> 0 # Completely random string -> 1 random_alias_suffix = sa.Column( sa.Integer, nullable=False, default=AliasSuffixEnum.word.value, server_default=str(AliasSuffixEnum.random_string.value), ) # always expand the alias info, i.e. without needing to press "More" expand_alias_info = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # ignore emails send from a mailbox to its alias. This can happen when replying all to a forwarded email # can automatically re-includes the alias ignore_loop_email = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # used for flask-login as an "alternative token" # cf https://flask-login.readthedocs.io/en/latest/#alternative-tokens alternative_id = sa.Column(sa.String(128), unique=True, nullable=True) # by default, when an alias is automatically created, a note like "Created with ...." is created # If this field is True, the note won't be created. disable_automatic_alias_note = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # By default, the one-click unsubscribe disable the alias # If set to true, it will block the sender instead one_click_unsubscribe_block_sender = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # automatically include the website name when user creates an alias via the SimpleLogin icon in the email field include_website_in_one_click_alias = sa.Column( sa.Boolean, # new user will have this option turned on automatically default=True, nullable=False, # old user will have this option turned off server_default="0", ) _directory_quota = sa.Column( "directory_quota", sa.Integer, default=50, nullable=False, server_default="50" ) _subdomain_quota = sa.Column( "subdomain_quota", sa.Integer, default=5, nullable=False, server_default="5" ) # user can use import to import too many aliases disable_import = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # user can use the phone feature can_use_phone = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # in minutes phone_quota = sa.Column(sa.Integer, nullable=True) # Status code to return if is blocked block_behaviour = sa.Column( sa.Enum(BlockBehaviourEnum), nullable=False, server_default=BlockBehaviourEnum.return_2xx.name, ) include_header_email_header = sa.Column( sa.Boolean, default=True, nullable=False, server_default="1" ) # bitwise flags. Allow for future expansion flags = sa.Column( sa.BigInteger, default=FLAG_FREE_DISABLE_CREATE_ALIAS, server_default="0", nullable=False, ) # Keep original unsub behaviour unsub_behaviour = sa.Column( IntEnumType(UnsubscribeBehaviourEnum), default=UnsubscribeBehaviourEnum.PreserveOriginal, server_default=str(UnsubscribeBehaviourEnum.DisableAlias.value), nullable=False, ) # Trigger hard deletion of the account at this time delete_on = sa.Column(ArrowType, default=None) __table_args__ = ( sa.Index( "ix_users_activated_trial_end_lifetime", activated, trial_end, lifetime ), sa.Index("ix_users_delete_on", delete_on), ) def directory_quota(self): return min( self._directory_quota, config.MAX_NB_DIRECTORY - Directory.filter_by(user_id=self.id).count(), ) def subdomain_quota(self): return min( self._subdomain_quota, config.MAX_NB_SUBDOMAIN - CustomDomain.filter_by(user_id=self.id, is_sl_subdomain=True).count(), ) def created_by_partner(self): return User.FLAG_CREATED_FROM_PARTNER == ( self.flags & User.FLAG_CREATED_FROM_PARTNER ) def subdomain_is_available(): return SLDomain.filter_by(can_use_subdomain=True).count() > 0 # implement flask-login "alternative token" def get_id(self): if self.alternative_id: return self.alternative_id else: return str(self.id) def create(cls, email, name="", password=None, from_partner=False, **kwargs): email = sanitize_email(email) user: User = super(User, cls).create(email=email, name=name[:100], **kwargs) if password: user.set_password(password) Session.flush() mb = Mailbox.create(user_id=user.id, email=user.email, verified=True) Session.flush() user.default_mailbox_id = mb.id # generate an alternative_id if needed if "alternative_id" not in kwargs: user.alternative_id = str(uuid.uuid4()) # If the user is created from partner, do not notify # nor give a trial if from_partner: user.flags = User.FLAG_CREATED_FROM_PARTNER user.notification = False user.trial_end = None Job.create( name=config.JOB_SEND_PROTON_WELCOME_1, payload={"user_id": user.id}, run_at=arrow.now(), ) Session.flush() return user # create a first alias mail to show user how to use when they login alias = Alias.create_new( user, prefix="simplelogin-newsletter", mailbox_id=mb.id, note="This is your first alias. It's used to receive SimpleLogin communications " "like new features announcements, newsletters.", ) Session.flush() user.newsletter_alias_id = alias.id Session.flush() if config.DISABLE_ONBOARDING: LOG.d("Disable onboarding emails") return user # Schedule onboarding emails Job.create( name=config.JOB_ONBOARDING_1, payload={"user_id": user.id}, run_at=arrow.now().shift(days=1), ) Job.create( name=config.JOB_ONBOARDING_2, payload={"user_id": user.id}, run_at=arrow.now().shift(days=2), ) Job.create( name=config.JOB_ONBOARDING_4, payload={"user_id": user.id}, run_at=arrow.now().shift(days=3), ) Session.flush() return user def get_active_subscription( self, include_partner_subscription: bool = True ) -> Optional[ Union[ Subscription | AppleSubscription | ManualSubscription | CoinbaseSubscription | PartnerSubscription ] ]: sub: Subscription = self.get_paddle_subscription() if sub: return sub apple_sub: AppleSubscription = AppleSubscription.get_by(user_id=self.id) if apple_sub and apple_sub.is_valid(): return apple_sub manual_sub: ManualSubscription = ManualSubscription.get_by(user_id=self.id) if manual_sub and manual_sub.is_active(): return manual_sub coinbase_subscription: CoinbaseSubscription = CoinbaseSubscription.get_by( user_id=self.id ) if coinbase_subscription and coinbase_subscription.is_active(): return coinbase_subscription if include_partner_subscription: partner_sub: PartnerSubscription = PartnerSubscription.find_by_user_id( self.id ) if partner_sub and partner_sub.is_active(): return partner_sub return None def get_active_subscription_end( self, include_partner_subscription: bool = True ) -> Optional[arrow.Arrow]: sub = self.get_active_subscription( include_partner_subscription=include_partner_subscription ) if isinstance(sub, Subscription): return arrow.get(sub.next_bill_date) if isinstance(sub, AppleSubscription): return sub.expires_date if isinstance(sub, ManualSubscription): return sub.end_at if isinstance(sub, CoinbaseSubscription): return sub.end_at return None # region Billing def lifetime_or_active_subscription( self, include_partner_subscription: bool = True ) -> bool: """True if user has lifetime licence or active subscription""" if self.lifetime: return True return self.get_active_subscription(include_partner_subscription) is not None def is_paid(self) -> bool: """same as _lifetime_or_active_subscription but not include free manual subscription""" sub = self.get_active_subscription() if sub is None: return False if isinstance(sub, ManualSubscription) and sub.is_giveaway: return False return True def is_active(self) -> bool: if self.delete_on is None: return True return self.delete_on < arrow.now() def in_trial(self): """return True if user does not have lifetime licence or an active subscription AND is in trial period""" if self.lifetime_or_active_subscription(): return False if self.trial_end and arrow.now() < self.trial_end: return True return False def should_show_upgrade_button(self): if self.lifetime_or_active_subscription(): return False return True def is_premium(self, include_partner_subscription: bool = True) -> bool: """ user is premium if they: - have a lifetime deal or - in trial period or - active subscription """ if self.lifetime_or_active_subscription(include_partner_subscription): return True if self.trial_end and arrow.now() < self.trial_end: return True return False def upgrade_channel(self) -> str: """Used on admin dashboard""" # user can have multiple subscription channel channels = [] if self.lifetime: channels.append("Lifetime") sub: Subscription = self.get_paddle_subscription() if sub: if sub.cancelled: channels.append( f"""Cancelled Paddle Subscription <a href="https://vendors.paddle.com/subscriptions/customers/manage/{sub.subscription_id}">{sub.subscription_id}</a> {sub.plan_name()} ends at {sub.next_bill_date}""" ) else: channels.append( f"""Active Paddle Subscription <a href="https://vendors.paddle.com/subscriptions/customers/manage/{sub.subscription_id}">{sub.subscription_id}</a> {sub.plan_name()}, renews at {sub.next_bill_date}""" ) apple_sub: AppleSubscription = AppleSubscription.get_by(user_id=self.id) if apple_sub and apple_sub.is_valid(): channels.append(f"Apple Subscription {apple_sub.expires_date.humanize()}") manual_sub: ManualSubscription = ManualSubscription.get_by(user_id=self.id) if manual_sub and manual_sub.is_active(): mode = "Giveaway" if manual_sub.is_giveaway else "Paid" channels.append( f"Manual Subscription {manual_sub.comment} {mode} {manual_sub.end_at.humanize()}" ) coinbase_subscription: CoinbaseSubscription = CoinbaseSubscription.get_by( user_id=self.id ) if coinbase_subscription and coinbase_subscription.is_active(): channels.append( f"Coinbase Subscription ends {coinbase_subscription.end_at.humanize()}" ) r = ( Session.query(PartnerSubscription, PartnerUser, Partner) .filter( PartnerSubscription.partner_user_id == PartnerUser.id, PartnerUser.user_id == self.id, Partner.id == PartnerUser.partner_id, ) .first() ) if r and r[0].is_active(): channels.append( f"Subscription via {r[2].name} partner , ends {r[0].end_at.humanize()}" ) return ".\n".join(channels) # endregion def max_alias_for_free_account(self) -> int: if ( self.FLAG_FREE_OLD_ALIAS_LIMIT == self.flags & self.FLAG_FREE_OLD_ALIAS_LIMIT ): return config.MAX_NB_EMAIL_OLD_FREE_PLAN else: return config.MAX_NB_EMAIL_FREE_PLAN def can_create_new_alias(self) -> bool: """ Whether user can create a new alias. User can't create a new alias if - has more than 15 aliases in the free plan, *even in the free trial* """ if not self.is_active(): return False if self.disabled: return False if self.lifetime_or_active_subscription(): return True else: return ( Alias.filter_by(user_id=self.id).count() < self.max_alias_for_free_account() ) def can_send_or_receive(self) -> bool: if self.disabled: LOG.i(f"User {self} is disabled. Cannot receive or send emails") return False if self.delete_on is not None: LOG.i( f"User {self} is scheduled to be deleted. Cannot receive or send emails" ) return False return True def profile_picture_url(self): if self.profile_picture_id: return self.profile_picture.get_url() else: return url_for("static", filename="default-avatar.png") def suggested_emails(self, website_name) -> (str, [str]): """return suggested email and other email choices""" website_name = convert_to_id(website_name) all_aliases = [ ge.email for ge in Alias.filter_by(user_id=self.id, enabled=True) ] if self.can_create_new_alias(): suggested_alias = Alias.create_new(self, prefix=website_name).email else: # pick an email from the list of gen emails suggested_alias = random.choice(all_aliases) return ( suggested_alias, list(set(all_aliases).difference({suggested_alias})), ) def suggested_names(self) -> (str, [str]): """return suggested name and other name choices""" other_name = convert_to_id(self.name) return self.name, [other_name, "Anonymous", "whoami"] def get_name_initial(self) -> str: if not self.name: return "" names = self.name.split(" ") return "".join([n[0].upper() for n in names if n]) def get_paddle_subscription(self) -> Optional["Subscription"]: """return *active* Paddle subscription Return None if the subscription is already expired TODO: support user unsubscribe and re-subscribe """ sub = Subscription.get_by(user_id=self.id) if sub: # grace period is 14 days # sub is active until the next billing_date + PADDLE_SUBSCRIPTION_GRACE_DAYS if ( sub.next_bill_date >= arrow.now().shift(days=-PADDLE_SUBSCRIPTION_GRACE_DAYS).date() ): return sub # past subscription, user is considered not having a subscription = free plan else: return None else: return sub def verified_custom_domains(self) -> List["CustomDomain"]: return ( CustomDomain.filter_by(user_id=self.id, ownership_verified=True) .order_by(CustomDomain.domain.asc()) .all() ) def mailboxes(self) -> List["Mailbox"]: """list of mailbox that user own""" mailboxes = [] for mailbox in Mailbox.filter_by(user_id=self.id, verified=True): mailboxes.append(mailbox) return mailboxes def nb_directory(self): return Directory.filter_by(user_id=self.id).count() def has_custom_domain(self): return CustomDomain.filter_by(user_id=self.id, verified=True).count() > 0 def custom_domains(self): return CustomDomain.filter_by(user_id=self.id, verified=True).all() def available_domains_for_random_alias( self, alias_options: Optional[AliasOptions] = None ) -> List[Tuple[bool, str]]: """Return available domains for user to create random aliases Each result record contains: - whether the domain belongs to SimpleLogin - the domain """ res = [] for domain in self.available_sl_domains(alias_options=alias_options): res.append((True, domain)) for custom_domain in self.verified_custom_domains(): res.append((False, custom_domain.domain)) return res def default_random_alias_domain(self) -> str: """return the domain used for the random alias""" if self.default_alias_custom_domain_id: custom_domain = CustomDomain.get(self.default_alias_custom_domain_id) # sanity check if ( not custom_domain or not custom_domain.verified or custom_domain.user_id != self.id ): LOG.w("Problem with %s default random alias domain", self) return config.FIRST_ALIAS_DOMAIN return custom_domain.domain if self.default_alias_public_domain_id: sl_domain = SLDomain.get(self.default_alias_public_domain_id) # sanity check if not sl_domain: LOG.e("Problem with %s public random alias domain", self) return config.FIRST_ALIAS_DOMAIN if sl_domain.premium_only and not self.is_premium(): LOG.w( "%s is not premium and cannot use %s. Reset default random alias domain setting", self, sl_domain, ) self.default_alias_custom_domain_id = None self.default_alias_public_domain_id = None Session.commit() return config.FIRST_ALIAS_DOMAIN return sl_domain.domain return config.FIRST_ALIAS_DOMAIN def fido_enabled(self) -> bool: if self.fido_uuid is not None: return True return False def two_factor_authentication_enabled(self) -> bool: return self.enable_otp or self.fido_enabled() def get_communication_email(self) -> (Optional[str], str, bool): """ Return - the email that user uses to receive email communication. None if user unsubscribes from newsletter - the unsubscribe URL - whether the unsubscribe method is via sending email (mailto:) or Http POST """ if self.notification and self.activated and not self.disabled: if self.newsletter_alias_id: alias = Alias.get(self.newsletter_alias_id) if alias.enabled: unsub = UnsubscribeEncoder.encode( UnsubscribeAction.DisableAlias, alias.id ) return alias.email, unsub.link, unsub.via_email # alias disabled -> user doesn't want to receive newsletter else: return None, "", False else: # do not handle http POST unsubscribe if config.UNSUBSCRIBER: # use * as suffix instead of = as for alias unsubscribe return ( self.email, UnsubscribeEncoder.encode_mailto( UnsubscribeAction.UnsubscribeNewsletter, self.id ), True, ) return None, "", False def available_sl_domains( self, alias_options: Optional[AliasOptions] = None ) -> [str]: """ Return all SimpleLogin domains that user can use when creating a new alias, including: - SimpleLogin public domains, available for all users (ALIAS_DOMAIN) - SimpleLogin premium domains, only available for Premium accounts (PREMIUM_ALIAS_DOMAIN) """ return [ sl_domain.domain for sl_domain in self.get_sl_domains(alias_options=alias_options) ] def get_sl_domains( self, alias_options: Optional[AliasOptions] = None ) -> list["SLDomain"]: if alias_options is None: alias_options = AliasOptions() top_conds = [SLDomain.hidden == False] # noqa: E712 or_conds = [] # noqa:E711 if self.default_alias_public_domain_id is not None: default_domain_conds = [SLDomain.id == self.default_alias_public_domain_id] if not self.is_premium(): default_domain_conds.append( SLDomain.premium_only == False # noqa: E712 ) or_conds.append(and_(*default_domain_conds).self_group()) if alias_options.show_partner_domains is not None: partner_user = PartnerUser.filter_by( user_id=self.id, partner_id=alias_options.show_partner_domains.id ).first() if partner_user is not None: partner_domain_cond = [SLDomain.partner_id == partner_user.partner_id] if alias_options.show_partner_premium is None: alias_options.show_partner_premium = self.is_premium() if not alias_options.show_partner_premium: partner_domain_cond.append( SLDomain.premium_only == False # noqa: E712 ) or_conds.append(and_(*partner_domain_cond).self_group()) if alias_options.show_sl_domains: sl_conds = [SLDomain.partner_id == None] # noqa: E711 if not self.is_premium(): sl_conds.append(SLDomain.premium_only == False) # noqa: E712 or_conds.append(and_(*sl_conds).self_group()) top_conds.append(or_(*or_conds)) query = Session.query(SLDomain).filter(*top_conds).order_by(SLDomain.order) return query.all() def available_alias_domains( self, alias_options: Optional[AliasOptions] = None ) -> [str]: """return all domains that user can use when creating a new alias, including: - SimpleLogin public domains, available for all users (ALIAS_DOMAIN) - SimpleLogin premium domains, only available for Premium accounts (PREMIUM_ALIAS_DOMAIN) - Verified custom domains """ domains = self.available_sl_domains(alias_options=alias_options) for custom_domain in self.verified_custom_domains(): domains.append(custom_domain.domain) # can have duplicate where a "root" user has a domain that's also listed in SL domains return list(set(domains)) def should_show_app_page(self) -> bool: """whether to show the app page""" return ( # when user has used the "Sign in with SL" button before ClientUser.filter(ClientUser.user_id == self.id).count() # or when user has created an app + Client.filter(Client.user_id == self.id).count() > 0 ) def get_random_alias_suffix(self, custom_domain: Optional["CustomDomain"] = None): """Get random suffix for an alias based on user's preference. Use a shorter suffix in case of custom domain Returns: str: the random suffix generated """ if self.random_alias_suffix == AliasSuffixEnum.random_string.value: return random_string(config.ALIAS_RANDOM_SUFFIX_LENGTH, include_digits=True) if custom_domain is None: return random_words(1, 3) return random_words(1) def can_create_contacts(self) -> bool: if self.is_premium(): return True if self.flags & User.FLAG_FREE_DISABLE_CREATE_ALIAS == 0: return True return not config.DISABLE_CREATE_CONTACTS_FOR_FREE_USERS def __repr__(self): return f"<User {self.id} {self.name} {self.email}>" class 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"),) def sanitize_email(email_address: str, not_lower=False) -> str: if email_address: email_address = email_address.strip().replace(" ", "").replace("\n", " ") if not not_lower: email_address = email_address.lower() return email_address.replace("\u200f", "") def sanitize_next_url(url: Optional[str]) -> Optional[str]: return NextUrlSanitizer.sanitize(url, ALLOWED_REDIRECT_DOMAINS) def github_callback(): # user clicks on cancel if "error" in request.args: flash("Please use another sign in method then", "warning") return redirect("/") github = OAuth2Session( GITHUB_CLIENT_ID, state=session["oauth_state"], scope=["user:email"], redirect_uri=_redirect_uri, ) github.fetch_token( _token_url, client_secret=GITHUB_CLIENT_SECRET, authorization_response=request.url, ) # a dict with "name", "login" github_user_data = github.get("https://api.github.com/user").json() # return list of emails # { # 'email': 'abcd@gmail.com', # 'primary': False, # 'verified': True, # 'visibility': None # } emails = github.get("https://api.github.com/user/emails").json() # only take the primary email email = None for e in emails: if e.get("verified") and e.get("primary"): email = e.get("email") break if not email: LOG.e(f"cannot get email for github user {github_user_data} {emails}") flash( "Cannot get a valid email from Github, please another way to login/sign up", "error", ) return redirect(url_for("auth.login")) email = sanitize_email(email) user = User.get_by(email=email) if not user: flash( "Sorry you cannot sign up via Github, please use email/password sign-up instead", "error", ) return redirect(url_for("auth.register")) if not SocialAuth.get_by(user_id=user.id, social="github"): SocialAuth.create(user_id=user.id, social="github") Session.commit() # The activation link contains the original page, for ex authorize page next_url = sanitize_next_url(request.args.get("next")) if request.args else None return after_login(user, next_url)
null
180,665
from flask import request, flash, render_template, redirect, url_for from flask_wtf import FlaskForm from wtforms import StringField, validators from app.auth.base import auth_bp from app.auth.views.register import send_activation_email from app.extensions import limiter from app.log import LOG from app.models import User from app.utils import sanitize_email, canonicalize_email class ResendActivationForm(FlaskForm): def send_activation_email(user, next_url): LOG = _get_logger("SL") class User(Base, ModelMixin, UserMixin, PasswordOracle): def directory_quota(self): def subdomain_quota(self): def created_by_partner(self): def subdomain_is_available(): def get_id(self): def create(cls, email, name="", password=None, from_partner=False, **kwargs): def get_active_subscription( self, include_partner_subscription: bool = True ) -> Optional[ Union[ Subscription | AppleSubscription | ManualSubscription | CoinbaseSubscription | PartnerSubscription ] ]: def get_active_subscription_end( self, include_partner_subscription: bool = True ) -> Optional[arrow.Arrow]: def lifetime_or_active_subscription( self, include_partner_subscription: bool = True ) -> bool: def is_paid(self) -> bool: def is_active(self) -> bool: def in_trial(self): def should_show_upgrade_button(self): def is_premium(self, include_partner_subscription: bool = True) -> bool: def upgrade_channel(self) -> str: def max_alias_for_free_account(self) -> int: def can_create_new_alias(self) -> bool: def can_send_or_receive(self) -> bool: def profile_picture_url(self): def suggested_emails(self, website_name) -> (str, [str]): def suggested_names(self) -> (str, [str]): def get_name_initial(self) -> str: def get_paddle_subscription(self) -> Optional["Subscription"]: def verified_custom_domains(self) -> List["CustomDomain"]: def mailboxes(self) -> List["Mailbox"]: def nb_directory(self): def has_custom_domain(self): def custom_domains(self): def available_domains_for_random_alias( self, alias_options: Optional[AliasOptions] = None ) -> List[Tuple[bool, str]]: def default_random_alias_domain(self) -> str: def fido_enabled(self) -> bool: def two_factor_authentication_enabled(self) -> bool: def get_communication_email(self) -> (Optional[str], str, bool): def available_sl_domains( self, alias_options: Optional[AliasOptions] = None ) -> [str]: def get_sl_domains( self, alias_options: Optional[AliasOptions] = None ) -> list["SLDomain"]: def available_alias_domains( self, alias_options: Optional[AliasOptions] = None ) -> [str]: def should_show_app_page(self) -> bool: def get_random_alias_suffix(self, custom_domain: Optional["CustomDomain"] = None): def can_create_contacts(self) -> bool: def __repr__(self): def canonicalize_email(email_address: str) -> str: def sanitize_email(email_address: str, not_lower=False) -> str: def resend_activation(): form = ResendActivationForm(request.form) if form.validate_on_submit(): email = sanitize_email(form.email.data) canonical_email = canonicalize_email(email) user = User.get_by(email=email) or User.get_by(email=canonical_email) if not user: flash("There is no such email", "warning") return render_template("auth/resend_activation.html", form=form) if user.activated: flash("Your account was already activated, please login", "success") return redirect(url_for("auth.login")) # user is not activated LOG.d("user %s is not activated", user) flash( "An activation email has been sent to you. Please check your inbox/spam folder.", "warning", ) send_activation_email(user, request.args.get("next")) return render_template("auth/register_waiting_activation.html") return render_template("auth/resend_activation.html", form=form)
null
180,666
from flask import redirect, url_for, flash, make_response from app.auth.base import auth_bp from app.config import SESSION_COOKIE_NAME from app.session import logout_session SESSION_COOKIE_NAME = "slapp" def logout_session(): logout_user() purge_fn = getattr(current_app.session_interface, "purge_session", None) if callable(purge_fn): purge_fn(session) def logout(): logout_session() flash("You are logged out", "success") response = make_response(redirect(url_for("auth.login"))) response.delete_cookie(SESSION_COOKIE_NAME) response.delete_cookie("mfa") response.delete_cookie("dark-mode") return response
null
180,667
from flask import request, session, redirect, flash, url_for from requests_oauthlib import OAuth2Session from app import s3 from app.auth.base import auth_bp from app.config import URL, GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET from app.db import Session from app.log import LOG from app.models import User, File, SocialAuth from app.utils import random_string, sanitize_email, sanitize_next_url from .login_utils import after_login _authorization_base_url = "https://accounts.google.com/o/oauth2/v2/auth" _scope = [ "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile", "openid", ] _redirect_uri = URL + "/auth/google/callback" GOOGLE_CLIENT_ID = os.environ.get("GOOGLE_CLIENT_ID") def sanitize_next_url(url: Optional[str]) -> Optional[str]: return NextUrlSanitizer.sanitize(url, ALLOWED_REDIRECT_DOMAINS) def google_login(): # to avoid flask-login displaying the login error message session.pop("_flashes", None) next_url = sanitize_next_url(request.args.get("next")) # Google does not allow to append param to redirect_url # we need to pass the next url by session if next_url: session["google_next_url"] = next_url google = OAuth2Session(GOOGLE_CLIENT_ID, scope=_scope, redirect_uri=_redirect_uri) authorization_url, state = google.authorization_url(_authorization_base_url) # State is used to prevent CSRF, keep this for later. session["oauth_state"] = state return redirect(authorization_url)
null
180,668
from flask import request, session, redirect, flash, url_for from requests_oauthlib import OAuth2Session from app import s3 from app.auth.base import auth_bp from app.config import URL, GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET from app.db import Session from app.log import LOG from app.models import User, File, SocialAuth from app.utils import random_string, sanitize_email, sanitize_next_url from .login_utils import after_login _token_url = "https://www.googleapis.com/oauth2/v4/token" _scope = [ "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile", "openid", ] _redirect_uri = URL + "/auth/google/callback" def create_file_from_url(user, url) -> File: file_path = random_string(30) file = File.create(path=file_path, user_id=user.id) s3.upload_from_url(url, file_path) Session.flush() LOG.d("upload file %s to s3", file) return file GOOGLE_CLIENT_ID = os.environ.get("GOOGLE_CLIENT_ID") GOOGLE_CLIENT_SECRET = os.environ.get("GOOGLE_CLIENT_SECRET") Session = scoped_session(sessionmaker(bind=connection)) Session: sqlalchemy.orm.Session LOG = _get_logger("SL") class User(Base, ModelMixin, UserMixin, PasswordOracle): __tablename__ = "users" FLAG_FREE_DISABLE_CREATE_ALIAS = 1 << 0 FLAG_CREATED_FROM_PARTNER = 1 << 1 FLAG_FREE_OLD_ALIAS_LIMIT = 1 << 2 email = sa.Column(sa.String(256), unique=True, nullable=False) name = sa.Column(sa.String(128), nullable=True) is_admin = sa.Column(sa.Boolean, nullable=False, default=False) alias_generator = sa.Column( sa.Integer, nullable=False, default=AliasGeneratorEnum.word.value, server_default=str(AliasGeneratorEnum.word.value), ) notification = sa.Column( sa.Boolean, default=True, nullable=False, server_default="1" ) activated = sa.Column(sa.Boolean, default=False, nullable=False, index=True) # an account can be disabled if having harmful behavior disabled = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0") profile_picture_id = sa.Column(sa.ForeignKey(File.id), nullable=True) otp_secret = sa.Column(sa.String(16), nullable=True) enable_otp = sa.Column( sa.Boolean, nullable=False, default=False, server_default="0" ) last_otp = sa.Column(sa.String(12), nullable=True, default=False) # Fields for WebAuthn fido_uuid = sa.Column(sa.String(), nullable=True, unique=True) # the default domain that's used when user creates a new random alias # default_alias_custom_domain_id XOR default_alias_public_domain_id default_alias_custom_domain_id = sa.Column( sa.ForeignKey("custom_domain.id", ondelete="SET NULL"), nullable=True, default=None, ) default_alias_public_domain_id = sa.Column( sa.ForeignKey("public_domain.id", ondelete="SET NULL"), nullable=True, default=None, ) # some users could have lifetime premium lifetime = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0") paid_lifetime = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) lifetime_coupon_id = sa.Column( sa.ForeignKey("lifetime_coupon.id", ondelete="SET NULL"), nullable=True, default=None, ) # user can use all premium features until this date trial_end = sa.Column( ArrowType, default=lambda: arrow.now().shift(days=7, hours=1), nullable=True ) # the mailbox used when create random alias # this field is nullable but in practice, it's always set # it cannot be set to non-nullable though # as this will create foreign key cycle between User and Mailbox default_mailbox_id = sa.Column( sa.ForeignKey("mailbox.id"), nullable=True, default=None ) profile_picture = orm.relationship(File, foreign_keys=[profile_picture_id]) # Specify the format for sender address # for the full list, see SenderFormatEnum sender_format = sa.Column( sa.Integer, default="0", nullable=False, server_default="0" ) # to know whether user has explicitly chosen a sender format as opposed to those who use the default ones. # users who haven't chosen a sender format and are using 1 or 3 format, their sender format will be set to 0 sender_format_updated_at = sa.Column(ArrowType, default=None) replace_reverse_alias = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) referral_id = sa.Column( sa.ForeignKey("referral.id", ondelete="SET NULL"), nullable=True, default=None, index=True, ) referral = orm.relationship("Referral", foreign_keys=[referral_id]) # whether intro has been shown to user intro_shown = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) default_mailbox = orm.relationship("Mailbox", foreign_keys=[default_mailbox_id]) # user can set a more strict max_spam score to block spams more aggressively max_spam_score = sa.Column(sa.Integer, nullable=True) # newsletter is sent to this address newsletter_alias_id = sa.Column( sa.ForeignKey("alias.id", ondelete="SET NULL"), nullable=True, default=None, index=True, ) # whether to include the sender address in reverse-alias include_sender_in_reverse_alias = sa.Column( sa.Boolean, default=True, nullable=False, server_default="0" ) # whether to use random string or random word as suffix # Random word from dictionary file -> 0 # Completely random string -> 1 random_alias_suffix = sa.Column( sa.Integer, nullable=False, default=AliasSuffixEnum.word.value, server_default=str(AliasSuffixEnum.random_string.value), ) # always expand the alias info, i.e. without needing to press "More" expand_alias_info = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # ignore emails send from a mailbox to its alias. This can happen when replying all to a forwarded email # can automatically re-includes the alias ignore_loop_email = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # used for flask-login as an "alternative token" # cf https://flask-login.readthedocs.io/en/latest/#alternative-tokens alternative_id = sa.Column(sa.String(128), unique=True, nullable=True) # by default, when an alias is automatically created, a note like "Created with ...." is created # If this field is True, the note won't be created. disable_automatic_alias_note = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # By default, the one-click unsubscribe disable the alias # If set to true, it will block the sender instead one_click_unsubscribe_block_sender = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # automatically include the website name when user creates an alias via the SimpleLogin icon in the email field include_website_in_one_click_alias = sa.Column( sa.Boolean, # new user will have this option turned on automatically default=True, nullable=False, # old user will have this option turned off server_default="0", ) _directory_quota = sa.Column( "directory_quota", sa.Integer, default=50, nullable=False, server_default="50" ) _subdomain_quota = sa.Column( "subdomain_quota", sa.Integer, default=5, nullable=False, server_default="5" ) # user can use import to import too many aliases disable_import = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # user can use the phone feature can_use_phone = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # in minutes phone_quota = sa.Column(sa.Integer, nullable=True) # Status code to return if is blocked block_behaviour = sa.Column( sa.Enum(BlockBehaviourEnum), nullable=False, server_default=BlockBehaviourEnum.return_2xx.name, ) include_header_email_header = sa.Column( sa.Boolean, default=True, nullable=False, server_default="1" ) # bitwise flags. Allow for future expansion flags = sa.Column( sa.BigInteger, default=FLAG_FREE_DISABLE_CREATE_ALIAS, server_default="0", nullable=False, ) # Keep original unsub behaviour unsub_behaviour = sa.Column( IntEnumType(UnsubscribeBehaviourEnum), default=UnsubscribeBehaviourEnum.PreserveOriginal, server_default=str(UnsubscribeBehaviourEnum.DisableAlias.value), nullable=False, ) # Trigger hard deletion of the account at this time delete_on = sa.Column(ArrowType, default=None) __table_args__ = ( sa.Index( "ix_users_activated_trial_end_lifetime", activated, trial_end, lifetime ), sa.Index("ix_users_delete_on", delete_on), ) def directory_quota(self): return min( self._directory_quota, config.MAX_NB_DIRECTORY - Directory.filter_by(user_id=self.id).count(), ) def subdomain_quota(self): return min( self._subdomain_quota, config.MAX_NB_SUBDOMAIN - CustomDomain.filter_by(user_id=self.id, is_sl_subdomain=True).count(), ) def created_by_partner(self): return User.FLAG_CREATED_FROM_PARTNER == ( self.flags & User.FLAG_CREATED_FROM_PARTNER ) def subdomain_is_available(): return SLDomain.filter_by(can_use_subdomain=True).count() > 0 # implement flask-login "alternative token" def get_id(self): if self.alternative_id: return self.alternative_id else: return str(self.id) def create(cls, email, name="", password=None, from_partner=False, **kwargs): email = sanitize_email(email) user: User = super(User, cls).create(email=email, name=name[:100], **kwargs) if password: user.set_password(password) Session.flush() mb = Mailbox.create(user_id=user.id, email=user.email, verified=True) Session.flush() user.default_mailbox_id = mb.id # generate an alternative_id if needed if "alternative_id" not in kwargs: user.alternative_id = str(uuid.uuid4()) # If the user is created from partner, do not notify # nor give a trial if from_partner: user.flags = User.FLAG_CREATED_FROM_PARTNER user.notification = False user.trial_end = None Job.create( name=config.JOB_SEND_PROTON_WELCOME_1, payload={"user_id": user.id}, run_at=arrow.now(), ) Session.flush() return user # create a first alias mail to show user how to use when they login alias = Alias.create_new( user, prefix="simplelogin-newsletter", mailbox_id=mb.id, note="This is your first alias. It's used to receive SimpleLogin communications " "like new features announcements, newsletters.", ) Session.flush() user.newsletter_alias_id = alias.id Session.flush() if config.DISABLE_ONBOARDING: LOG.d("Disable onboarding emails") return user # Schedule onboarding emails Job.create( name=config.JOB_ONBOARDING_1, payload={"user_id": user.id}, run_at=arrow.now().shift(days=1), ) Job.create( name=config.JOB_ONBOARDING_2, payload={"user_id": user.id}, run_at=arrow.now().shift(days=2), ) Job.create( name=config.JOB_ONBOARDING_4, payload={"user_id": user.id}, run_at=arrow.now().shift(days=3), ) Session.flush() return user def get_active_subscription( self, include_partner_subscription: bool = True ) -> Optional[ Union[ Subscription | AppleSubscription | ManualSubscription | CoinbaseSubscription | PartnerSubscription ] ]: sub: Subscription = self.get_paddle_subscription() if sub: return sub apple_sub: AppleSubscription = AppleSubscription.get_by(user_id=self.id) if apple_sub and apple_sub.is_valid(): return apple_sub manual_sub: ManualSubscription = ManualSubscription.get_by(user_id=self.id) if manual_sub and manual_sub.is_active(): return manual_sub coinbase_subscription: CoinbaseSubscription = CoinbaseSubscription.get_by( user_id=self.id ) if coinbase_subscription and coinbase_subscription.is_active(): return coinbase_subscription if include_partner_subscription: partner_sub: PartnerSubscription = PartnerSubscription.find_by_user_id( self.id ) if partner_sub and partner_sub.is_active(): return partner_sub return None def get_active_subscription_end( self, include_partner_subscription: bool = True ) -> Optional[arrow.Arrow]: sub = self.get_active_subscription( include_partner_subscription=include_partner_subscription ) if isinstance(sub, Subscription): return arrow.get(sub.next_bill_date) if isinstance(sub, AppleSubscription): return sub.expires_date if isinstance(sub, ManualSubscription): return sub.end_at if isinstance(sub, CoinbaseSubscription): return sub.end_at return None # region Billing def lifetime_or_active_subscription( self, include_partner_subscription: bool = True ) -> bool: """True if user has lifetime licence or active subscription""" if self.lifetime: return True return self.get_active_subscription(include_partner_subscription) is not None def is_paid(self) -> bool: """same as _lifetime_or_active_subscription but not include free manual subscription""" sub = self.get_active_subscription() if sub is None: return False if isinstance(sub, ManualSubscription) and sub.is_giveaway: return False return True def is_active(self) -> bool: if self.delete_on is None: return True return self.delete_on < arrow.now() def in_trial(self): """return True if user does not have lifetime licence or an active subscription AND is in trial period""" if self.lifetime_or_active_subscription(): return False if self.trial_end and arrow.now() < self.trial_end: return True return False def should_show_upgrade_button(self): if self.lifetime_or_active_subscription(): return False return True def is_premium(self, include_partner_subscription: bool = True) -> bool: """ user is premium if they: - have a lifetime deal or - in trial period or - active subscription """ if self.lifetime_or_active_subscription(include_partner_subscription): return True if self.trial_end and arrow.now() < self.trial_end: return True return False def upgrade_channel(self) -> str: """Used on admin dashboard""" # user can have multiple subscription channel channels = [] if self.lifetime: channels.append("Lifetime") sub: Subscription = self.get_paddle_subscription() if sub: if sub.cancelled: channels.append( f"""Cancelled Paddle Subscription <a href="https://vendors.paddle.com/subscriptions/customers/manage/{sub.subscription_id}">{sub.subscription_id}</a> {sub.plan_name()} ends at {sub.next_bill_date}""" ) else: channels.append( f"""Active Paddle Subscription <a href="https://vendors.paddle.com/subscriptions/customers/manage/{sub.subscription_id}">{sub.subscription_id}</a> {sub.plan_name()}, renews at {sub.next_bill_date}""" ) apple_sub: AppleSubscription = AppleSubscription.get_by(user_id=self.id) if apple_sub and apple_sub.is_valid(): channels.append(f"Apple Subscription {apple_sub.expires_date.humanize()}") manual_sub: ManualSubscription = ManualSubscription.get_by(user_id=self.id) if manual_sub and manual_sub.is_active(): mode = "Giveaway" if manual_sub.is_giveaway else "Paid" channels.append( f"Manual Subscription {manual_sub.comment} {mode} {manual_sub.end_at.humanize()}" ) coinbase_subscription: CoinbaseSubscription = CoinbaseSubscription.get_by( user_id=self.id ) if coinbase_subscription and coinbase_subscription.is_active(): channels.append( f"Coinbase Subscription ends {coinbase_subscription.end_at.humanize()}" ) r = ( Session.query(PartnerSubscription, PartnerUser, Partner) .filter( PartnerSubscription.partner_user_id == PartnerUser.id, PartnerUser.user_id == self.id, Partner.id == PartnerUser.partner_id, ) .first() ) if r and r[0].is_active(): channels.append( f"Subscription via {r[2].name} partner , ends {r[0].end_at.humanize()}" ) return ".\n".join(channels) # endregion def max_alias_for_free_account(self) -> int: if ( self.FLAG_FREE_OLD_ALIAS_LIMIT == self.flags & self.FLAG_FREE_OLD_ALIAS_LIMIT ): return config.MAX_NB_EMAIL_OLD_FREE_PLAN else: return config.MAX_NB_EMAIL_FREE_PLAN def can_create_new_alias(self) -> bool: """ Whether user can create a new alias. User can't create a new alias if - has more than 15 aliases in the free plan, *even in the free trial* """ if not self.is_active(): return False if self.disabled: return False if self.lifetime_or_active_subscription(): return True else: return ( Alias.filter_by(user_id=self.id).count() < self.max_alias_for_free_account() ) def can_send_or_receive(self) -> bool: if self.disabled: LOG.i(f"User {self} is disabled. Cannot receive or send emails") return False if self.delete_on is not None: LOG.i( f"User {self} is scheduled to be deleted. Cannot receive or send emails" ) return False return True def profile_picture_url(self): if self.profile_picture_id: return self.profile_picture.get_url() else: return url_for("static", filename="default-avatar.png") def suggested_emails(self, website_name) -> (str, [str]): """return suggested email and other email choices""" website_name = convert_to_id(website_name) all_aliases = [ ge.email for ge in Alias.filter_by(user_id=self.id, enabled=True) ] if self.can_create_new_alias(): suggested_alias = Alias.create_new(self, prefix=website_name).email else: # pick an email from the list of gen emails suggested_alias = random.choice(all_aliases) return ( suggested_alias, list(set(all_aliases).difference({suggested_alias})), ) def suggested_names(self) -> (str, [str]): """return suggested name and other name choices""" other_name = convert_to_id(self.name) return self.name, [other_name, "Anonymous", "whoami"] def get_name_initial(self) -> str: if not self.name: return "" names = self.name.split(" ") return "".join([n[0].upper() for n in names if n]) def get_paddle_subscription(self) -> Optional["Subscription"]: """return *active* Paddle subscription Return None if the subscription is already expired TODO: support user unsubscribe and re-subscribe """ sub = Subscription.get_by(user_id=self.id) if sub: # grace period is 14 days # sub is active until the next billing_date + PADDLE_SUBSCRIPTION_GRACE_DAYS if ( sub.next_bill_date >= arrow.now().shift(days=-PADDLE_SUBSCRIPTION_GRACE_DAYS).date() ): return sub # past subscription, user is considered not having a subscription = free plan else: return None else: return sub def verified_custom_domains(self) -> List["CustomDomain"]: return ( CustomDomain.filter_by(user_id=self.id, ownership_verified=True) .order_by(CustomDomain.domain.asc()) .all() ) def mailboxes(self) -> List["Mailbox"]: """list of mailbox that user own""" mailboxes = [] for mailbox in Mailbox.filter_by(user_id=self.id, verified=True): mailboxes.append(mailbox) return mailboxes def nb_directory(self): return Directory.filter_by(user_id=self.id).count() def has_custom_domain(self): return CustomDomain.filter_by(user_id=self.id, verified=True).count() > 0 def custom_domains(self): return CustomDomain.filter_by(user_id=self.id, verified=True).all() def available_domains_for_random_alias( self, alias_options: Optional[AliasOptions] = None ) -> List[Tuple[bool, str]]: """Return available domains for user to create random aliases Each result record contains: - whether the domain belongs to SimpleLogin - the domain """ res = [] for domain in self.available_sl_domains(alias_options=alias_options): res.append((True, domain)) for custom_domain in self.verified_custom_domains(): res.append((False, custom_domain.domain)) return res def default_random_alias_domain(self) -> str: """return the domain used for the random alias""" if self.default_alias_custom_domain_id: custom_domain = CustomDomain.get(self.default_alias_custom_domain_id) # sanity check if ( not custom_domain or not custom_domain.verified or custom_domain.user_id != self.id ): LOG.w("Problem with %s default random alias domain", self) return config.FIRST_ALIAS_DOMAIN return custom_domain.domain if self.default_alias_public_domain_id: sl_domain = SLDomain.get(self.default_alias_public_domain_id) # sanity check if not sl_domain: LOG.e("Problem with %s public random alias domain", self) return config.FIRST_ALIAS_DOMAIN if sl_domain.premium_only and not self.is_premium(): LOG.w( "%s is not premium and cannot use %s. Reset default random alias domain setting", self, sl_domain, ) self.default_alias_custom_domain_id = None self.default_alias_public_domain_id = None Session.commit() return config.FIRST_ALIAS_DOMAIN return sl_domain.domain return config.FIRST_ALIAS_DOMAIN def fido_enabled(self) -> bool: if self.fido_uuid is not None: return True return False def two_factor_authentication_enabled(self) -> bool: return self.enable_otp or self.fido_enabled() def get_communication_email(self) -> (Optional[str], str, bool): """ Return - the email that user uses to receive email communication. None if user unsubscribes from newsletter - the unsubscribe URL - whether the unsubscribe method is via sending email (mailto:) or Http POST """ if self.notification and self.activated and not self.disabled: if self.newsletter_alias_id: alias = Alias.get(self.newsletter_alias_id) if alias.enabled: unsub = UnsubscribeEncoder.encode( UnsubscribeAction.DisableAlias, alias.id ) return alias.email, unsub.link, unsub.via_email # alias disabled -> user doesn't want to receive newsletter else: return None, "", False else: # do not handle http POST unsubscribe if config.UNSUBSCRIBER: # use * as suffix instead of = as for alias unsubscribe return ( self.email, UnsubscribeEncoder.encode_mailto( UnsubscribeAction.UnsubscribeNewsletter, self.id ), True, ) return None, "", False def available_sl_domains( self, alias_options: Optional[AliasOptions] = None ) -> [str]: """ Return all SimpleLogin domains that user can use when creating a new alias, including: - SimpleLogin public domains, available for all users (ALIAS_DOMAIN) - SimpleLogin premium domains, only available for Premium accounts (PREMIUM_ALIAS_DOMAIN) """ return [ sl_domain.domain for sl_domain in self.get_sl_domains(alias_options=alias_options) ] def get_sl_domains( self, alias_options: Optional[AliasOptions] = None ) -> list["SLDomain"]: if alias_options is None: alias_options = AliasOptions() top_conds = [SLDomain.hidden == False] # noqa: E712 or_conds = [] # noqa:E711 if self.default_alias_public_domain_id is not None: default_domain_conds = [SLDomain.id == self.default_alias_public_domain_id] if not self.is_premium(): default_domain_conds.append( SLDomain.premium_only == False # noqa: E712 ) or_conds.append(and_(*default_domain_conds).self_group()) if alias_options.show_partner_domains is not None: partner_user = PartnerUser.filter_by( user_id=self.id, partner_id=alias_options.show_partner_domains.id ).first() if partner_user is not None: partner_domain_cond = [SLDomain.partner_id == partner_user.partner_id] if alias_options.show_partner_premium is None: alias_options.show_partner_premium = self.is_premium() if not alias_options.show_partner_premium: partner_domain_cond.append( SLDomain.premium_only == False # noqa: E712 ) or_conds.append(and_(*partner_domain_cond).self_group()) if alias_options.show_sl_domains: sl_conds = [SLDomain.partner_id == None] # noqa: E711 if not self.is_premium(): sl_conds.append(SLDomain.premium_only == False) # noqa: E712 or_conds.append(and_(*sl_conds).self_group()) top_conds.append(or_(*or_conds)) query = Session.query(SLDomain).filter(*top_conds).order_by(SLDomain.order) return query.all() def available_alias_domains( self, alias_options: Optional[AliasOptions] = None ) -> [str]: """return all domains that user can use when creating a new alias, including: - SimpleLogin public domains, available for all users (ALIAS_DOMAIN) - SimpleLogin premium domains, only available for Premium accounts (PREMIUM_ALIAS_DOMAIN) - Verified custom domains """ domains = self.available_sl_domains(alias_options=alias_options) for custom_domain in self.verified_custom_domains(): domains.append(custom_domain.domain) # can have duplicate where a "root" user has a domain that's also listed in SL domains return list(set(domains)) def should_show_app_page(self) -> bool: """whether to show the app page""" return ( # when user has used the "Sign in with SL" button before ClientUser.filter(ClientUser.user_id == self.id).count() # or when user has created an app + Client.filter(Client.user_id == self.id).count() > 0 ) def get_random_alias_suffix(self, custom_domain: Optional["CustomDomain"] = None): """Get random suffix for an alias based on user's preference. Use a shorter suffix in case of custom domain Returns: str: the random suffix generated """ if self.random_alias_suffix == AliasSuffixEnum.random_string.value: return random_string(config.ALIAS_RANDOM_SUFFIX_LENGTH, include_digits=True) if custom_domain is None: return random_words(1, 3) return random_words(1) def can_create_contacts(self) -> bool: if self.is_premium(): return True if self.flags & User.FLAG_FREE_DISABLE_CREATE_ALIAS == 0: return True return not config.DISABLE_CREATE_CONTACTS_FOR_FREE_USERS def __repr__(self): return f"<User {self.id} {self.name} {self.email}>" class 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"),) def sanitize_email(email_address: str, not_lower=False) -> str: if email_address: email_address = email_address.strip().replace(" ", "").replace("\n", " ") if not not_lower: email_address = email_address.lower() return email_address.replace("\u200f", "") def after_login(user, next_url, login_from_proton: bool = False): """ Redirect to the correct page after login. If the user is logged in with Proton, do not look at fido nor otp If user enables MFA: redirect user to MFA page Otherwise redirect to dashboard page if no next_url """ if not login_from_proton: if user.fido_enabled(): # Use the same session for FIDO so that we can easily # switch between these two 2FA option session[MFA_USER_ID] = user.id if next_url: return redirect(url_for("auth.fido", next=next_url)) else: return redirect(url_for("auth.fido")) elif user.enable_otp: session[MFA_USER_ID] = user.id if next_url: return redirect(url_for("auth.mfa", next=next_url)) else: return redirect(url_for("auth.mfa")) LOG.d("log user %s in", user) login_user(user) session["sudo_time"] = int(time()) # User comes to login page from another page 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")) def google_callback(): # user clicks on cancel if "error" in request.args: flash("please use another sign in method then", "warning") return redirect("/") google = OAuth2Session( GOOGLE_CLIENT_ID, # some how Google Login fails with oauth_state KeyError # state=session["oauth_state"], scope=_scope, redirect_uri=_redirect_uri, ) google.fetch_token( _token_url, client_secret=GOOGLE_CLIENT_SECRET, authorization_response=request.url, ) # Fetch a protected resource, i.e. user profile # { # "email": "abcd@gmail.com", # "family_name": "First name", # "given_name": "Last name", # "id": "1234", # "locale": "en", # "name": "First Last", # "picture": "http://profile.jpg", # "verified_email": true # } google_user_data = google.get( "https://www.googleapis.com/oauth2/v1/userinfo" ).json() email = sanitize_email(google_user_data["email"]) user = User.get_by(email=email) picture_url = google_user_data.get("picture") if user: if picture_url and not user.profile_picture_id: LOG.d("set user profile picture to %s", picture_url) file = create_file_from_url(user, picture_url) user.profile_picture_id = file.id Session.commit() else: flash( "Sorry you cannot sign up via Google, please use email/password sign-up instead", "error", ) return redirect(url_for("auth.register")) next_url = None # The activation link contains the original page, for ex authorize page if "google_next_url" in session: next_url = session["google_next_url"] LOG.d("redirect user to %s", next_url) # reset the next_url to avoid user getting redirected at each login :) session.pop("google_next_url", None) if not SocialAuth.get_by(user_id=user.id, social="google"): SocialAuth.create(user_id=user.id, social="google") Session.commit() return after_login(user, next_url)
null
180,669
import json import secrets from time import time import webauthn from flask import ( request, render_template, redirect, url_for, flash, session, make_response, g, ) from flask_login import login_user from flask_wtf import FlaskForm from wtforms import HiddenField, validators, BooleanField from app.auth.base import auth_bp from app.config import MFA_USER_ID from app.config import RP_ID, URL from app.db import Session from app.extensions import limiter from app.log import LOG from app.models import User, Fido, MfaBrowser from app.utils import sanitize_next_url class FidoTokenForm(FlaskForm): sk_assertion = HiddenField("sk_assertion", validators=[validators.DataRequired()]) remember = BooleanField( "attr", default=False, description="Remember this browser for 30 days" ) "10/minute", deduct_when=lambda r: hasattr(g, "deduct_limit") and g.deduct_limit URL = os.environ["URL"] RP_ID = urlparse(URL).hostname MFA_USER_ID = "mfa_user_id" 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 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 MfaBrowser(Base, ModelMixin): __tablename__ = "mfa_browser" user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False) token = sa.Column(sa.String(64), default=False, unique=True, nullable=False) expires = sa.Column(ArrowType, default=False, nullable=False) user = orm.relationship(User) def create_new(cls, user, token_length=64) -> "MfaBrowser": found = False while not found: token = random_string(token_length) if not cls.get_by(token=token): found = True return MfaBrowser.create( user_id=user.id, token=token, expires=arrow.now().shift(days=30), ) def delete(cls, token): cls.filter(cls.token == token).delete() Session.commit() def delete_expired(cls): cls.filter(cls.expires < arrow.now()).delete() Session.commit() def is_expired(self): return self.expires < arrow.now() def reset_expire(self): self.expires = arrow.now().shift(days=30) def sanitize_next_url(url: Optional[str]) -> Optional[str]: return NextUrlSanitizer.sanitize(url, ALLOWED_REDIRECT_DOMAINS) def fido(): # passed from login page user_id = session.get(MFA_USER_ID) # user access this page directly without passing by login page if not user_id: flash("Unknown error, redirect back to main page", "warning") return redirect(url_for("auth.login")) user = User.get(user_id) if not (user and user.fido_enabled()): flash("Only user with security key linked should go to this page", "warning") return redirect(url_for("auth.login")) auto_activate = True fido_token_form = FidoTokenForm() next_url = sanitize_next_url(request.args.get("next")) if request.cookies.get("mfa"): browser = MfaBrowser.get_by(token=request.cookies.get("mfa")) if browser and not browser.is_expired() and browser.user_id == user.id: login_user(user) flash("Welcome back!", "success") # Redirect user to correct page return redirect(next_url or url_for("dashboard.index")) else: # Trigger rate limiter g.deduct_limit = True # 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 verification failed. Error: Invalid Payload", "warning") return redirect(url_for("auth.login")) challenge = session["fido_challenge"] try: fido_key = Fido.get_by( uuid=user.fido_uuid, credential_id=sk_assertion["id"] ) webauthn_user = webauthn.WebAuthnUser( user.fido_uuid, user.email, user.name if user.name else user.email, False, fido_key.credential_id, fido_key.public_key, fido_key.sign_count, RP_ID, ) webauthn_assertion_response = webauthn.WebAuthnAssertionResponse( webauthn_user, sk_assertion, challenge, URL, uv_required=False ) new_sign_count = webauthn_assertion_response.verify() except Exception as e: LOG.w(f"An error occurred in WebAuthn verification process: {e}") flash("Key verification failed.", "warning") # Trigger rate limiter g.deduct_limit = True auto_activate = False else: user.fido_sign_count = new_sign_count Session.commit() del session[MFA_USER_ID] session["sudo_time"] = int(time()) login_user(user) flash("Welcome back!", "success") # Redirect user to correct page response = make_response(redirect(next_url or url_for("dashboard.index"))) if fido_token_form.remember.data: browser = MfaBrowser.create_new(user=user) Session.commit() response.set_cookie( "mfa", value=browser.token, expires=browser.expires.datetime, secure=True if URL.startswith("https") else False, httponly=True, samesite="Lax", ) return response # Prepare information for key registration process session.pop("challenge", None) challenge = secrets.token_urlsafe(32) session["fido_challenge"] = challenge.rstrip("=") fidos = Fido.filter_by(uuid=user.fido_uuid).all() webauthn_users = [] for fido in fidos: webauthn_users.append( webauthn.WebAuthnUser( user.fido_uuid, user.email, user.name if user.name else user.email, False, fido.credential_id, fido.public_key, fido.sign_count, RP_ID, ) ) webauthn_assertion_options = webauthn.WebAuthnAssertionOptions( webauthn_users, challenge ) webauthn_assertion_options = webauthn_assertion_options.assertion_dict try: # HACK: We need to upgrade to webauthn > 1 so it can support specifying the transports for credential in webauthn_assertion_options["allowCredentials"]: del credential["transports"] except KeyError: # Should never happen but... pass return render_template( "auth/fido.html", fido_token_form=fido_token_form, webauthn_assertion_options=webauthn_assertion_options, enable_otp=user.enable_otp, auto_activate=auto_activate, next_url=next_url, )
null
180,670
from flask import render_template, redirect, url_for from flask_login import current_user from app.auth.base import auth_bp from app.log import LOG LOG = _get_logger("SL") def social(): if current_user.is_authenticated: LOG.d("user is already authenticated, redirect to dashboard") return redirect(url_for("dashboard.index")) return render_template("auth/social.html")
null
180,671
from flask import request, session, redirect, url_for, flash from requests_oauthlib import OAuth2Session from requests_oauthlib.compliance_fixes import facebook_compliance_fix from app.auth.base import auth_bp from app.auth.views.google import create_file_from_url from app.config import ( URL, FACEBOOK_CLIENT_ID, FACEBOOK_CLIENT_SECRET, ) from app.db import Session from app.log import LOG from app.models import User, SocialAuth from .login_utils import after_login from ...utils import sanitize_email, sanitize_next_url _authorization_base_url = "https://www.facebook.com/dialog/oauth" _scope = ["email"] _redirect_uri = URL + "/auth/facebook/callback" FACEBOOK_CLIENT_ID = os.environ.get("FACEBOOK_CLIENT_ID") def sanitize_next_url(url: Optional[str]) -> Optional[str]: def facebook_login(): # to avoid flask-login displaying the login error message session.pop("_flashes", None) next_url = sanitize_next_url(request.args.get("next")) # Facebook does not allow to append param to redirect_uri # we need to pass the next url by session if next_url: session["facebook_next_url"] = next_url facebook = OAuth2Session( FACEBOOK_CLIENT_ID, scope=_scope, redirect_uri=_redirect_uri ) facebook = facebook_compliance_fix(facebook) authorization_url, state = facebook.authorization_url(_authorization_base_url) # State is used to prevent CSRF, keep this for later. session["oauth_state"] = state return redirect(authorization_url)
null
180,672
from flask import request, session, redirect, url_for, flash from requests_oauthlib import OAuth2Session from requests_oauthlib.compliance_fixes import facebook_compliance_fix from app.auth.base import auth_bp from app.auth.views.google import create_file_from_url from app.config import ( URL, FACEBOOK_CLIENT_ID, FACEBOOK_CLIENT_SECRET, ) from app.db import Session from app.log import LOG from app.models import User, SocialAuth from .login_utils import after_login from ...utils import sanitize_email, sanitize_next_url _token_url = "https://graph.facebook.com/oauth/access_token" _scope = ["email"] _redirect_uri = URL + "/auth/facebook/callback" def create_file_from_url(user, url) -> File: file_path = random_string(30) file = File.create(path=file_path, user_id=user.id) s3.upload_from_url(url, file_path) Session.flush() LOG.d("upload file %s to s3", file) return file FACEBOOK_CLIENT_ID = os.environ.get("FACEBOOK_CLIENT_ID") FACEBOOK_CLIENT_SECRET = os.environ.get("FACEBOOK_CLIENT_SECRET") Session = scoped_session(sessionmaker(bind=connection)) Session: sqlalchemy.orm.Session LOG = _get_logger("SL") class User(Base, ModelMixin, UserMixin, PasswordOracle): __tablename__ = "users" FLAG_FREE_DISABLE_CREATE_ALIAS = 1 << 0 FLAG_CREATED_FROM_PARTNER = 1 << 1 FLAG_FREE_OLD_ALIAS_LIMIT = 1 << 2 email = sa.Column(sa.String(256), unique=True, nullable=False) name = sa.Column(sa.String(128), nullable=True) is_admin = sa.Column(sa.Boolean, nullable=False, default=False) alias_generator = sa.Column( sa.Integer, nullable=False, default=AliasGeneratorEnum.word.value, server_default=str(AliasGeneratorEnum.word.value), ) notification = sa.Column( sa.Boolean, default=True, nullable=False, server_default="1" ) activated = sa.Column(sa.Boolean, default=False, nullable=False, index=True) # an account can be disabled if having harmful behavior disabled = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0") profile_picture_id = sa.Column(sa.ForeignKey(File.id), nullable=True) otp_secret = sa.Column(sa.String(16), nullable=True) enable_otp = sa.Column( sa.Boolean, nullable=False, default=False, server_default="0" ) last_otp = sa.Column(sa.String(12), nullable=True, default=False) # Fields for WebAuthn fido_uuid = sa.Column(sa.String(), nullable=True, unique=True) # the default domain that's used when user creates a new random alias # default_alias_custom_domain_id XOR default_alias_public_domain_id default_alias_custom_domain_id = sa.Column( sa.ForeignKey("custom_domain.id", ondelete="SET NULL"), nullable=True, default=None, ) default_alias_public_domain_id = sa.Column( sa.ForeignKey("public_domain.id", ondelete="SET NULL"), nullable=True, default=None, ) # some users could have lifetime premium lifetime = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0") paid_lifetime = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) lifetime_coupon_id = sa.Column( sa.ForeignKey("lifetime_coupon.id", ondelete="SET NULL"), nullable=True, default=None, ) # user can use all premium features until this date trial_end = sa.Column( ArrowType, default=lambda: arrow.now().shift(days=7, hours=1), nullable=True ) # the mailbox used when create random alias # this field is nullable but in practice, it's always set # it cannot be set to non-nullable though # as this will create foreign key cycle between User and Mailbox default_mailbox_id = sa.Column( sa.ForeignKey("mailbox.id"), nullable=True, default=None ) profile_picture = orm.relationship(File, foreign_keys=[profile_picture_id]) # Specify the format for sender address # for the full list, see SenderFormatEnum sender_format = sa.Column( sa.Integer, default="0", nullable=False, server_default="0" ) # to know whether user has explicitly chosen a sender format as opposed to those who use the default ones. # users who haven't chosen a sender format and are using 1 or 3 format, their sender format will be set to 0 sender_format_updated_at = sa.Column(ArrowType, default=None) replace_reverse_alias = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) referral_id = sa.Column( sa.ForeignKey("referral.id", ondelete="SET NULL"), nullable=True, default=None, index=True, ) referral = orm.relationship("Referral", foreign_keys=[referral_id]) # whether intro has been shown to user intro_shown = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) default_mailbox = orm.relationship("Mailbox", foreign_keys=[default_mailbox_id]) # user can set a more strict max_spam score to block spams more aggressively max_spam_score = sa.Column(sa.Integer, nullable=True) # newsletter is sent to this address newsletter_alias_id = sa.Column( sa.ForeignKey("alias.id", ondelete="SET NULL"), nullable=True, default=None, index=True, ) # whether to include the sender address in reverse-alias include_sender_in_reverse_alias = sa.Column( sa.Boolean, default=True, nullable=False, server_default="0" ) # whether to use random string or random word as suffix # Random word from dictionary file -> 0 # Completely random string -> 1 random_alias_suffix = sa.Column( sa.Integer, nullable=False, default=AliasSuffixEnum.word.value, server_default=str(AliasSuffixEnum.random_string.value), ) # always expand the alias info, i.e. without needing to press "More" expand_alias_info = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # ignore emails send from a mailbox to its alias. This can happen when replying all to a forwarded email # can automatically re-includes the alias ignore_loop_email = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # used for flask-login as an "alternative token" # cf https://flask-login.readthedocs.io/en/latest/#alternative-tokens alternative_id = sa.Column(sa.String(128), unique=True, nullable=True) # by default, when an alias is automatically created, a note like "Created with ...." is created # If this field is True, the note won't be created. disable_automatic_alias_note = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # By default, the one-click unsubscribe disable the alias # If set to true, it will block the sender instead one_click_unsubscribe_block_sender = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # automatically include the website name when user creates an alias via the SimpleLogin icon in the email field include_website_in_one_click_alias = sa.Column( sa.Boolean, # new user will have this option turned on automatically default=True, nullable=False, # old user will have this option turned off server_default="0", ) _directory_quota = sa.Column( "directory_quota", sa.Integer, default=50, nullable=False, server_default="50" ) _subdomain_quota = sa.Column( "subdomain_quota", sa.Integer, default=5, nullable=False, server_default="5" ) # user can use import to import too many aliases disable_import = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # user can use the phone feature can_use_phone = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # in minutes phone_quota = sa.Column(sa.Integer, nullable=True) # Status code to return if is blocked block_behaviour = sa.Column( sa.Enum(BlockBehaviourEnum), nullable=False, server_default=BlockBehaviourEnum.return_2xx.name, ) include_header_email_header = sa.Column( sa.Boolean, default=True, nullable=False, server_default="1" ) # bitwise flags. Allow for future expansion flags = sa.Column( sa.BigInteger, default=FLAG_FREE_DISABLE_CREATE_ALIAS, server_default="0", nullable=False, ) # Keep original unsub behaviour unsub_behaviour = sa.Column( IntEnumType(UnsubscribeBehaviourEnum), default=UnsubscribeBehaviourEnum.PreserveOriginal, server_default=str(UnsubscribeBehaviourEnum.DisableAlias.value), nullable=False, ) # Trigger hard deletion of the account at this time delete_on = sa.Column(ArrowType, default=None) __table_args__ = ( sa.Index( "ix_users_activated_trial_end_lifetime", activated, trial_end, lifetime ), sa.Index("ix_users_delete_on", delete_on), ) def directory_quota(self): return min( self._directory_quota, config.MAX_NB_DIRECTORY - Directory.filter_by(user_id=self.id).count(), ) def subdomain_quota(self): return min( self._subdomain_quota, config.MAX_NB_SUBDOMAIN - CustomDomain.filter_by(user_id=self.id, is_sl_subdomain=True).count(), ) def created_by_partner(self): return User.FLAG_CREATED_FROM_PARTNER == ( self.flags & User.FLAG_CREATED_FROM_PARTNER ) def subdomain_is_available(): return SLDomain.filter_by(can_use_subdomain=True).count() > 0 # implement flask-login "alternative token" def get_id(self): if self.alternative_id: return self.alternative_id else: return str(self.id) def create(cls, email, name="", password=None, from_partner=False, **kwargs): email = sanitize_email(email) user: User = super(User, cls).create(email=email, name=name[:100], **kwargs) if password: user.set_password(password) Session.flush() mb = Mailbox.create(user_id=user.id, email=user.email, verified=True) Session.flush() user.default_mailbox_id = mb.id # generate an alternative_id if needed if "alternative_id" not in kwargs: user.alternative_id = str(uuid.uuid4()) # If the user is created from partner, do not notify # nor give a trial if from_partner: user.flags = User.FLAG_CREATED_FROM_PARTNER user.notification = False user.trial_end = None Job.create( name=config.JOB_SEND_PROTON_WELCOME_1, payload={"user_id": user.id}, run_at=arrow.now(), ) Session.flush() return user # create a first alias mail to show user how to use when they login alias = Alias.create_new( user, prefix="simplelogin-newsletter", mailbox_id=mb.id, note="This is your first alias. It's used to receive SimpleLogin communications " "like new features announcements, newsletters.", ) Session.flush() user.newsletter_alias_id = alias.id Session.flush() if config.DISABLE_ONBOARDING: LOG.d("Disable onboarding emails") return user # Schedule onboarding emails Job.create( name=config.JOB_ONBOARDING_1, payload={"user_id": user.id}, run_at=arrow.now().shift(days=1), ) Job.create( name=config.JOB_ONBOARDING_2, payload={"user_id": user.id}, run_at=arrow.now().shift(days=2), ) Job.create( name=config.JOB_ONBOARDING_4, payload={"user_id": user.id}, run_at=arrow.now().shift(days=3), ) Session.flush() return user def get_active_subscription( self, include_partner_subscription: bool = True ) -> Optional[ Union[ Subscription | AppleSubscription | ManualSubscription | CoinbaseSubscription | PartnerSubscription ] ]: sub: Subscription = self.get_paddle_subscription() if sub: return sub apple_sub: AppleSubscription = AppleSubscription.get_by(user_id=self.id) if apple_sub and apple_sub.is_valid(): return apple_sub manual_sub: ManualSubscription = ManualSubscription.get_by(user_id=self.id) if manual_sub and manual_sub.is_active(): return manual_sub coinbase_subscription: CoinbaseSubscription = CoinbaseSubscription.get_by( user_id=self.id ) if coinbase_subscription and coinbase_subscription.is_active(): return coinbase_subscription if include_partner_subscription: partner_sub: PartnerSubscription = PartnerSubscription.find_by_user_id( self.id ) if partner_sub and partner_sub.is_active(): return partner_sub return None def get_active_subscription_end( self, include_partner_subscription: bool = True ) -> Optional[arrow.Arrow]: sub = self.get_active_subscription( include_partner_subscription=include_partner_subscription ) if isinstance(sub, Subscription): return arrow.get(sub.next_bill_date) if isinstance(sub, AppleSubscription): return sub.expires_date if isinstance(sub, ManualSubscription): return sub.end_at if isinstance(sub, CoinbaseSubscription): return sub.end_at return None # region Billing def lifetime_or_active_subscription( self, include_partner_subscription: bool = True ) -> bool: """True if user has lifetime licence or active subscription""" if self.lifetime: return True return self.get_active_subscription(include_partner_subscription) is not None def is_paid(self) -> bool: """same as _lifetime_or_active_subscription but not include free manual subscription""" sub = self.get_active_subscription() if sub is None: return False if isinstance(sub, ManualSubscription) and sub.is_giveaway: return False return True def is_active(self) -> bool: if self.delete_on is None: return True return self.delete_on < arrow.now() def in_trial(self): """return True if user does not have lifetime licence or an active subscription AND is in trial period""" if self.lifetime_or_active_subscription(): return False if self.trial_end and arrow.now() < self.trial_end: return True return False def should_show_upgrade_button(self): if self.lifetime_or_active_subscription(): return False return True def is_premium(self, include_partner_subscription: bool = True) -> bool: """ user is premium if they: - have a lifetime deal or - in trial period or - active subscription """ if self.lifetime_or_active_subscription(include_partner_subscription): return True if self.trial_end and arrow.now() < self.trial_end: return True return False def upgrade_channel(self) -> str: """Used on admin dashboard""" # user can have multiple subscription channel channels = [] if self.lifetime: channels.append("Lifetime") sub: Subscription = self.get_paddle_subscription() if sub: if sub.cancelled: channels.append( f"""Cancelled Paddle Subscription <a href="https://vendors.paddle.com/subscriptions/customers/manage/{sub.subscription_id}">{sub.subscription_id}</a> {sub.plan_name()} ends at {sub.next_bill_date}""" ) else: channels.append( f"""Active Paddle Subscription <a href="https://vendors.paddle.com/subscriptions/customers/manage/{sub.subscription_id}">{sub.subscription_id}</a> {sub.plan_name()}, renews at {sub.next_bill_date}""" ) apple_sub: AppleSubscription = AppleSubscription.get_by(user_id=self.id) if apple_sub and apple_sub.is_valid(): channels.append(f"Apple Subscription {apple_sub.expires_date.humanize()}") manual_sub: ManualSubscription = ManualSubscription.get_by(user_id=self.id) if manual_sub and manual_sub.is_active(): mode = "Giveaway" if manual_sub.is_giveaway else "Paid" channels.append( f"Manual Subscription {manual_sub.comment} {mode} {manual_sub.end_at.humanize()}" ) coinbase_subscription: CoinbaseSubscription = CoinbaseSubscription.get_by( user_id=self.id ) if coinbase_subscription and coinbase_subscription.is_active(): channels.append( f"Coinbase Subscription ends {coinbase_subscription.end_at.humanize()}" ) r = ( Session.query(PartnerSubscription, PartnerUser, Partner) .filter( PartnerSubscription.partner_user_id == PartnerUser.id, PartnerUser.user_id == self.id, Partner.id == PartnerUser.partner_id, ) .first() ) if r and r[0].is_active(): channels.append( f"Subscription via {r[2].name} partner , ends {r[0].end_at.humanize()}" ) return ".\n".join(channels) # endregion def max_alias_for_free_account(self) -> int: if ( self.FLAG_FREE_OLD_ALIAS_LIMIT == self.flags & self.FLAG_FREE_OLD_ALIAS_LIMIT ): return config.MAX_NB_EMAIL_OLD_FREE_PLAN else: return config.MAX_NB_EMAIL_FREE_PLAN def can_create_new_alias(self) -> bool: """ Whether user can create a new alias. User can't create a new alias if - has more than 15 aliases in the free plan, *even in the free trial* """ if not self.is_active(): return False if self.disabled: return False if self.lifetime_or_active_subscription(): return True else: return ( Alias.filter_by(user_id=self.id).count() < self.max_alias_for_free_account() ) def can_send_or_receive(self) -> bool: if self.disabled: LOG.i(f"User {self} is disabled. Cannot receive or send emails") return False if self.delete_on is not None: LOG.i( f"User {self} is scheduled to be deleted. Cannot receive or send emails" ) return False return True def profile_picture_url(self): if self.profile_picture_id: return self.profile_picture.get_url() else: return url_for("static", filename="default-avatar.png") def suggested_emails(self, website_name) -> (str, [str]): """return suggested email and other email choices""" website_name = convert_to_id(website_name) all_aliases = [ ge.email for ge in Alias.filter_by(user_id=self.id, enabled=True) ] if self.can_create_new_alias(): suggested_alias = Alias.create_new(self, prefix=website_name).email else: # pick an email from the list of gen emails suggested_alias = random.choice(all_aliases) return ( suggested_alias, list(set(all_aliases).difference({suggested_alias})), ) def suggested_names(self) -> (str, [str]): """return suggested name and other name choices""" other_name = convert_to_id(self.name) return self.name, [other_name, "Anonymous", "whoami"] def get_name_initial(self) -> str: if not self.name: return "" names = self.name.split(" ") return "".join([n[0].upper() for n in names if n]) def get_paddle_subscription(self) -> Optional["Subscription"]: """return *active* Paddle subscription Return None if the subscription is already expired TODO: support user unsubscribe and re-subscribe """ sub = Subscription.get_by(user_id=self.id) if sub: # grace period is 14 days # sub is active until the next billing_date + PADDLE_SUBSCRIPTION_GRACE_DAYS if ( sub.next_bill_date >= arrow.now().shift(days=-PADDLE_SUBSCRIPTION_GRACE_DAYS).date() ): return sub # past subscription, user is considered not having a subscription = free plan else: return None else: return sub def verified_custom_domains(self) -> List["CustomDomain"]: return ( CustomDomain.filter_by(user_id=self.id, ownership_verified=True) .order_by(CustomDomain.domain.asc()) .all() ) def mailboxes(self) -> List["Mailbox"]: """list of mailbox that user own""" mailboxes = [] for mailbox in Mailbox.filter_by(user_id=self.id, verified=True): mailboxes.append(mailbox) return mailboxes def nb_directory(self): return Directory.filter_by(user_id=self.id).count() def has_custom_domain(self): return CustomDomain.filter_by(user_id=self.id, verified=True).count() > 0 def custom_domains(self): return CustomDomain.filter_by(user_id=self.id, verified=True).all() def available_domains_for_random_alias( self, alias_options: Optional[AliasOptions] = None ) -> List[Tuple[bool, str]]: """Return available domains for user to create random aliases Each result record contains: - whether the domain belongs to SimpleLogin - the domain """ res = [] for domain in self.available_sl_domains(alias_options=alias_options): res.append((True, domain)) for custom_domain in self.verified_custom_domains(): res.append((False, custom_domain.domain)) return res def default_random_alias_domain(self) -> str: """return the domain used for the random alias""" if self.default_alias_custom_domain_id: custom_domain = CustomDomain.get(self.default_alias_custom_domain_id) # sanity check if ( not custom_domain or not custom_domain.verified or custom_domain.user_id != self.id ): LOG.w("Problem with %s default random alias domain", self) return config.FIRST_ALIAS_DOMAIN return custom_domain.domain if self.default_alias_public_domain_id: sl_domain = SLDomain.get(self.default_alias_public_domain_id) # sanity check if not sl_domain: LOG.e("Problem with %s public random alias domain", self) return config.FIRST_ALIAS_DOMAIN if sl_domain.premium_only and not self.is_premium(): LOG.w( "%s is not premium and cannot use %s. Reset default random alias domain setting", self, sl_domain, ) self.default_alias_custom_domain_id = None self.default_alias_public_domain_id = None Session.commit() return config.FIRST_ALIAS_DOMAIN return sl_domain.domain return config.FIRST_ALIAS_DOMAIN def fido_enabled(self) -> bool: if self.fido_uuid is not None: return True return False def two_factor_authentication_enabled(self) -> bool: return self.enable_otp or self.fido_enabled() def get_communication_email(self) -> (Optional[str], str, bool): """ Return - the email that user uses to receive email communication. None if user unsubscribes from newsletter - the unsubscribe URL - whether the unsubscribe method is via sending email (mailto:) or Http POST """ if self.notification and self.activated and not self.disabled: if self.newsletter_alias_id: alias = Alias.get(self.newsletter_alias_id) if alias.enabled: unsub = UnsubscribeEncoder.encode( UnsubscribeAction.DisableAlias, alias.id ) return alias.email, unsub.link, unsub.via_email # alias disabled -> user doesn't want to receive newsletter else: return None, "", False else: # do not handle http POST unsubscribe if config.UNSUBSCRIBER: # use * as suffix instead of = as for alias unsubscribe return ( self.email, UnsubscribeEncoder.encode_mailto( UnsubscribeAction.UnsubscribeNewsletter, self.id ), True, ) return None, "", False def available_sl_domains( self, alias_options: Optional[AliasOptions] = None ) -> [str]: """ Return all SimpleLogin domains that user can use when creating a new alias, including: - SimpleLogin public domains, available for all users (ALIAS_DOMAIN) - SimpleLogin premium domains, only available for Premium accounts (PREMIUM_ALIAS_DOMAIN) """ return [ sl_domain.domain for sl_domain in self.get_sl_domains(alias_options=alias_options) ] def get_sl_domains( self, alias_options: Optional[AliasOptions] = None ) -> list["SLDomain"]: if alias_options is None: alias_options = AliasOptions() top_conds = [SLDomain.hidden == False] # noqa: E712 or_conds = [] # noqa:E711 if self.default_alias_public_domain_id is not None: default_domain_conds = [SLDomain.id == self.default_alias_public_domain_id] if not self.is_premium(): default_domain_conds.append( SLDomain.premium_only == False # noqa: E712 ) or_conds.append(and_(*default_domain_conds).self_group()) if alias_options.show_partner_domains is not None: partner_user = PartnerUser.filter_by( user_id=self.id, partner_id=alias_options.show_partner_domains.id ).first() if partner_user is not None: partner_domain_cond = [SLDomain.partner_id == partner_user.partner_id] if alias_options.show_partner_premium is None: alias_options.show_partner_premium = self.is_premium() if not alias_options.show_partner_premium: partner_domain_cond.append( SLDomain.premium_only == False # noqa: E712 ) or_conds.append(and_(*partner_domain_cond).self_group()) if alias_options.show_sl_domains: sl_conds = [SLDomain.partner_id == None] # noqa: E711 if not self.is_premium(): sl_conds.append(SLDomain.premium_only == False) # noqa: E712 or_conds.append(and_(*sl_conds).self_group()) top_conds.append(or_(*or_conds)) query = Session.query(SLDomain).filter(*top_conds).order_by(SLDomain.order) return query.all() def available_alias_domains( self, alias_options: Optional[AliasOptions] = None ) -> [str]: """return all domains that user can use when creating a new alias, including: - SimpleLogin public domains, available for all users (ALIAS_DOMAIN) - SimpleLogin premium domains, only available for Premium accounts (PREMIUM_ALIAS_DOMAIN) - Verified custom domains """ domains = self.available_sl_domains(alias_options=alias_options) for custom_domain in self.verified_custom_domains(): domains.append(custom_domain.domain) # can have duplicate where a "root" user has a domain that's also listed in SL domains return list(set(domains)) def should_show_app_page(self) -> bool: """whether to show the app page""" return ( # when user has used the "Sign in with SL" button before ClientUser.filter(ClientUser.user_id == self.id).count() # or when user has created an app + Client.filter(Client.user_id == self.id).count() > 0 ) def get_random_alias_suffix(self, custom_domain: Optional["CustomDomain"] = None): """Get random suffix for an alias based on user's preference. Use a shorter suffix in case of custom domain Returns: str: the random suffix generated """ if self.random_alias_suffix == AliasSuffixEnum.random_string.value: return random_string(config.ALIAS_RANDOM_SUFFIX_LENGTH, include_digits=True) if custom_domain is None: return random_words(1, 3) return random_words(1) def can_create_contacts(self) -> bool: if self.is_premium(): return True if self.flags & User.FLAG_FREE_DISABLE_CREATE_ALIAS == 0: return True return not config.DISABLE_CREATE_CONTACTS_FOR_FREE_USERS def __repr__(self): return f"<User {self.id} {self.name} {self.email}>" class 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"),) def after_login(user, next_url, login_from_proton: bool = False): """ Redirect to the correct page after login. If the user is logged in with Proton, do not look at fido nor otp If user enables MFA: redirect user to MFA page Otherwise redirect to dashboard page if no next_url """ if not login_from_proton: if user.fido_enabled(): # Use the same session for FIDO so that we can easily # switch between these two 2FA option session[MFA_USER_ID] = user.id if next_url: return redirect(url_for("auth.fido", next=next_url)) else: return redirect(url_for("auth.fido")) elif user.enable_otp: session[MFA_USER_ID] = user.id if next_url: return redirect(url_for("auth.mfa", next=next_url)) else: return redirect(url_for("auth.mfa")) LOG.d("log user %s in", user) login_user(user) session["sudo_time"] = int(time()) # User comes to login page from another page 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")) def sanitize_email(email_address: str, not_lower=False) -> str: if email_address: email_address = email_address.strip().replace(" ", "").replace("\n", " ") if not not_lower: email_address = email_address.lower() return email_address.replace("\u200f", "") def facebook_callback(): # user clicks on cancel if "error" in request.args: flash("Please use another sign in method then", "warning") return redirect("/") facebook = OAuth2Session( FACEBOOK_CLIENT_ID, state=session["oauth_state"], scope=_scope, redirect_uri=_redirect_uri, ) facebook = facebook_compliance_fix(facebook) facebook.fetch_token( _token_url, client_secret=FACEBOOK_CLIENT_SECRET, authorization_response=request.url, ) # Fetch a protected resource, i.e. user profile # { # "email": "abcd@gmail.com", # "id": "1234", # "name": "First Last", # "picture": { # "data": { # "url": "long_url" # } # } # } facebook_user_data = facebook.get( "https://graph.facebook.com/me?fields=id,name,email,picture{url}" ).json() email = facebook_user_data.get("email") # user choose to not share email, cannot continue if not email: flash( "In order to use SimpleLogin, you need to give us a valid email", "warning" ) return redirect(url_for("auth.register")) email = sanitize_email(email) user = User.get_by(email=email) picture_url = facebook_user_data.get("picture", {}).get("data", {}).get("url") if user: if picture_url and not user.profile_picture_id: LOG.d("set user profile picture to %s", picture_url) file = create_file_from_url(user, picture_url) user.profile_picture_id = file.id Session.commit() else: flash( "Sorry you cannot sign up via Facebook, please use email/password sign-up instead", "error", ) return redirect(url_for("auth.register")) next_url = None # The activation link contains the original page, for ex authorize page if "facebook_next_url" in session: next_url = session["facebook_next_url"] LOG.d("redirect user to %s", next_url) # reset the next_url to avoid user getting redirected at each login :) session.pop("facebook_next_url", None) if not SocialAuth.get_by(user_id=user.id, social="facebook"): SocialAuth.create(user_id=user.id, social="facebook") Session.commit() return after_login(user, next_url)
null
180,673
from flask import request, render_template, flash, g from flask_wtf import FlaskForm from wtforms import StringField, validators from app.auth.base import auth_bp from app.dashboard.views.account_setting import send_reset_password_email from app.extensions import limiter from app.log import LOG from app.models import User from app.utils import sanitize_email, canonicalize_email class ForgotPasswordForm(FlaskForm): email = StringField("Email", validators=[validators.DataRequired()]) "10/hour", deduct_when=lambda r: hasattr(g, "deduct_limit") and g.deduct_limit 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) 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}>" 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", "") def forgot_password(): form = ForgotPasswordForm(request.form) if form.validate_on_submit(): # Trigger rate limiter g.deduct_limit = True flash( "If your email is correct, you are going to receive an email to reset your password", "success", ) email = sanitize_email(form.email.data) canonical_email = canonicalize_email(email) user = User.get_by(email=email) or User.get_by(email=canonical_email) if user: LOG.d("Send forgot password email to %s", user) send_reset_password_email(user) return render_template("auth/forgot_password.html", form=form)
null
180,674
from flask import request, render_template, redirect, url_for, flash, g from flask_login import current_user from flask_wtf import FlaskForm from wtforms import StringField, validators from app.auth.base import auth_bp from app.auth.views.login_utils import after_login from app.config import CONNECT_WITH_PROTON, CONNECT_WITH_OIDC_ICON, OIDC_CLIENT_ID from app.events.auth_event import LoginEvent from app.extensions import limiter from app.log import LOG from app.models import User from app.utils import sanitize_email, sanitize_next_url, canonicalize_email class LoginForm(FlaskForm): email = StringField("Email", validators=[validators.DataRequired()]) password = StringField("Password", validators=[validators.DataRequired()]) "10/minute", deduct_when=lambda r: hasattr(g, "deduct_limit") and g.deduct_limit def after_login(user, next_url, login_from_proton: bool = False): """ Redirect to the correct page after login. If the user is logged in with Proton, do not look at fido nor otp If user enables MFA: redirect user to MFA page Otherwise redirect to dashboard page if no next_url """ if not login_from_proton: if user.fido_enabled(): # Use the same session for FIDO so that we can easily # switch between these two 2FA option session[MFA_USER_ID] = user.id if next_url: return redirect(url_for("auth.fido", next=next_url)) else: return redirect(url_for("auth.fido")) elif user.enable_otp: session[MFA_USER_ID] = user.id if next_url: return redirect(url_for("auth.mfa", next=next_url)) else: return redirect(url_for("auth.mfa")) LOG.d("log user %s in", user) login_user(user) session["sudo_time"] = int(time()) # User comes to login page from another page 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")) 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 class LoginEvent: class ActionType(EnumE): success = 0 failed = 1 disabled_login = 2 not_activated = 3 scheduled_to_be_deleted = 4 class Source(EnumE): web = 0 api = 1 def __init__(self, action: ActionType, source: Source = Source.web): self.action = action self.source = source def send(self): newrelic.agent.record_custom_event( "LoginEvent", {"action": self.action.name, "source": self.source.name} ) 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}>" 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", "") def sanitize_next_url(url: Optional[str]) -> Optional[str]: return NextUrlSanitizer.sanitize(url, ALLOWED_REDIRECT_DOMAINS) def login(): next_url = sanitize_next_url(request.args.get("next")) if current_user.is_authenticated: if next_url: LOG.d("user is already authenticated, redirect to %s", next_url) return redirect(next_url) else: LOG.d("user is already authenticated, redirect to dashboard") return redirect(url_for("dashboard.index")) form = LoginForm(request.form) show_resend_activation = False if form.validate_on_submit(): email = sanitize_email(form.email.data) canonical_email = canonicalize_email(email) user = User.get_by(email=email) or User.get_by(email=canonical_email) if not user or not user.check_password(form.password.data): # Trigger rate limiter g.deduct_limit = True form.password.data = None flash("Email or password incorrect", "error") LoginEvent(LoginEvent.ActionType.failed).send() elif user.disabled: flash( "Your account is disabled. Please contact SimpleLogin team to re-enable your account.", "error", ) LoginEvent(LoginEvent.ActionType.disabled_login).send() elif user.delete_on is not None: flash( f"Your account is scheduled to be deleted on {user.delete_on}", "error", ) LoginEvent(LoginEvent.ActionType.scheduled_to_be_deleted).send() elif not user.activated: show_resend_activation = True flash( "Please check your inbox for the activation email. You can also have this email re-sent", "error", ) LoginEvent(LoginEvent.ActionType.not_activated).send() else: LoginEvent(LoginEvent.ActionType.success).send() return after_login(user, next_url) return render_template( "auth/login.html", form=form, next_url=next_url, show_resend_activation=show_resend_activation, connect_with_proton=CONNECT_WITH_PROTON, connect_with_oidc=OIDC_CLIENT_ID is not None, connect_with_oidc_icon=CONNECT_WITH_OIDC_ICON, )
null
180,675
from flask import request, session, redirect, flash, url_for from requests_oauthlib import OAuth2Session from app import config from app.auth.base import auth_bp from app.auth.views.login_utils import after_login from app.config import ( URL, OIDC_AUTHORIZATION_URL, OIDC_USER_INFO_URL, OIDC_TOKEN_URL, OIDC_SCOPES, OIDC_NAME_FIELD, ) from app.db import Session from app.email_utils import send_welcome_email from app.log import LOG from app.models import User, SocialAuth from app.utils import encode_url, sanitize_email, sanitize_next_url _redirect_uri = URL + "/auth/oidc/callback" SESSION_STATE_KEY = "oauth_state" OIDC_AUTHORIZATION_URL = os.environ.get("OIDC_AUTHORIZATION_URL") OIDC_SCOPES = os.environ.get("OIDC_SCOPES") def encode_url(url): return urllib.parse.quote(url, safe="") def sanitize_next_url(url: Optional[str]) -> Optional[str]: return NextUrlSanitizer.sanitize(url, ALLOWED_REDIRECT_DOMAINS) def oidc_login(): if config.OIDC_CLIENT_ID is None or config.OIDC_CLIENT_SECRET is None: return redirect(url_for("auth.login")) next_url = sanitize_next_url(request.args.get("next")) if next_url: redirect_uri = _redirect_uri + "?next=" + encode_url(next_url) else: redirect_uri = _redirect_uri oidc = OAuth2Session( config.OIDC_CLIENT_ID, scope=[OIDC_SCOPES], redirect_uri=redirect_uri ) authorization_url, state = oidc.authorization_url(OIDC_AUTHORIZATION_URL) # State is used to prevent CSRF, keep this for later. session[SESSION_STATE_KEY] = state return redirect(authorization_url)
null
180,676
from flask import request, session, redirect, flash, url_for from requests_oauthlib import OAuth2Session from app import config from app.auth.base import auth_bp from app.auth.views.login_utils import after_login from app.config import ( URL, OIDC_AUTHORIZATION_URL, OIDC_USER_INFO_URL, OIDC_TOKEN_URL, OIDC_SCOPES, OIDC_NAME_FIELD, ) from app.db import Session from app.email_utils import send_welcome_email from app.log import LOG from app.models import User, SocialAuth from app.utils import encode_url, sanitize_email, sanitize_next_url _redirect_uri = URL + "/auth/oidc/callback" SESSION_STATE_KEY = "oauth_state" def create_user(email, oidc_user_data): new_user = User.create( email=email, name=oidc_user_data.get(OIDC_NAME_FIELD), password="", activated=True, ) LOG.i(f"Created new user for login request from OIDC. New user {new_user.id}") Session.commit() send_welcome_email(new_user) return new_user OIDC_USER_INFO_URL = os.environ.get("OIDC_USER_INFO_URL") OIDC_TOKEN_URL = os.environ.get("OIDC_TOKEN_URL") OIDC_SCOPES = os.environ.get("OIDC_SCOPES") def after_login(user, next_url, login_from_proton: bool = False): """ Redirect to the correct page after login. If the user is logged in with Proton, do not look at fido nor otp If user enables MFA: redirect user to MFA page Otherwise redirect to dashboard page if no next_url """ if not login_from_proton: if user.fido_enabled(): # Use the same session for FIDO so that we can easily # switch between these two 2FA option session[MFA_USER_ID] = user.id if next_url: return redirect(url_for("auth.fido", next=next_url)) else: return redirect(url_for("auth.fido")) elif user.enable_otp: session[MFA_USER_ID] = user.id if next_url: return redirect(url_for("auth.mfa", next=next_url)) else: return redirect(url_for("auth.mfa")) LOG.d("log user %s in", user) login_user(user) session["sudo_time"] = int(time()) # User comes to login page from another page 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")) Session = scoped_session(sessionmaker(bind=connection)) Session: sqlalchemy.orm.Session LOG = _get_logger("SL") class User(Base, ModelMixin, UserMixin, PasswordOracle): __tablename__ = "users" FLAG_FREE_DISABLE_CREATE_ALIAS = 1 << 0 FLAG_CREATED_FROM_PARTNER = 1 << 1 FLAG_FREE_OLD_ALIAS_LIMIT = 1 << 2 email = sa.Column(sa.String(256), unique=True, nullable=False) name = sa.Column(sa.String(128), nullable=True) is_admin = sa.Column(sa.Boolean, nullable=False, default=False) alias_generator = sa.Column( sa.Integer, nullable=False, default=AliasGeneratorEnum.word.value, server_default=str(AliasGeneratorEnum.word.value), ) notification = sa.Column( sa.Boolean, default=True, nullable=False, server_default="1" ) activated = sa.Column(sa.Boolean, default=False, nullable=False, index=True) # an account can be disabled if having harmful behavior disabled = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0") profile_picture_id = sa.Column(sa.ForeignKey(File.id), nullable=True) otp_secret = sa.Column(sa.String(16), nullable=True) enable_otp = sa.Column( sa.Boolean, nullable=False, default=False, server_default="0" ) last_otp = sa.Column(sa.String(12), nullable=True, default=False) # Fields for WebAuthn fido_uuid = sa.Column(sa.String(), nullable=True, unique=True) # the default domain that's used when user creates a new random alias # default_alias_custom_domain_id XOR default_alias_public_domain_id default_alias_custom_domain_id = sa.Column( sa.ForeignKey("custom_domain.id", ondelete="SET NULL"), nullable=True, default=None, ) default_alias_public_domain_id = sa.Column( sa.ForeignKey("public_domain.id", ondelete="SET NULL"), nullable=True, default=None, ) # some users could have lifetime premium lifetime = sa.Column(sa.Boolean, default=False, nullable=False, server_default="0") paid_lifetime = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) lifetime_coupon_id = sa.Column( sa.ForeignKey("lifetime_coupon.id", ondelete="SET NULL"), nullable=True, default=None, ) # user can use all premium features until this date trial_end = sa.Column( ArrowType, default=lambda: arrow.now().shift(days=7, hours=1), nullable=True ) # the mailbox used when create random alias # this field is nullable but in practice, it's always set # it cannot be set to non-nullable though # as this will create foreign key cycle between User and Mailbox default_mailbox_id = sa.Column( sa.ForeignKey("mailbox.id"), nullable=True, default=None ) profile_picture = orm.relationship(File, foreign_keys=[profile_picture_id]) # Specify the format for sender address # for the full list, see SenderFormatEnum sender_format = sa.Column( sa.Integer, default="0", nullable=False, server_default="0" ) # to know whether user has explicitly chosen a sender format as opposed to those who use the default ones. # users who haven't chosen a sender format and are using 1 or 3 format, their sender format will be set to 0 sender_format_updated_at = sa.Column(ArrowType, default=None) replace_reverse_alias = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) referral_id = sa.Column( sa.ForeignKey("referral.id", ondelete="SET NULL"), nullable=True, default=None, index=True, ) referral = orm.relationship("Referral", foreign_keys=[referral_id]) # whether intro has been shown to user intro_shown = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) default_mailbox = orm.relationship("Mailbox", foreign_keys=[default_mailbox_id]) # user can set a more strict max_spam score to block spams more aggressively max_spam_score = sa.Column(sa.Integer, nullable=True) # newsletter is sent to this address newsletter_alias_id = sa.Column( sa.ForeignKey("alias.id", ondelete="SET NULL"), nullable=True, default=None, index=True, ) # whether to include the sender address in reverse-alias include_sender_in_reverse_alias = sa.Column( sa.Boolean, default=True, nullable=False, server_default="0" ) # whether to use random string or random word as suffix # Random word from dictionary file -> 0 # Completely random string -> 1 random_alias_suffix = sa.Column( sa.Integer, nullable=False, default=AliasSuffixEnum.word.value, server_default=str(AliasSuffixEnum.random_string.value), ) # always expand the alias info, i.e. without needing to press "More" expand_alias_info = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # ignore emails send from a mailbox to its alias. This can happen when replying all to a forwarded email # can automatically re-includes the alias ignore_loop_email = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # used for flask-login as an "alternative token" # cf https://flask-login.readthedocs.io/en/latest/#alternative-tokens alternative_id = sa.Column(sa.String(128), unique=True, nullable=True) # by default, when an alias is automatically created, a note like "Created with ...." is created # If this field is True, the note won't be created. disable_automatic_alias_note = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # By default, the one-click unsubscribe disable the alias # If set to true, it will block the sender instead one_click_unsubscribe_block_sender = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # automatically include the website name when user creates an alias via the SimpleLogin icon in the email field include_website_in_one_click_alias = sa.Column( sa.Boolean, # new user will have this option turned on automatically default=True, nullable=False, # old user will have this option turned off server_default="0", ) _directory_quota = sa.Column( "directory_quota", sa.Integer, default=50, nullable=False, server_default="50" ) _subdomain_quota = sa.Column( "subdomain_quota", sa.Integer, default=5, nullable=False, server_default="5" ) # user can use import to import too many aliases disable_import = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # user can use the phone feature can_use_phone = sa.Column( sa.Boolean, default=False, nullable=False, server_default="0" ) # in minutes phone_quota = sa.Column(sa.Integer, nullable=True) # Status code to return if is blocked block_behaviour = sa.Column( sa.Enum(BlockBehaviourEnum), nullable=False, server_default=BlockBehaviourEnum.return_2xx.name, ) include_header_email_header = sa.Column( sa.Boolean, default=True, nullable=False, server_default="1" ) # bitwise flags. Allow for future expansion flags = sa.Column( sa.BigInteger, default=FLAG_FREE_DISABLE_CREATE_ALIAS, server_default="0", nullable=False, ) # Keep original unsub behaviour unsub_behaviour = sa.Column( IntEnumType(UnsubscribeBehaviourEnum), default=UnsubscribeBehaviourEnum.PreserveOriginal, server_default=str(UnsubscribeBehaviourEnum.DisableAlias.value), nullable=False, ) # Trigger hard deletion of the account at this time delete_on = sa.Column(ArrowType, default=None) __table_args__ = ( sa.Index( "ix_users_activated_trial_end_lifetime", activated, trial_end, lifetime ), sa.Index("ix_users_delete_on", delete_on), ) def directory_quota(self): return min( self._directory_quota, config.MAX_NB_DIRECTORY - Directory.filter_by(user_id=self.id).count(), ) def subdomain_quota(self): return min( self._subdomain_quota, config.MAX_NB_SUBDOMAIN - CustomDomain.filter_by(user_id=self.id, is_sl_subdomain=True).count(), ) def created_by_partner(self): return User.FLAG_CREATED_FROM_PARTNER == ( self.flags & User.FLAG_CREATED_FROM_PARTNER ) def subdomain_is_available(): return SLDomain.filter_by(can_use_subdomain=True).count() > 0 # implement flask-login "alternative token" def get_id(self): if self.alternative_id: return self.alternative_id else: return str(self.id) def create(cls, email, name="", password=None, from_partner=False, **kwargs): email = sanitize_email(email) user: User = super(User, cls).create(email=email, name=name[:100], **kwargs) if password: user.set_password(password) Session.flush() mb = Mailbox.create(user_id=user.id, email=user.email, verified=True) Session.flush() user.default_mailbox_id = mb.id # generate an alternative_id if needed if "alternative_id" not in kwargs: user.alternative_id = str(uuid.uuid4()) # If the user is created from partner, do not notify # nor give a trial if from_partner: user.flags = User.FLAG_CREATED_FROM_PARTNER user.notification = False user.trial_end = None Job.create( name=config.JOB_SEND_PROTON_WELCOME_1, payload={"user_id": user.id}, run_at=arrow.now(), ) Session.flush() return user # create a first alias mail to show user how to use when they login alias = Alias.create_new( user, prefix="simplelogin-newsletter", mailbox_id=mb.id, note="This is your first alias. It's used to receive SimpleLogin communications " "like new features announcements, newsletters.", ) Session.flush() user.newsletter_alias_id = alias.id Session.flush() if config.DISABLE_ONBOARDING: LOG.d("Disable onboarding emails") return user # Schedule onboarding emails Job.create( name=config.JOB_ONBOARDING_1, payload={"user_id": user.id}, run_at=arrow.now().shift(days=1), ) Job.create( name=config.JOB_ONBOARDING_2, payload={"user_id": user.id}, run_at=arrow.now().shift(days=2), ) Job.create( name=config.JOB_ONBOARDING_4, payload={"user_id": user.id}, run_at=arrow.now().shift(days=3), ) Session.flush() return user def get_active_subscription( self, include_partner_subscription: bool = True ) -> Optional[ Union[ Subscription | AppleSubscription | ManualSubscription | CoinbaseSubscription | PartnerSubscription ] ]: sub: Subscription = self.get_paddle_subscription() if sub: return sub apple_sub: AppleSubscription = AppleSubscription.get_by(user_id=self.id) if apple_sub and apple_sub.is_valid(): return apple_sub manual_sub: ManualSubscription = ManualSubscription.get_by(user_id=self.id) if manual_sub and manual_sub.is_active(): return manual_sub coinbase_subscription: CoinbaseSubscription = CoinbaseSubscription.get_by( user_id=self.id ) if coinbase_subscription and coinbase_subscription.is_active(): return coinbase_subscription if include_partner_subscription: partner_sub: PartnerSubscription = PartnerSubscription.find_by_user_id( self.id ) if partner_sub and partner_sub.is_active(): return partner_sub return None def get_active_subscription_end( self, include_partner_subscription: bool = True ) -> Optional[arrow.Arrow]: sub = self.get_active_subscription( include_partner_subscription=include_partner_subscription ) if isinstance(sub, Subscription): return arrow.get(sub.next_bill_date) if isinstance(sub, AppleSubscription): return sub.expires_date if isinstance(sub, ManualSubscription): return sub.end_at if isinstance(sub, CoinbaseSubscription): return sub.end_at return None # region Billing def lifetime_or_active_subscription( self, include_partner_subscription: bool = True ) -> bool: """True if user has lifetime licence or active subscription""" if self.lifetime: return True return self.get_active_subscription(include_partner_subscription) is not None def is_paid(self) -> bool: """same as _lifetime_or_active_subscription but not include free manual subscription""" sub = self.get_active_subscription() if sub is None: return False if isinstance(sub, ManualSubscription) and sub.is_giveaway: return False return True def is_active(self) -> bool: if self.delete_on is None: return True return self.delete_on < arrow.now() def in_trial(self): """return True if user does not have lifetime licence or an active subscription AND is in trial period""" if self.lifetime_or_active_subscription(): return False if self.trial_end and arrow.now() < self.trial_end: return True return False def should_show_upgrade_button(self): if self.lifetime_or_active_subscription(): return False return True def is_premium(self, include_partner_subscription: bool = True) -> bool: """ user is premium if they: - have a lifetime deal or - in trial period or - active subscription """ if self.lifetime_or_active_subscription(include_partner_subscription): return True if self.trial_end and arrow.now() < self.trial_end: return True return False def upgrade_channel(self) -> str: """Used on admin dashboard""" # user can have multiple subscription channel channels = [] if self.lifetime: channels.append("Lifetime") sub: Subscription = self.get_paddle_subscription() if sub: if sub.cancelled: channels.append( f"""Cancelled Paddle Subscription <a href="https://vendors.paddle.com/subscriptions/customers/manage/{sub.subscription_id}">{sub.subscription_id}</a> {sub.plan_name()} ends at {sub.next_bill_date}""" ) else: channels.append( f"""Active Paddle Subscription <a href="https://vendors.paddle.com/subscriptions/customers/manage/{sub.subscription_id}">{sub.subscription_id}</a> {sub.plan_name()}, renews at {sub.next_bill_date}""" ) apple_sub: AppleSubscription = AppleSubscription.get_by(user_id=self.id) if apple_sub and apple_sub.is_valid(): channels.append(f"Apple Subscription {apple_sub.expires_date.humanize()}") manual_sub: ManualSubscription = ManualSubscription.get_by(user_id=self.id) if manual_sub and manual_sub.is_active(): mode = "Giveaway" if manual_sub.is_giveaway else "Paid" channels.append( f"Manual Subscription {manual_sub.comment} {mode} {manual_sub.end_at.humanize()}" ) coinbase_subscription: CoinbaseSubscription = CoinbaseSubscription.get_by( user_id=self.id ) if coinbase_subscription and coinbase_subscription.is_active(): channels.append( f"Coinbase Subscription ends {coinbase_subscription.end_at.humanize()}" ) r = ( Session.query(PartnerSubscription, PartnerUser, Partner) .filter( PartnerSubscription.partner_user_id == PartnerUser.id, PartnerUser.user_id == self.id, Partner.id == PartnerUser.partner_id, ) .first() ) if r and r[0].is_active(): channels.append( f"Subscription via {r[2].name} partner , ends {r[0].end_at.humanize()}" ) return ".\n".join(channels) # endregion def max_alias_for_free_account(self) -> int: if ( self.FLAG_FREE_OLD_ALIAS_LIMIT == self.flags & self.FLAG_FREE_OLD_ALIAS_LIMIT ): return config.MAX_NB_EMAIL_OLD_FREE_PLAN else: return config.MAX_NB_EMAIL_FREE_PLAN def can_create_new_alias(self) -> bool: """ Whether user can create a new alias. User can't create a new alias if - has more than 15 aliases in the free plan, *even in the free trial* """ if not self.is_active(): return False if self.disabled: return False if self.lifetime_or_active_subscription(): return True else: return ( Alias.filter_by(user_id=self.id).count() < self.max_alias_for_free_account() ) def can_send_or_receive(self) -> bool: if self.disabled: LOG.i(f"User {self} is disabled. Cannot receive or send emails") return False if self.delete_on is not None: LOG.i( f"User {self} is scheduled to be deleted. Cannot receive or send emails" ) return False return True def profile_picture_url(self): if self.profile_picture_id: return self.profile_picture.get_url() else: return url_for("static", filename="default-avatar.png") def suggested_emails(self, website_name) -> (str, [str]): """return suggested email and other email choices""" website_name = convert_to_id(website_name) all_aliases = [ ge.email for ge in Alias.filter_by(user_id=self.id, enabled=True) ] if self.can_create_new_alias(): suggested_alias = Alias.create_new(self, prefix=website_name).email else: # pick an email from the list of gen emails suggested_alias = random.choice(all_aliases) return ( suggested_alias, list(set(all_aliases).difference({suggested_alias})), ) def suggested_names(self) -> (str, [str]): """return suggested name and other name choices""" other_name = convert_to_id(self.name) return self.name, [other_name, "Anonymous", "whoami"] def get_name_initial(self) -> str: if not self.name: return "" names = self.name.split(" ") return "".join([n[0].upper() for n in names if n]) def get_paddle_subscription(self) -> Optional["Subscription"]: """return *active* Paddle subscription Return None if the subscription is already expired TODO: support user unsubscribe and re-subscribe """ sub = Subscription.get_by(user_id=self.id) if sub: # grace period is 14 days # sub is active until the next billing_date + PADDLE_SUBSCRIPTION_GRACE_DAYS if ( sub.next_bill_date >= arrow.now().shift(days=-PADDLE_SUBSCRIPTION_GRACE_DAYS).date() ): return sub # past subscription, user is considered not having a subscription = free plan else: return None else: return sub def verified_custom_domains(self) -> List["CustomDomain"]: return ( CustomDomain.filter_by(user_id=self.id, ownership_verified=True) .order_by(CustomDomain.domain.asc()) .all() ) def mailboxes(self) -> List["Mailbox"]: """list of mailbox that user own""" mailboxes = [] for mailbox in Mailbox.filter_by(user_id=self.id, verified=True): mailboxes.append(mailbox) return mailboxes def nb_directory(self): return Directory.filter_by(user_id=self.id).count() def has_custom_domain(self): return CustomDomain.filter_by(user_id=self.id, verified=True).count() > 0 def custom_domains(self): return CustomDomain.filter_by(user_id=self.id, verified=True).all() def available_domains_for_random_alias( self, alias_options: Optional[AliasOptions] = None ) -> List[Tuple[bool, str]]: """Return available domains for user to create random aliases Each result record contains: - whether the domain belongs to SimpleLogin - the domain """ res = [] for domain in self.available_sl_domains(alias_options=alias_options): res.append((True, domain)) for custom_domain in self.verified_custom_domains(): res.append((False, custom_domain.domain)) return res def default_random_alias_domain(self) -> str: """return the domain used for the random alias""" if self.default_alias_custom_domain_id: custom_domain = CustomDomain.get(self.default_alias_custom_domain_id) # sanity check if ( not custom_domain or not custom_domain.verified or custom_domain.user_id != self.id ): LOG.w("Problem with %s default random alias domain", self) return config.FIRST_ALIAS_DOMAIN return custom_domain.domain if self.default_alias_public_domain_id: sl_domain = SLDomain.get(self.default_alias_public_domain_id) # sanity check if not sl_domain: LOG.e("Problem with %s public random alias domain", self) return config.FIRST_ALIAS_DOMAIN if sl_domain.premium_only and not self.is_premium(): LOG.w( "%s is not premium and cannot use %s. Reset default random alias domain setting", self, sl_domain, ) self.default_alias_custom_domain_id = None self.default_alias_public_domain_id = None Session.commit() return config.FIRST_ALIAS_DOMAIN return sl_domain.domain return config.FIRST_ALIAS_DOMAIN def fido_enabled(self) -> bool: if self.fido_uuid is not None: return True return False def two_factor_authentication_enabled(self) -> bool: return self.enable_otp or self.fido_enabled() def get_communication_email(self) -> (Optional[str], str, bool): """ Return - the email that user uses to receive email communication. None if user unsubscribes from newsletter - the unsubscribe URL - whether the unsubscribe method is via sending email (mailto:) or Http POST """ if self.notification and self.activated and not self.disabled: if self.newsletter_alias_id: alias = Alias.get(self.newsletter_alias_id) if alias.enabled: unsub = UnsubscribeEncoder.encode( UnsubscribeAction.DisableAlias, alias.id ) return alias.email, unsub.link, unsub.via_email # alias disabled -> user doesn't want to receive newsletter else: return None, "", False else: # do not handle http POST unsubscribe if config.UNSUBSCRIBER: # use * as suffix instead of = as for alias unsubscribe return ( self.email, UnsubscribeEncoder.encode_mailto( UnsubscribeAction.UnsubscribeNewsletter, self.id ), True, ) return None, "", False def available_sl_domains( self, alias_options: Optional[AliasOptions] = None ) -> [str]: """ Return all SimpleLogin domains that user can use when creating a new alias, including: - SimpleLogin public domains, available for all users (ALIAS_DOMAIN) - SimpleLogin premium domains, only available for Premium accounts (PREMIUM_ALIAS_DOMAIN) """ return [ sl_domain.domain for sl_domain in self.get_sl_domains(alias_options=alias_options) ] def get_sl_domains( self, alias_options: Optional[AliasOptions] = None ) -> list["SLDomain"]: if alias_options is None: alias_options = AliasOptions() top_conds = [SLDomain.hidden == False] # noqa: E712 or_conds = [] # noqa:E711 if self.default_alias_public_domain_id is not None: default_domain_conds = [SLDomain.id == self.default_alias_public_domain_id] if not self.is_premium(): default_domain_conds.append( SLDomain.premium_only == False # noqa: E712 ) or_conds.append(and_(*default_domain_conds).self_group()) if alias_options.show_partner_domains is not None: partner_user = PartnerUser.filter_by( user_id=self.id, partner_id=alias_options.show_partner_domains.id ).first() if partner_user is not None: partner_domain_cond = [SLDomain.partner_id == partner_user.partner_id] if alias_options.show_partner_premium is None: alias_options.show_partner_premium = self.is_premium() if not alias_options.show_partner_premium: partner_domain_cond.append( SLDomain.premium_only == False # noqa: E712 ) or_conds.append(and_(*partner_domain_cond).self_group()) if alias_options.show_sl_domains: sl_conds = [SLDomain.partner_id == None] # noqa: E711 if not self.is_premium(): sl_conds.append(SLDomain.premium_only == False) # noqa: E712 or_conds.append(and_(*sl_conds).self_group()) top_conds.append(or_(*or_conds)) query = Session.query(SLDomain).filter(*top_conds).order_by(SLDomain.order) return query.all() def available_alias_domains( self, alias_options: Optional[AliasOptions] = None ) -> [str]: """return all domains that user can use when creating a new alias, including: - SimpleLogin public domains, available for all users (ALIAS_DOMAIN) - SimpleLogin premium domains, only available for Premium accounts (PREMIUM_ALIAS_DOMAIN) - Verified custom domains """ domains = self.available_sl_domains(alias_options=alias_options) for custom_domain in self.verified_custom_domains(): domains.append(custom_domain.domain) # can have duplicate where a "root" user has a domain that's also listed in SL domains return list(set(domains)) def should_show_app_page(self) -> bool: """whether to show the app page""" return ( # when user has used the "Sign in with SL" button before ClientUser.filter(ClientUser.user_id == self.id).count() # or when user has created an app + Client.filter(Client.user_id == self.id).count() > 0 ) def get_random_alias_suffix(self, custom_domain: Optional["CustomDomain"] = None): """Get random suffix for an alias based on user's preference. Use a shorter suffix in case of custom domain Returns: str: the random suffix generated """ if self.random_alias_suffix == AliasSuffixEnum.random_string.value: return random_string(config.ALIAS_RANDOM_SUFFIX_LENGTH, include_digits=True) if custom_domain is None: return random_words(1, 3) return random_words(1) def can_create_contacts(self) -> bool: if self.is_premium(): return True if self.flags & User.FLAG_FREE_DISABLE_CREATE_ALIAS == 0: return True return not config.DISABLE_CREATE_CONTACTS_FOR_FREE_USERS def __repr__(self): return f"<User {self.id} {self.name} {self.email}>" class 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"),) def sanitize_email(email_address: str, not_lower=False) -> str: if email_address: email_address = email_address.strip().replace(" ", "").replace("\n", " ") if not not_lower: email_address = email_address.lower() return email_address.replace("\u200f", "") def sanitize_next_url(url: Optional[str]) -> Optional[str]: return NextUrlSanitizer.sanitize(url, ALLOWED_REDIRECT_DOMAINS) def oidc_callback(): if SESSION_STATE_KEY not in session: flash("Invalid state, please retry", "error") return redirect(url_for("auth.login")) if config.OIDC_CLIENT_ID is None or config.OIDC_CLIENT_SECRET is None: return redirect(url_for("auth.login")) # user clicks on cancel if "error" in request.args: flash("Please use another sign in method then", "warning") return redirect("/") oidc = OAuth2Session( config.OIDC_CLIENT_ID, state=session[SESSION_STATE_KEY], scope=[OIDC_SCOPES], redirect_uri=_redirect_uri, ) oidc.fetch_token( OIDC_TOKEN_URL, client_secret=config.OIDC_CLIENT_SECRET, authorization_response=request.url, ) oidc_user_data = oidc.get(OIDC_USER_INFO_URL) if oidc_user_data.status_code != 200: LOG.e( f"cannot get oidc user data {oidc_user_data.status_code} {oidc_user_data.text}" ) flash( "Cannot get user data from OIDC, please use another way to login/sign up", "error", ) return redirect(url_for("auth.login")) oidc_user_data = oidc_user_data.json() email = oidc_user_data.get("email") if not email: LOG.e(f"cannot get email for OIDC user {oidc_user_data} {email}") flash( "Cannot get a valid email from OIDC, please another way to login/sign up", "error", ) return redirect(url_for("auth.login")) email = sanitize_email(email) user = User.get_by(email=email) if not user and config.DISABLE_REGISTRATION: flash( "Sorry you cannot sign up via the OIDC provider. Please sign-up first with your email.", "error", ) return redirect(url_for("auth.register")) elif not user: user = create_user(email, oidc_user_data) if not SocialAuth.get_by(user_id=user.id, social="oidc"): SocialAuth.create(user_id=user.id, social="oidc") Session.commit() # The activation link contains the original page, for ex authorize page next_url = sanitize_next_url(request.args.get("next")) if request.args else None return after_login(user, next_url)
null
180,677
import arrow from flask import request, render_template, redirect, url_for, flash, session, g from flask_login import login_user from flask_wtf import FlaskForm from wtforms import StringField, validators from app.auth.base import auth_bp from app.config import MFA_USER_ID from app.db import Session from app.email_utils import send_invalid_totp_login_email from app.extensions import limiter from app.log import LOG from app.models import User, RecoveryCode from app.utils import sanitize_next_url class RecoveryForm(FlaskForm): MFA_USER_ID = "mfa_user_id" Session = scoped_session(sessionmaker(bind=connection)) Session: sqlalchemy.orm.Session def send_invalid_totp_login_email(user, totp_type): LOG = _get_logger("SL") class User(Base, ModelMixin, UserMixin, PasswordOracle): def directory_quota(self): def subdomain_quota(self): def created_by_partner(self): def subdomain_is_available(): def get_id(self): def create(cls, email, name="", password=None, from_partner=False, **kwargs): def get_active_subscription( self, include_partner_subscription: bool = True ) -> Optional[ Union[ Subscription | AppleSubscription | ManualSubscription | CoinbaseSubscription | PartnerSubscription ] ]: def get_active_subscription_end( self, include_partner_subscription: bool = True ) -> Optional[arrow.Arrow]: def lifetime_or_active_subscription( self, include_partner_subscription: bool = True ) -> bool: def is_paid(self) -> bool: def is_active(self) -> bool: def in_trial(self): def should_show_upgrade_button(self): def is_premium(self, include_partner_subscription: bool = True) -> bool: def upgrade_channel(self) -> str: def max_alias_for_free_account(self) -> int: def can_create_new_alias(self) -> bool: def can_send_or_receive(self) -> bool: def profile_picture_url(self): def suggested_emails(self, website_name) -> (str, [str]): def suggested_names(self) -> (str, [str]): def get_name_initial(self) -> str: def get_paddle_subscription(self) -> Optional["Subscription"]: def verified_custom_domains(self) -> List["CustomDomain"]: def mailboxes(self) -> List["Mailbox"]: def nb_directory(self): def has_custom_domain(self): def custom_domains(self): def available_domains_for_random_alias( self, alias_options: Optional[AliasOptions] = None ) -> List[Tuple[bool, str]]: def default_random_alias_domain(self) -> str: def fido_enabled(self) -> bool: def two_factor_authentication_enabled(self) -> bool: def get_communication_email(self) -> (Optional[str], str, bool): def available_sl_domains( self, alias_options: Optional[AliasOptions] = None ) -> [str]: def get_sl_domains( self, alias_options: Optional[AliasOptions] = None ) -> list["SLDomain"]: def available_alias_domains( self, alias_options: Optional[AliasOptions] = None ) -> [str]: def should_show_app_page(self) -> bool: def get_random_alias_suffix(self, custom_domain: Optional["CustomDomain"] = None): def can_create_contacts(self) -> bool: def __repr__(self): 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 sanitize_next_url(url: Optional[str]) -> Optional[str]: def recovery_route(): # passed from login page user_id = session.get(MFA_USER_ID) # user access this page directly without passing by login page if not user_id: flash("Unknown error, redirect back to main page", "warning") return redirect(url_for("auth.login")) user = User.get(user_id) if not user.two_factor_authentication_enabled(): flash("Only user with MFA enabled should go to this page", "warning") return redirect(url_for("auth.login")) recovery_form = RecoveryForm() next_url = sanitize_next_url(request.args.get("next")) if recovery_form.validate_on_submit(): code = recovery_form.code.data recovery_code = RecoveryCode.find_by_user_code(user, code) if recovery_code: if recovery_code.used: # Trigger rate limiter g.deduct_limit = True flash("Code already used", "error") else: del session[MFA_USER_ID] login_user(user) flash("Welcome back!", "success") recovery_code.used = True recovery_code.used_at = arrow.now() Session.commit() # User comes to login page from another page 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: # Trigger rate limiter g.deduct_limit = True flash("Incorrect code", "error") send_invalid_totp_login_email(user, "recovery") return render_template("auth/recovery.html", recovery_form=recovery_form)
null
180,678
import requests from flask import request, flash, render_template, redirect, url_for from flask_login import current_user from flask_wtf import FlaskForm from wtforms import StringField, validators from app import email_utils, config from app.auth.base import auth_bp from app.config import CONNECT_WITH_PROTON, CONNECT_WITH_OIDC_ICON from app.auth.views.login_utils import get_referral from app.config import URL, HCAPTCHA_SECRET, HCAPTCHA_SITEKEY from app.db import Session from app.email_utils import ( email_can_be_used_as_mailbox, personal_email_already_used, ) from app.events.auth_event import RegisterEvent from app.log import LOG from app.models import User, ActivationCode, DailyMetric from app.utils import random_string, encode_url, sanitize_email, canonicalize_email class RegisterForm(FlaskForm): email = StringField("Email", validators=[validators.DataRequired()]) password = StringField( "Password", validators=[validators.DataRequired(), validators.Length(min=8, max=100)], ) def send_activation_email(user, next_url): # the activation code is valid for 1h activation = ActivationCode.create(user_id=user.id, code=random_string(30)) Session.commit() # Send user activation email activation_link = f"{URL}/auth/activate?code={activation.code}" if next_url: LOG.d("redirect user to %s after activation", next_url) activation_link = activation_link + "&next=" + encode_url(next_url) email_utils.send_activation_email(user.email, activation_link) CONNECT_WITH_OIDC_ICON = os.environ.get("CONNECT_WITH_OIDC_ICON") CONNECT_WITH_PROTON = "CONNECT_WITH_PROTON" in os.environ HCAPTCHA_SECRET = os.environ.get("HCAPTCHA_SECRET") HCAPTCHA_SITEKEY = os.environ.get("HCAPTCHA_SITEKEY") def get_referral() -> Optional[Referral]: """Get the eventual referral stored in cookie""" # whether user arrives via a referral referral = None if request.cookies: ref_code = request.cookies.get(_REFERRAL_COOKIE) referral = Referral.get_by(code=ref_code) if not referral: if "slref" in session: ref_code = session["slref"] referral = Referral.get_by(code=ref_code) if referral: LOG.d("referral found %s", referral) return referral 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 RegisterEvent: class ActionType(EnumE): success = 0 failed = 1 catpcha_failed = 2 email_in_use = 3 invalid_email = 4 class Source(EnumE): web = 0 api = 1 def __init__(self, action: ActionType, source: Source = Source.web): self.action = action self.source = source def send(self): newrelic.agent.record_custom_event( "RegisterEvent", {"action": self.action.name, "source": self.source.name} ) 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 DailyMetric(Base, ModelMixin): """ For storing daily event-based metrics. The difference between DailyEventMetric and Metric2 is Metric2 stores the total whereas DailyEventMetric is reset for a new day """ __tablename__ = "daily_metric" date = sa.Column(sa.Date, nullable=False, unique=True) # users who sign up via web without using "Login with Proton" nb_new_web_non_proton_user = sa.Column( sa.Integer, nullable=False, server_default="0", default=0 ) nb_alias = sa.Column(sa.Integer, nullable=False, server_default="0", default=0) def get_or_create_today_metric() -> DailyMetric: today = arrow.utcnow().date() daily_metric = DailyMetric.get_by(date=today) if not daily_metric: daily_metric = DailyMetric.create( date=today, nb_new_web_non_proton_user=0, nb_alias=0 ) return daily_metric 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", "") def register(): if current_user.is_authenticated: LOG.d("user is already authenticated, redirect to dashboard") flash("You are already logged in", "warning") return redirect(url_for("dashboard.index")) if config.DISABLE_REGISTRATION: flash("Registration is closed", "error") return redirect(url_for("auth.login")) form = RegisterForm(request.form) next_url = request.args.get("next") if form.validate_on_submit(): # only check if hcaptcha is enabled if HCAPTCHA_SECRET: # check with hCaptcha token = request.form.get("h-captcha-response") params = {"secret": HCAPTCHA_SECRET, "response": token} hcaptcha_res = requests.post( "https://hcaptcha.com/siteverify", data=params ).json() # return something like # {'success': True, # 'challenge_ts': '2020-07-23T10:03:25', # 'hostname': '127.0.0.1'} if not hcaptcha_res["success"]: LOG.w( "User put wrong captcha %s %s", form.email.data, hcaptcha_res, ) flash("Wrong Captcha", "error") RegisterEvent(RegisterEvent.ActionType.catpcha_failed).send() return render_template( "auth/register.html", form=form, next_url=next_url, HCAPTCHA_SITEKEY=HCAPTCHA_SITEKEY, ) email = canonicalize_email(form.email.data) if not email_can_be_used_as_mailbox(email): flash("You cannot use this email address as your personal inbox.", "error") RegisterEvent(RegisterEvent.ActionType.email_in_use).send() else: sanitized_email = sanitize_email(form.email.data) if personal_email_already_used(email) or personal_email_already_used( sanitized_email ): flash(f"Email {email} already used", "error") RegisterEvent(RegisterEvent.ActionType.email_in_use).send() else: LOG.d("create user %s", email) user = User.create( email=email, name=form.email.data, password=form.password.data, referral=get_referral(), ) Session.commit() try: send_activation_email(user, next_url) RegisterEvent(RegisterEvent.ActionType.success).send() DailyMetric.get_or_create_today_metric().nb_new_web_non_proton_user += 1 Session.commit() except Exception: flash("Invalid email, are you sure the email is correct?", "error") RegisterEvent(RegisterEvent.ActionType.invalid_email).send() return redirect(url_for("auth.register")) return render_template("auth/register_waiting_activation.html") return render_template( "auth/register.html", form=form, next_url=next_url, HCAPTCHA_SITEKEY=HCAPTCHA_SITEKEY, connect_with_proton=CONNECT_WITH_PROTON, connect_with_oidc=config.OIDC_CLIENT_ID is not None, connect_with_oidc_icon=CONNECT_WITH_OIDC_ICON, )
null
180,679
import requests from flask import request, session, redirect, flash, url_for from flask_limiter.util import get_remote_address from flask_login import current_user from requests_oauthlib import OAuth2Session from typing import Optional from app.auth.base import auth_bp from app.auth.views.login_utils import after_login from app.config import ( PROTON_BASE_URL, PROTON_CLIENT_ID, PROTON_CLIENT_SECRET, PROTON_EXTRA_HEADER_NAME, PROTON_EXTRA_HEADER_VALUE, PROTON_VALIDATE_CERTS, URL, ) from app.log import LOG from app.models import ApiKey, User from app.proton.proton_client import HttpProtonClient, convert_access_token from app.proton.proton_callback_handler import ( ProtonCallbackHandler, Action, ) from app.proton.utils import get_proton_partner from app.utils import sanitize_next_url, sanitize_scheme _authorization_base_url = PROTON_BASE_URL + "/oauth/authorize" _redirect_uri = URL + "/auth/proton/callback" SESSION_ACTION_KEY = "oauth_action" SESSION_STATE_KEY = "oauth_state" def extract_action() -> Optional[Action]: action = request.args.get("action") if action is not None: if action == "link": return Action.Link elif action == "login": return Action.Login else: LOG.w(f"Unknown action received: {action}") return None return Action.Login PROTON_CLIENT_ID = os.environ.get("PROTON_CLIENT_ID") PROTON_CLIENT_SECRET = os.environ.get("PROTON_CLIENT_SECRET") class Action(Enum): Login = 1 Link = 2 def sanitize_next_url(url: Optional[str]) -> Optional[str]: return NextUrlSanitizer.sanitize(url, ALLOWED_REDIRECT_DOMAINS) def sanitize_scheme(scheme: Optional[str]) -> Optional[str]: if not scheme: return None if scheme in ["http", "https"]: return None scheme_regex = re.compile("^[a-z.]+$") if scheme_regex.match(scheme): return scheme return None def proton_login(): if PROTON_CLIENT_ID is None or PROTON_CLIENT_SECRET is None: return redirect(url_for("auth.login")) action = extract_action() if action is None: return redirect(url_for("auth.login")) if action == Action.Link and not current_user.is_authenticated: return redirect(url_for("auth.login")) next_url = sanitize_next_url(request.args.get("next")) if next_url: session["oauth_next"] = next_url elif "oauth_next" in session: del session["oauth_next"] scheme = sanitize_scheme(request.args.get("scheme")) if scheme: session["oauth_scheme"] = scheme elif "oauth_scheme" in session: del session["oauth_scheme"] mode = request.args.get("mode", "session") if mode == "apikey": session["oauth_mode"] = "apikey" else: session["oauth_mode"] = "session" proton = OAuth2Session(PROTON_CLIENT_ID, redirect_uri=_redirect_uri) authorization_url, state = proton.authorization_url(_authorization_base_url) # State is used to prevent CSRF, keep this for later. session[SESSION_STATE_KEY] = state session[SESSION_ACTION_KEY] = action.value return redirect(authorization_url)
null
180,680
import requests from flask import request, session, redirect, flash, url_for from flask_limiter.util import get_remote_address from flask_login import current_user from requests_oauthlib import OAuth2Session from typing import Optional from app.auth.base import auth_bp from app.auth.views.login_utils import after_login from app.config import ( PROTON_BASE_URL, PROTON_CLIENT_ID, PROTON_CLIENT_SECRET, PROTON_EXTRA_HEADER_NAME, PROTON_EXTRA_HEADER_VALUE, PROTON_VALIDATE_CERTS, URL, ) from app.log import LOG from app.models import ApiKey, User from app.proton.proton_client import HttpProtonClient, convert_access_token from app.proton.proton_callback_handler import ( ProtonCallbackHandler, Action, ) from app.proton.utils import get_proton_partner from app.utils import sanitize_next_url, sanitize_scheme _token_url = PROTON_BASE_URL + "/oauth/token" _redirect_uri = URL + "/auth/proton/callback" SESSION_STATE_KEY = "oauth_state" DEFAULT_SCHEME = "auth.simplelogin" def get_api_key_for_user(user: User) -> str: ak = ApiKey.create( user_id=user.id, name="Created via Login with Proton on mobile app", commit=True, ) return ak.code def get_action_from_state() -> Action: oauth_action = session[SESSION_ACTION_KEY] if oauth_action == Action.Login.value: return Action.Login elif oauth_action == Action.Link.value: return Action.Link raise Exception(f"Unknown action in state: {oauth_action}") def after_login(user, next_url, login_from_proton: bool = False): """ Redirect to the correct page after login. If the user is logged in with Proton, do not look at fido nor otp If user enables MFA: redirect user to MFA page Otherwise redirect to dashboard page if no next_url """ if not login_from_proton: if user.fido_enabled(): # Use the same session for FIDO so that we can easily # switch between these two 2FA option session[MFA_USER_ID] = user.id if next_url: return redirect(url_for("auth.fido", next=next_url)) else: return redirect(url_for("auth.fido")) elif user.enable_otp: session[MFA_USER_ID] = user.id if next_url: return redirect(url_for("auth.mfa", next=next_url)) else: return redirect(url_for("auth.mfa")) LOG.d("log user %s in", user) login_user(user) session["sudo_time"] = int(time()) # User comes to login page from another page 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")) PROTON_CLIENT_ID = os.environ.get("PROTON_CLIENT_ID") PROTON_CLIENT_SECRET = os.environ.get("PROTON_CLIENT_SECRET") PROTON_BASE_URL = os.environ.get( "PROTON_BASE_URL", "https://account.protonmail.com/api" ) PROTON_VALIDATE_CERTS = "PROTON_VALIDATE_CERTS" in os.environ PROTON_EXTRA_HEADER_NAME = os.environ.get("PROTON_EXTRA_HEADER_NAME") PROTON_EXTRA_HEADER_VALUE = os.environ.get("PROTON_EXTRA_HEADER_VALUE") LOG = _get_logger("SL") def convert_access_token(access_token_response: str) -> AccessCredentials: """ The Access token response contains both the Proton Session ID and the Access Token. The Session ID is necessary in order to use the Proton API. However, the OAuth response does not allow us to return extra content. This method takes the Access token response and extracts the session ID and the access token. """ parts = access_token_response.split("-") if len(parts) != 3: raise Exception("Invalid access token response") if parts[0] != "pt": raise Exception("Invalid access token response format") return AccessCredentials( session_id=parts[1], access_token=parts[2], ) class HttpProtonClient(ProtonClient): def __init__( self, base_url: str, credentials: AccessCredentials, original_ip: Optional[str], verify: bool = True, ): self.base_url = base_url self.access_token = credentials.access_token client = Session() client.verify = verify headers = { "x-pm-appversion": _APP_VERSION, "x-pm-apiversion": "3", "x-pm-uid": credentials.session_id, "authorization": f"Bearer {credentials.access_token}", "accept": "application/vnd.protonmail.v1+json", "user-agent": "ProtonOauthClient", } if PROTON_EXTRA_HEADER_NAME and PROTON_EXTRA_HEADER_VALUE: headers[PROTON_EXTRA_HEADER_NAME] = PROTON_EXTRA_HEADER_VALUE if original_ip is not None: headers["x-forwarded-for"] = original_ip client.headers.update(headers) self.client = client def get_user(self) -> Optional[UserInformation]: info = self.__get("/simple_login/v1/subscription")["Subscription"] if not info["IsAllowed"]: LOG.debug("Account is not allowed to log into SL") return None plan_value = info["Plan"] if plan_value == PLAN_FREE: plan = SLPlan(type=SLPlanType.Free, expiration=None) elif plan_value == PLAN_PREMIUM: plan = SLPlan( type=SLPlanType.Premium, expiration=Arrow.fromtimestamp(info["PlanExpiration"], tzinfo="utc"), ) else: raise Exception(f"Invalid value for plan: {plan_value}") return UserInformation( email=info.get("Email"), name=info.get("DisplayName"), id=info.get("UserID"), plan=plan, ) def __get(self, route: str) -> dict: url = f"{self.base_url}{route}" res = self.client.get(url) return self.__validate_response(res) def __validate_response(res: Response) -> dict: status = res.status_code as_json = res.json() if status != HTTPStatus.OK: raise HttpProtonClient.__handle_response_not_ok( status=status, body=as_json, text=res.text ) res_code = as_json.get("Code") if not res_code or res_code != 1000: raise Exception( f"Unexpected response code. Wanted 1000 and got {res_code}: " + res.text ) return as_json class Action(Enum): Login = 1 Link = 2 class ProtonCallbackHandler: def __init__(self, proton_client: ProtonClient): self.proton_client = proton_client def handle_login(self, partner: Partner) -> ProtonCallbackResult: try: user = self.__get_partner_user() if user is None: return generate_account_not_allowed_to_log_in() res = process_login_case(user, partner) return ProtonCallbackResult( redirect_to_login=False, flash_message=None, flash_category=None, redirect=None, user=res.user, ) except LinkException as e: return ProtonCallbackResult( redirect_to_login=True, flash_message=e.message, flash_category="error", redirect=None, user=None, ) def handle_link( self, current_user: Optional[User], partner: Partner, ) -> ProtonCallbackResult: if current_user is None: raise Exception("Cannot link account with current_user being None") try: user = self.__get_partner_user() if user is None: return generate_account_not_allowed_to_log_in() res = process_link_case(user, current_user, partner) return ProtonCallbackResult( redirect_to_login=False, flash_message="Account successfully linked", flash_category="success", redirect=url_for("dashboard.setting"), user=res.user, ) except LinkException as e: return ProtonCallbackResult( redirect_to_login=False, flash_message=e.message, flash_category="error", redirect=None, user=None, ) def __get_partner_user(self) -> Optional[PartnerLinkRequest]: proton_user = self.__get_proton_user() if proton_user is None: return None return PartnerLinkRequest( email=proton_user.email, external_user_id=proton_user.id, name=proton_user.name, plan=proton_user.plan, from_partner=False, # The user has started this flow, so we don't mark it as created by a partner ) def __get_proton_user(self) -> Optional[ProtonUser]: user = self.proton_client.get_user() if user is None: return None return ProtonUser(email=user.email, plan=user.plan, name=user.name, id=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 proton_callback(): if SESSION_STATE_KEY not in session or SESSION_STATE_KEY not in session: flash("Invalid state, please retry", "error") return redirect(url_for("auth.login")) if PROTON_CLIENT_ID is None or PROTON_CLIENT_SECRET is None: return redirect(url_for("auth.login")) # user clicks on cancel if "error" in request.args: flash("Please use another sign in method then", "warning") return redirect("/") proton = OAuth2Session( PROTON_CLIENT_ID, state=session[SESSION_STATE_KEY], redirect_uri=_redirect_uri, ) def check_status_code(response: requests.Response) -> requests.Response: if response.status_code != 200: raise Exception( f"Bad Proton API response [status={response.status_code}]: {response.json()}" ) return response proton.register_compliance_hook("access_token_response", check_status_code) headers = None if PROTON_EXTRA_HEADER_NAME and PROTON_EXTRA_HEADER_VALUE: headers = {PROTON_EXTRA_HEADER_NAME: PROTON_EXTRA_HEADER_VALUE} try: token = proton.fetch_token( _token_url, client_secret=PROTON_CLIENT_SECRET, authorization_response=request.url, verify=PROTON_VALIDATE_CERTS, method="GET", include_client_id=True, headers=headers, ) except Exception as e: LOG.warning(f"Error fetching Proton token: {e}") flash("There was an error in the login process", "error") return redirect(url_for("auth.login")) credentials = convert_access_token(token["access_token"]) action = get_action_from_state() proton_client = HttpProtonClient( PROTON_BASE_URL, credentials, get_remote_address(), verify=PROTON_VALIDATE_CERTS ) handler = ProtonCallbackHandler(proton_client) proton_partner = get_proton_partner() next_url = session.get("oauth_next") if action == Action.Login: res = handler.handle_login(proton_partner) elif action == Action.Link: res = handler.handle_link(current_user, proton_partner) else: raise Exception(f"Unknown Action: {action.name}") if res.flash_message is not None: flash(res.flash_message, res.flash_category) oauth_scheme = session.get("oauth_scheme") if session.get("oauth_mode", "session") == "apikey": apikey = get_api_key_for_user(res.user) scheme = oauth_scheme or DEFAULT_SCHEME return redirect(f"{scheme}:///login?apikey={apikey}") if res.redirect_to_login: return redirect(url_for("auth.login")) if next_url and next_url[0] == "/" and oauth_scheme: next_url = f"{oauth_scheme}://{next_url}" redirect_url = next_url or res.redirect return after_login(res.user, redirect_url, login_from_proton=True)
null
180,681
import uuid from flask import request, flash, render_template, url_for, g from flask_wtf import FlaskForm from wtforms import StringField, validators from app.auth.base import auth_bp from app.auth.views.login_utils import after_login from app.db import Session from app.extensions import limiter from app.models import ResetPasswordCode class ResetPasswordForm(FlaskForm): def after_login(user, next_url, login_from_proton: bool = False): Session = scoped_session(sessionmaker(bind=connection)) Session: sqlalchemy.orm.Session class ResetPasswordCode(Base, ModelMixin): def is_expired(self): def reset_password(): form = ResetPasswordForm(request.form) reset_password_code_str = request.args.get("code") reset_password_code: ResetPasswordCode = ResetPasswordCode.get_by( code=reset_password_code_str ) if not reset_password_code: # Trigger rate limiter g.deduct_limit = True error = ( "The reset password link can be used only once. " "Please request a new link to reset password." ) return render_template("auth/reset_password.html", form=form, error=error) if reset_password_code.is_expired(): error = "The link has been already expired. Please make a new request of the reset password link" return render_template("auth/reset_password.html", form=form, error=error) if form.validate_on_submit(): user = reset_password_code.user new_password = form.password.data # avoid user reusing the old password if user.check_password(new_password): error = "You cannot reuse the same password" return render_template("auth/reset_password.html", form=form, error=error) user.set_password(new_password) flash("Your new password has been set", "success") # this can be served to activate user too user.activated = True # remove all reset password codes ResetPasswordCode.filter_by(user_id=user.id).delete() # change the alternative_id to log user out on other browsers user.alternative_id = str(uuid.uuid4()) Session.commit() # do not use login_user(user) here # to make sure user needs to go through MFA if enabled return after_login(user, url_for("dashboard.index")) return render_template("auth/reset_password.html", form=form)
null
180,682
import pyotp from flask import ( render_template, redirect, url_for, flash, session, make_response, request, g, ) from flask_login import login_user from flask_wtf import FlaskForm from wtforms import BooleanField, StringField, validators from app.auth.base import auth_bp from app.config import MFA_USER_ID, URL from app.db import Session from app.email_utils import send_invalid_totp_login_email from app.extensions import limiter from app.models import User, MfaBrowser from app.utils import sanitize_next_url class OtpTokenForm(FlaskForm): token = StringField("Token", validators=[validators.DataRequired()]) remember = BooleanField( "attr", default=False, description="Remember this browser for 30 days" ) "10/minute", deduct_when=lambda r: hasattr(g, "deduct_limit") and g.deduct_limit URL = os.environ["URL"] MFA_USER_ID = "mfa_user_id" Session = scoped_session(sessionmaker(bind=connection)) Session: sqlalchemy.orm.Session def send_invalid_totp_login_email(user, totp_type): send_email_with_rate_control( user, config.ALERT_INVALID_TOTP_LOGIN, user.email, "Unsuccessful attempt to login to your SimpleLogin account", render( "transactional/invalid-totp-login.txt", type=totp_type, ), render( "transactional/invalid-totp-login.html", type=totp_type, ), 1, ) 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 MfaBrowser(Base, ModelMixin): __tablename__ = "mfa_browser" user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False) token = sa.Column(sa.String(64), default=False, unique=True, nullable=False) expires = sa.Column(ArrowType, default=False, nullable=False) user = orm.relationship(User) def create_new(cls, user, token_length=64) -> "MfaBrowser": found = False while not found: token = random_string(token_length) if not cls.get_by(token=token): found = True return MfaBrowser.create( user_id=user.id, token=token, expires=arrow.now().shift(days=30), ) def delete(cls, token): cls.filter(cls.token == token).delete() Session.commit() def delete_expired(cls): cls.filter(cls.expires < arrow.now()).delete() Session.commit() def is_expired(self): return self.expires < arrow.now() def reset_expire(self): self.expires = arrow.now().shift(days=30) def sanitize_next_url(url: Optional[str]) -> Optional[str]: return NextUrlSanitizer.sanitize(url, ALLOWED_REDIRECT_DOMAINS) def mfa(): # passed from login page user_id = session.get(MFA_USER_ID) # user access this page directly without passing by login page if not user_id: flash("Unknown error, redirect back to main page", "warning") return redirect(url_for("auth.login")) user = User.get(user_id) if not (user and user.enable_otp): flash("Only user with MFA enabled should go to this page", "warning") return redirect(url_for("auth.login")) otp_token_form = OtpTokenForm() next_url = sanitize_next_url(request.args.get("next")) if request.cookies.get("mfa"): browser = MfaBrowser.get_by(token=request.cookies.get("mfa")) if browser and not browser.is_expired() and browser.user_id == user.id: login_user(user) flash("Welcome back!", "success") # Redirect user to correct page return redirect(next_url or url_for("dashboard.index")) else: # Trigger rate limiter g.deduct_limit = True if otp_token_form.validate_on_submit(): totp = pyotp.TOTP(user.otp_secret) token = otp_token_form.token.data.replace(" ", "") if totp.verify(token, valid_window=2) and user.last_otp != token: del session[MFA_USER_ID] user.last_otp = token Session.commit() login_user(user) flash("Welcome back!", "success") # Redirect user to correct page response = make_response(redirect(next_url or url_for("dashboard.index"))) if otp_token_form.remember.data: browser = MfaBrowser.create_new(user=user) Session.commit() response.set_cookie( "mfa", value=browser.token, expires=browser.expires.datetime, secure=True if URL.startswith("https") else False, httponly=True, samesite="Lax", ) return response else: flash("Incorrect token", "warning") # Trigger rate limiter g.deduct_limit = True otp_token_form.token.data = None send_invalid_totp_login_email(user, "TOTP") return render_template( "auth/mfa.html", otp_token_form=otp_token_form, enable_fido=(user.fido_enabled()), next_url=next_url, )
null
180,683
import arrow from flask import redirect, url_for, request, flash from flask_login import login_user from app.auth.base import auth_bp from app.models import ApiToCookieToken from app.utils import sanitize_next_url class ApiToCookieToken(Base, ModelMixin): __tablename__ = "api_cookie_token" code = sa.Column(sa.String(128), unique=True, nullable=False) user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False) api_key_id = sa.Column(sa.ForeignKey(ApiKey.id, ondelete="cascade"), nullable=False) user = orm.relationship(User) api_key = orm.relationship(ApiKey) def create(cls, **kwargs): code = secrets.token_urlsafe(32) return super().create(code=code, **kwargs) def sanitize_next_url(url: Optional[str]) -> Optional[str]: return NextUrlSanitizer.sanitize(url, ALLOWED_REDIRECT_DOMAINS) def api_to_cookie(): code = request.args.get("token") if not code: flash("Missing token", "error") return redirect(url_for("auth.login")) token = ApiToCookieToken.get_by(code=code) if not token or token.created_at < arrow.now().shift(minutes=-5): flash("Missing token", "error") return redirect(url_for("auth.login")) user = token.user ApiToCookieToken.delete(token.id, commit=True) login_user(user) next_url = sanitize_next_url(request.args.get("next")) if next_url: return redirect(next_url) else: return redirect(url_for("dashboard.index"))
null
180,684
from flask import request, flash, render_template, redirect, url_for from flask_login import login_user from app.auth.base import auth_bp from app.db import Session from app.log import LOG from app.models import EmailChange, ResetPasswordCode Session = scoped_session(sessionmaker(bind=connection)) Session: sqlalchemy.orm.Session LOG = _get_logger("SL") class ResetPasswordCode(Base, ModelMixin): """For resetting password""" __tablename__ = "reset_password_code" user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False) code = sa.Column(sa.String(128), unique=True, nullable=False) user = orm.relationship(User) expired = sa.Column(ArrowType, nullable=False, default=_expiration_1h) def is_expired(self): return self.expired < arrow.now() 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 change_email(): code = request.args.get("code") email_change: EmailChange = EmailChange.get_by(code=code) if not email_change: return render_template("auth/change_email.html") if email_change.is_expired(): # delete the expired email EmailChange.delete(email_change.id) Session.commit() return render_template("auth/change_email.html") user = email_change.user old_email = user.email user.email = email_change.new_email EmailChange.delete(email_change.id) ResetPasswordCode.filter_by(user_id=user.id).delete() Session.commit() LOG.i(f"User {user} has changed their email from {old_email} to {user.email}") flash("Your new email has been updated", "success") login_user(user) return redirect(url_for("dashboard.index"))
null
180,685
import arrow from flask import render_template, flash, redirect, url_for, request from flask_login import login_required, current_user from app.db import Session from app.models import PhoneReservation, User from app.phone.base import phone_bp current_user: User Session = scoped_session(sessionmaker(bind=connection)) Session: sqlalchemy.orm.Session class PhoneReservation(Base, ModelMixin): def reservation_route(reservation_id: int): reservation: PhoneReservation = PhoneReservation.get(reservation_id) if not reservation or reservation.user_id != current_user.id: flash("Unknown error, redirect back to phone page", "warning") return redirect(url_for("phone.index")) phone_number = reservation.number if request.method == "POST": if request.form.get("form-name") == "release": time_left = reservation.end - arrow.now() if time_left.seconds > 0: current_user.phone_quota += time_left.seconds // 60 flash( f"Your phone quota is increased by {time_left.seconds // 60} minutes", "success", ) reservation.end = arrow.now() Session.commit() flash(f"{phone_number.number} is released", "success") return redirect(url_for("phone.index")) return render_template( "phone/phone_reservation.html", phone_number=phone_number, reservation=reservation, now=arrow.now(), )
null
180,686
import jwt from flask import request from jwt import InvalidSignatureError, DecodeError from app.config import ( PHONE_PROVIDER_2_HEADER, PHONE_PROVIDER_2_SECRET, ) from app.log import LOG from app.models import PhoneNumber, PhoneMessage from app.phone.base import phone_bp PHONE_PROVIDER_2_HEADER = os.environ.get("PHONE_PROVIDER_2_HEADER") PHONE_PROVIDER_2_SECRET = os.environ.get("PHONE_PROVIDER_2_SECRET") LOG = _get_logger("SL") class PhoneNumber(Base, ModelMixin): __tablename__ = "phone_number" country_id = sa.Column( sa.ForeignKey(PhoneCountry.id, ondelete="cascade"), nullable=False ) # with country code, e.g. +33612345678 number = sa.Column(sa.String(128), unique=True, nullable=False) active = sa.Column(sa.Boolean, nullable=False, default=True) # do not load this column comment = deferred(sa.Column(sa.Text, nullable=True)) country = orm.relationship(PhoneCountry) class PhoneMessage(Base, ModelMixin): __tablename__ = "phone_message" number_id = sa.Column( sa.ForeignKey(PhoneNumber.id, ondelete="cascade"), nullable=False ) from_number = sa.Column(sa.String(128), nullable=False) body = sa.Column(sa.Text) number = orm.relationship(PhoneNumber) def provider2_sms(): encoded = request.headers.get(PHONE_PROVIDER_2_HEADER) try: jwt.decode(encoded, key=PHONE_PROVIDER_2_SECRET, algorithms="HS256") except (InvalidSignatureError, DecodeError): LOG.e( "Unauthenticated callback %s %s %s %s", request.headers, request.method, request.args, request.json, ) return "not ok", 400 # request.json should be a dict where # msisdn is the sender # receiver is the receiver # For ex: # {'id': 2042489247, 'msisdn': 33612345678, 'country_code': 'FR', 'country_prefix': 33, 'receiver': 33687654321, # 'message': 'Test 1', 'senttime': 1641401781, 'webhook_label': 'Hagekar', 'sender': None, # 'mcc': None, 'mnc': None, 'validity_period': None, 'encoding': 'UTF8', 'udh': None, 'payload': None} to_number: str = str(request.json.get("receiver")) if not to_number.startswith("+"): to_number = "+" + to_number from_number = str(request.json.get("msisdn")) if not from_number.startswith("+"): from_number = "+" + from_number body = request.json.get("message") LOG.d("%s->%s:%s", from_number, to_number, body) phone_number = PhoneNumber.get_by(number=to_number) if phone_number: PhoneMessage.create( number_id=phone_number.id, from_number=from_number, body=body, commit=True, ) else: LOG.e("Unknown phone number %s %s", to_number, request.json) return "not ok", 200 return "ok", 200
null
180,687
from functools import wraps from flask import request, abort from twilio.request_validator import RequestValidator from twilio.twiml.messaging_response import MessagingResponse from app.config import TWILIO_AUTH_TOKEN from app.log import LOG from app.models import PhoneNumber, PhoneMessage from app.phone.base import phone_bp TWILIO_AUTH_TOKEN = os.environ.get("TWILIO_AUTH_TOKEN") The provided code snippet includes necessary dependencies for implementing the `validate_twilio_request` function. Write a Python function `def validate_twilio_request(f)` to solve the following problem: Validates that incoming requests genuinely originated from Twilio Here is the function: def validate_twilio_request(f): """Validates that incoming requests genuinely originated from Twilio""" @wraps(f) def decorated_function(*args, **kwargs): # Create an instance of the RequestValidator class validator = RequestValidator(TWILIO_AUTH_TOKEN) # Validate the request using its URL, POST data, # and X-TWILIO-SIGNATURE header request_valid = validator.validate( request.url, request.form, request.headers.get("X-TWILIO-SIGNATURE", "") ) # Continue processing the request if it's valid, return a 403 error if # it's not if request_valid: return f(*args, **kwargs) else: return abort(403) return decorated_function
Validates that incoming requests genuinely originated from Twilio
180,688
from functools import wraps from flask import request, abort from twilio.request_validator import RequestValidator from twilio.twiml.messaging_response import MessagingResponse from app.config import TWILIO_AUTH_TOKEN from app.log import LOG from app.models import PhoneNumber, PhoneMessage from app.phone.base import phone_bp LOG = _get_logger("SL") class PhoneNumber(Base, ModelMixin): __tablename__ = "phone_number" country_id = sa.Column( sa.ForeignKey(PhoneCountry.id, ondelete="cascade"), nullable=False ) # with country code, e.g. +33612345678 number = sa.Column(sa.String(128), unique=True, nullable=False) active = sa.Column(sa.Boolean, nullable=False, default=True) # do not load this column comment = deferred(sa.Column(sa.Text, nullable=True)) country = orm.relationship(PhoneCountry) class PhoneMessage(Base, ModelMixin): __tablename__ = "phone_message" number_id = sa.Column( sa.ForeignKey(PhoneNumber.id, ondelete="cascade"), nullable=False ) from_number = sa.Column(sa.String(128), nullable=False) body = sa.Column(sa.Text) number = orm.relationship(PhoneNumber) def twilio_sms(): LOG.d("%s %s %s", request.args, request.form, request.data) resp = MessagingResponse() to_number = request.form.get("To") from_number = request.form.get("From") body = request.form.get("Body") LOG.d("%s->%s:%s", from_number, to_number, body) phone_number = PhoneNumber.get_by(number=to_number) if phone_number: PhoneMessage.create( number_id=phone_number.id, from_number=from_number, body=body, commit=True, ) else: LOG.e("Unknown phone number %s %s", to_number, request.form) return str(resp)
null
180,689
from typing import Dict import arrow from flask import render_template, request, flash, redirect, url_for from flask_login import login_required, current_user from sqlalchemy import func from app.db import Session from app.models import PhoneCountry, PhoneNumber, PhoneReservation from app.phone.base import phone_bp def available_countries() -> [PhoneCountry]: now = arrow.now() phone_count_by_countries: Dict[PhoneCountry, int] = dict() for country, count in ( Session.query(PhoneCountry, func.count(PhoneNumber.id)) .join(PhoneNumber, PhoneNumber.country_id == PhoneCountry.id) .filter(PhoneNumber.active.is_(True)) .group_by(PhoneCountry) .all() ): phone_count_by_countries[country] = count busy_phone_count_by_countries: Dict[PhoneCountry, int] = dict() for country, count in ( Session.query(PhoneCountry, func.count(PhoneNumber.id)) .join(PhoneNumber, PhoneNumber.country_id == PhoneCountry.id) .join(PhoneReservation, PhoneReservation.number_id == PhoneNumber.id) .filter(PhoneReservation.start < now, PhoneReservation.end > now) .group_by(PhoneCountry) .all() ): busy_phone_count_by_countries[country] = count ret = [] for country in phone_count_by_countries: if ( country not in busy_phone_count_by_countries or phone_count_by_countries[country] > busy_phone_count_by_countries[country] ): ret.append(country) return ret Session = scoped_session(sessionmaker(bind=connection)) Session: sqlalchemy.orm.Session class PhoneCountry(Base, ModelMixin): __tablename__ = "phone_country" name = sa.Column(sa.String(128), unique=True, nullable=False) class PhoneNumber(Base, ModelMixin): __tablename__ = "phone_number" country_id = sa.Column( sa.ForeignKey(PhoneCountry.id, ondelete="cascade"), nullable=False ) # with country code, e.g. +33612345678 number = sa.Column(sa.String(128), unique=True, nullable=False) active = sa.Column(sa.Boolean, nullable=False, default=True) # do not load this column comment = deferred(sa.Column(sa.Text, nullable=True)) country = orm.relationship(PhoneCountry) class PhoneReservation(Base, ModelMixin): __tablename__ = "phone_reservation" number_id = sa.Column( sa.ForeignKey(PhoneNumber.id, ondelete="cascade"), nullable=False ) user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False) number = orm.relationship(PhoneNumber) start = sa.Column(ArrowType, nullable=False) end = sa.Column(ArrowType, nullable=False) def index(): if not current_user.can_use_phone: flash("You can't use this page", "error") return redirect(url_for("dashboard.index")) countries = available_countries() now = arrow.now() reservations = PhoneReservation.filter( PhoneReservation.user_id == current_user.id, PhoneReservation.start < now, PhoneReservation.end > now, ).all() past_reservations = PhoneReservation.filter( PhoneReservation.user_id == current_user.id, PhoneReservation.end <= now, ).all() if request.method == "POST": try: nb_minute = int(request.form.get("minute")) except ValueError: flash("Number of minutes must be specified", "error") return redirect(request.url) if current_user.phone_quota < nb_minute: flash( f"You don't have enough phone quota. Current quota is {current_user.phone_quota}", "error", ) return redirect(request.url) country_id = request.form.get("country") country = PhoneCountry.get(country_id) # get the first phone number available now = arrow.now() busy_phone_number_subquery = ( Session.query(PhoneReservation.number_id) .filter(PhoneReservation.start < now, PhoneReservation.end > now) .subquery() ) phone_number = ( Session.query(PhoneNumber) .filter( PhoneNumber.country_id == country.id, PhoneNumber.id.notin_(busy_phone_number_subquery), PhoneNumber.active, ) .first() ) if phone_number: phone_reservation = PhoneReservation.create( number_id=phone_number.id, start=arrow.now(), end=arrow.now().shift(minutes=nb_minute), user_id=current_user.id, ) current_user.phone_quota -= nb_minute Session.commit() return redirect( url_for("phone.reservation_route", reservation_id=phone_reservation.id) ) else: flash( f"No phone number available for {country.name} during {nb_minute} minutes" ) return render_template( "phone/index.html", countries=countries, reservations=reservations, past_reservations=past_reservations, )
null
180,690
from typing import Dict import arrow from flask import render_template, request, flash, redirect, url_for from flask_login import login_required, current_user from sqlalchemy import func from app.db import Session from app.models import PhoneCountry, PhoneNumber, PhoneReservation from app.phone.base import phone_bp Session = scoped_session(sessionmaker(bind=connection)) Session: sqlalchemy.orm.Session class PhoneNumber(Base, ModelMixin): __tablename__ = "phone_number" country_id = sa.Column( sa.ForeignKey(PhoneCountry.id, ondelete="cascade"), nullable=False ) # with country code, e.g. +33612345678 number = sa.Column(sa.String(128), unique=True, nullable=False) active = sa.Column(sa.Boolean, nullable=False, default=True) # do not load this column comment = deferred(sa.Column(sa.Text, nullable=True)) country = orm.relationship(PhoneCountry) class PhoneReservation(Base, ModelMixin): __tablename__ = "phone_reservation" number_id = sa.Column( sa.ForeignKey(PhoneNumber.id, ondelete="cascade"), nullable=False ) user_id = sa.Column(sa.ForeignKey(User.id, ondelete="cascade"), nullable=False) number = orm.relationship(PhoneNumber) start = sa.Column(ArrowType, nullable=False) end = sa.Column(ArrowType, nullable=False) def available_numbers() -> [PhoneNumber]: Session.query(PhoneReservation).filter(PhoneReservation.start)
null
180,691
from flask import request from app.config import ( PHONE_PROVIDER_1_HEADER, PHONE_PROVIDER_1_SECRET, ) from app.log import LOG from app.models import PhoneNumber, PhoneMessage from app.phone.base import phone_bp PHONE_PROVIDER_1_HEADER = "X-SimpleLogin-Secret" PHONE_PROVIDER_1_SECRET = os.environ.get("PHONE_PROVIDER_1_SECRET") LOG = _get_logger("SL") class PhoneNumber(Base, ModelMixin): __tablename__ = "phone_number" country_id = sa.Column( sa.ForeignKey(PhoneCountry.id, ondelete="cascade"), nullable=False ) # with country code, e.g. +33612345678 number = sa.Column(sa.String(128), unique=True, nullable=False) active = sa.Column(sa.Boolean, nullable=False, default=True) # do not load this column comment = deferred(sa.Column(sa.Text, nullable=True)) country = orm.relationship(PhoneCountry) class PhoneMessage(Base, ModelMixin): __tablename__ = "phone_message" number_id = sa.Column( sa.ForeignKey(PhoneNumber.id, ondelete="cascade"), nullable=False ) from_number = sa.Column(sa.String(128), nullable=False) body = sa.Column(sa.Text) number = orm.relationship(PhoneNumber) def provider1_sms(): if request.headers.get(PHONE_PROVIDER_1_HEADER) != PHONE_PROVIDER_1_SECRET: LOG.e( "Unauthenticated callback %s %s %s %s", request.headers, request.method, request.args, request.data, ) return "not ok", 200 # request.form should be a dict that contains message_id, number, text, sim_card_number. # "number" is the contact number and "sim_card_number" the virtual number # The "reception_date" is in local time and shouldn't be used # For ex: # ImmutableMultiDict([('message_id', 'sms_0000000000000000000000'), ('number', '+33600112233'), # ('text', 'Lorem Ipsum is simply dummy text ...'), ('sim_card_number', '12345'), # ('reception_date', '2022-01-04 14:42:51')]) to_number = request.form.get("sim_card_number") from_number = request.form.get("number") body = request.form.get("text") LOG.d("%s->%s:%s", from_number, to_number, body) phone_number = PhoneNumber.get_by(number=to_number) if phone_number: PhoneMessage.create( number_id=phone_number.id, from_number=from_number, body=body, commit=True, ) else: LOG.e("Unknown phone number %s %s", to_number, request.form) return "not ok", 200 return "ok", 200
null
180,692
import uuid from datetime import timedelta from functools import wraps from typing import Callable, Any, Optional from flask import request from flask_login import current_user from limits.storage import RedisStorage from werkzeug import exceptions class _InnerLock: def __init__( self, lock_suffix: Optional[str] = None, max_wait_secs: int = 5, only_when: Optional[Callable[..., bool]] = None, ): self.lock_suffix = lock_suffix self.max_wait_secs = max_wait_secs self.only_when = only_when def acquire_lock(self, lock_name: str, lock_value: str): if not lock_redis.storage.set( lock_name, lock_value, ex=timedelta(seconds=self.max_wait_secs), nx=True ): raise exceptions.TooManyRequests() def release_lock(self, lock_name: str, lock_value: str): current_lock_value = lock_redis.storage.get(lock_name) if current_lock_value == lock_value.encode("utf-8"): lock_redis.storage.delete(lock_name) def __call__(self, f: Callable[..., Any]): if self.lock_suffix is None: lock_suffix = f.__name__ else: lock_suffix = self.lock_suffix def decorated(*args, **kwargs): if self.only_when and not self.only_when(): return f(*args, **kwargs) if not lock_redis: return f(*args, **kwargs) lock_value = str(uuid.uuid4())[:10] if "id" in dir(current_user): lock_name = f"cl:{current_user.id}:{lock_suffix}" else: lock_name = f"cl:{request.remote_addr}:{lock_suffix}" self.acquire_lock(lock_name, lock_value) try: return f(*args, **kwargs) finally: self.release_lock(lock_name, lock_value) return decorated def lock( name: Optional[str] = None, max_wait_secs: int = 5, only_when: Optional[Callable[..., bool]] = None, ): return _InnerLock(name, max_wait_secs, only_when)
null
180,693
from flask_limiter import Limiter from flask_limiter.util import get_remote_address from flask_login import current_user, LoginManager from app import config def __key_func(): if current_user.is_authenticated: return f"userid:{current_user.id}" else: ip_addr = get_remote_address() return f"ip:{ip_addr}"
null
180,694
from flask_limiter import Limiter from flask_limiter.util import get_remote_address from flask_login import current_user, LoginManager from app import config def disable_rate_limit(): return config.DISABLE_RATE_LIMIT
null
180,695
import os import random import socket import string from ast import literal_eval from typing import Callable, List from urllib.parse import urlparse from dotenv import load_dotenv def sl_getenv(env_var: str, default_factory: Callable = None): URL = os.environ["URL"] def get_allowed_redirect_domains() -> List[str]: allowed_domains = sl_getenv("ALLOWED_REDIRECT_DOMAINS", list) if allowed_domains: return allowed_domains parsed_url = urlparse(URL) return [parsed_url.hostname]
null
180,696
import os import random import socket import string from ast import literal_eval from typing import Callable, List from urllib.parse import urlparse from dotenv import load_dotenv if "ALIAS_DOMAINS" in os.environ: ALIAS_DOMAINS = sl_getenv("ALIAS_DOMAINS") # ["domain1.com", "domain2.com"] else: ALIAS_DOMAINS = OTHER_ALIAS_DOMAINS + [EMAIL_DOMAIN] if "DKIM_PRIVATE_KEY_PATH" in os.environ: DKIM_PRIVATE_KEY_PATH = get_abs_path(os.environ["DKIM_PRIVATE_KEY_PATH"]) with open(DKIM_PRIVATE_KEY_PATH) as f: DKIM_PRIVATE_KEY = f.read() if os.environ.get("GNUPGHOME"): GNUPGHOME = get_abs_path(os.environ.get("GNUPGHOME")) else: letters = string.ascii_lowercase random_dir_name = "".join(random.choice(letters) for _ in range(20)) GNUPGHOME = f"/tmp/{random_dir_name}" if not os.path.exists(GNUPGHOME): os.mkdir(GNUPGHOME, mode=0o700) print("WARNING: Use a temp directory for GNUPGHOME", GNUPGHOME) if "MAX_SPAM_SCORE" in os.environ: MAX_SPAM_SCORE = float(os.environ["MAX_SPAM_SCORE"]) else: MAX_SPAM_SCORE = 5.5 if "MAX_REPLY_PHASE_SPAM_SCORE" in os.environ: MAX_REPLY_PHASE_SPAM_SCORE = float(os.environ["MAX_REPLY_PHASE_SPAM_SCORE"]) else: MAX_REPLY_PHASE_SPAM_SCORE = 5 if "MIN_RSPAMD_SCORE_FOR_FAILED_DMARC" in os.environ: MIN_RSPAMD_SCORE_FOR_FAILED_DMARC = float( os.environ["MIN_RSPAMD_SCORE_FOR_FAILED_DMARC"] ) else: MIN_RSPAMD_SCORE_FOR_FAILED_DMARC = None def setup_nameservers(): nameservers = os.environ.get("NAMESERVERS", "1.1.1.1") return nameservers.split(",")
null
180,697
import os import random import socket import string from ast import literal_eval from typing import Callable, List from urllib.parse import urlparse from dotenv import load_dotenv if "ALIAS_DOMAINS" in os.environ: ALIAS_DOMAINS = sl_getenv("ALIAS_DOMAINS") # ["domain1.com", "domain2.com"] else: ALIAS_DOMAINS = OTHER_ALIAS_DOMAINS + [EMAIL_DOMAIN] if "DKIM_PRIVATE_KEY_PATH" in os.environ: DKIM_PRIVATE_KEY_PATH = get_abs_path(os.environ["DKIM_PRIVATE_KEY_PATH"]) with open(DKIM_PRIVATE_KEY_PATH) as f: DKIM_PRIVATE_KEY = f.read() if os.environ.get("GNUPGHOME"): GNUPGHOME = get_abs_path(os.environ.get("GNUPGHOME")) else: letters = string.ascii_lowercase random_dir_name = "".join(random.choice(letters) for _ in range(20)) GNUPGHOME = f"/tmp/{random_dir_name}" if not os.path.exists(GNUPGHOME): os.mkdir(GNUPGHOME, mode=0o700) print("WARNING: Use a temp directory for GNUPGHOME", GNUPGHOME) if "MAX_SPAM_SCORE" in os.environ: MAX_SPAM_SCORE = float(os.environ["MAX_SPAM_SCORE"]) else: MAX_SPAM_SCORE = 5.5 if "MAX_REPLY_PHASE_SPAM_SCORE" in os.environ: MAX_REPLY_PHASE_SPAM_SCORE = float(os.environ["MAX_REPLY_PHASE_SPAM_SCORE"]) else: MAX_REPLY_PHASE_SPAM_SCORE = 5 if "MIN_RSPAMD_SCORE_FOR_FAILED_DMARC" in os.environ: MIN_RSPAMD_SCORE_FOR_FAILED_DMARC = float( os.environ["MIN_RSPAMD_SCORE_FOR_FAILED_DMARC"] ) else: MIN_RSPAMD_SCORE_FOR_FAILED_DMARC = None def getRateLimitFromConfig( env_var: string, default: string = "" ) -> list[tuple[int, int]]: value = os.environ.get(env_var, default) if not value: return [] entries = [entry for entry in value.split(":")] limits = [] for entry in entries: fields = entry.split(",") limit = (int(fields[0]), int(fields[1])) limits.append(limit) return limits
null
180,698
import enum from typing import Set, Union import flask class Scope(enum.Enum): EMAIL = "email" NAME = "name" OPENID = "openid" AVATAR_URL = "avatar_url" def _split_arg(arg_input: Union[str, list]) -> Set[str]: """convert input response_type/scope into a set of string. arg_input = request.args.getlist(response_type|scope) Take into account different variations and their combinations - the split character is " " or "," - the response_type/scope passed as a list ?scope=scope_1&scope=scope_2 """ res = set() if isinstance(arg_input, str): if " " in arg_input: for x in arg_input.split(" "): if x: res.add(x.lower()) elif "," in arg_input: for x in arg_input.split(","): if x: res.add(x.lower()) else: res.add(arg_input) else: for arg in arg_input: res = res.union(_split_arg(arg)) return res def get_scopes(request: flask.Request) -> Set[Scope]: scope_strs = _split_arg(request.args.getlist("scope")) return set([Scope(scope_str) for scope_str in scope_strs])
null
180,699
from flask import render_template, redirect, url_for, flash from flask_login import current_user, login_required from flask_wtf import FlaskForm from wtforms import StringField, validators from app.db import Session from app.developer.base import developer_bp from app.models import Client class NewClientForm(FlaskForm): name = StringField("Name", validators=[validators.DataRequired()]) url = StringField("Url", validators=[validators.DataRequired()]) Session = scoped_session(sessionmaker(bind=connection)) Session: sqlalchemy.orm.Session 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 new_client(): form = NewClientForm() if form.validate_on_submit(): client = Client.create_new(form.name.data, current_user.id) client.home_url = form.url.data Session.commit() flash("Your website has been created", "success") return redirect( url_for("developer.client_detail", client_id=client.id, is_new=1) ) return render_template("developer/new_client.html", form=form)
null
180,700
from io import BytesIO from flask import request, render_template, redirect, url_for, flash from flask_login import current_user, login_required from flask_wtf import FlaskForm from flask_wtf.file import FileField from wtforms import StringField, validators, TextAreaField from app import s3 from app.config import ADMIN_EMAIL from app.db import Session from app.developer.base import developer_bp from app.email_utils import send_email from app.log import LOG from app.models import Client, RedirectUri, File, Referral from app.utils import random_string class EditClientForm(FlaskForm): class ApprovalClientForm(FlaskForm): 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, ): LOG = _get_logger("SL") class File(Base, ModelMixin): def get_url(self, expires_in=3600): def __repr__(self): class Client(Base, ModelMixin): def nb_user(self): def get_scopes(self) -> [Scope]: def create_new(cls, name, user_id) -> "Client": def get_icon_url(self): def last_user_login(self) -> "ClientUser": def random_string(length=10, include_digits=False): def client_detail(client_id): form = EditClientForm() approval_form = ApprovalClientForm() is_new = "is_new" in request.args action = request.args.get("action") client = Client.get(client_id) if not client or client.user_id != current_user.id: flash("you cannot see this app", "warning") return redirect(url_for("developer.index")) # can't set value for a textarea field in jinja if request.method == "GET": approval_form.description.data = client.description if action == "edit" and form.validate_on_submit(): client.name = form.name.data client.home_url = form.url.data if form.icon.data: # todo: remove current icon if any # todo: handle remove icon file_path = random_string(30) file = File.create(path=file_path, user_id=client.user_id) s3.upload_from_bytesio(file_path, BytesIO(form.icon.data.read())) Session.flush() LOG.d("upload file %s to s3", file) client.icon_id = file.id Session.flush() Session.commit() flash(f"{client.name} has been updated", "success") return redirect(url_for("developer.client_detail", client_id=client.id)) if action == "submit" and approval_form.validate_on_submit(): client.description = approval_form.description.data Session.commit() send_email( ADMIN_EMAIL, subject=f"{client.name} {client.id} submits for approval", plaintext="", html=f""" name: {client.name} <br> created: {client.created_at} <br> user: {current_user.email} <br> <br> {client.description} """, ) flash( "Thanks for submitting, we are informed and will come back to you asap!", "success", ) return redirect(url_for("developer.client_detail", client_id=client.id)) return render_template( "developer/client_details/basic_info.html", form=form, approval_form=approval_form, client=client, is_new=is_new, )
null
180,701
from io import BytesIO from flask import request, render_template, redirect, url_for, flash from flask_login import current_user, login_required from flask_wtf import FlaskForm from flask_wtf.file import FileField from wtforms import StringField, validators, TextAreaField from app import s3 from app.config import ADMIN_EMAIL from app.db import Session from app.developer.base import developer_bp from app.email_utils import send_email from app.log import LOG from app.models import Client, RedirectUri, File, Referral from app.utils import random_string class OAuthSettingForm(FlaskForm): pass Session = scoped_session(sessionmaker(bind=connection)) Session: sqlalchemy.orm.Session 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") def client_detail_oauth_setting(client_id): form = OAuthSettingForm() client = Client.get(client_id) if not client: flash("no such app", "warning") return redirect(url_for("developer.index")) if client.user_id != current_user.id: flash("you cannot see this app", "warning") return redirect(url_for("developer.index")) if form.validate_on_submit(): uris = request.form.getlist("uri") # replace all uris. TODO: optimize this? for redirect_uri in client.redirect_uris: RedirectUri.delete(redirect_uri.id) for uri in uris: RedirectUri.create(client_id=client_id, uri=uri) Session.commit() flash(f"{client.name} has been updated", "success") return redirect( url_for("developer.client_detail_oauth_setting", client_id=client.id) ) return render_template( "developer/client_details/oauth_setting.html", form=form, client=client )
null
180,702
from io import BytesIO from flask import request, render_template, redirect, url_for, flash from flask_login import current_user, login_required from flask_wtf import FlaskForm from flask_wtf.file import FileField from wtforms import StringField, validators, TextAreaField from app import s3 from app.config import ADMIN_EMAIL from app.db import Session from app.developer.base import developer_bp from app.email_utils import send_email from app.log import LOG from app.models import Client, RedirectUri, File, Referral from app.utils import random_string 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 client_detail_oauth_endpoint(client_id): client = Client.get(client_id) if not client: flash("no such app", "warning") return redirect(url_for("developer.index")) if client.user_id != current_user.id: flash("you cannot see this app", "warning") return redirect(url_for("developer.index")) return render_template( "developer/client_details/oauth_endpoint.html", client=client )
null
180,703
from io import BytesIO from flask import request, render_template, redirect, url_for, flash from flask_login import current_user, login_required from flask_wtf import FlaskForm from flask_wtf.file import FileField from wtforms import StringField, validators, TextAreaField from app import s3 from app.config import ADMIN_EMAIL from app.db import Session from app.developer.base import developer_bp from app.email_utils import send_email from app.log import LOG from app.models import Client, RedirectUri, File, Referral from app.utils import random_string class AdvancedForm(FlaskForm): pass 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 def client_detail_advanced(client_id): form = AdvancedForm() client = Client.get(client_id) if not client: flash("no such app", "warning") return redirect(url_for("developer.index")) if client.user_id != current_user.id: flash("you cannot see this app", "warning") return redirect(url_for("developer.index")) if form.validate_on_submit(): # delete client client_name = client.name Client.delete(client.id) Session.commit() LOG.d("Remove client %s", client) flash(f"{client_name} has been deleted", "success") return redirect(url_for("developer.index")) return render_template( "developer/client_details/advanced.html", form=form, client=client )
null
180,704
from io import BytesIO from flask import request, render_template, redirect, url_for, flash from flask_login import current_user, login_required from flask_wtf import FlaskForm from flask_wtf.file import FileField from wtforms import StringField, validators, TextAreaField from app import s3 from app.config import ADMIN_EMAIL from app.db import Session from app.developer.base import developer_bp from app.email_utils import send_email from app.log import LOG from app.models import Client, RedirectUri, File, Referral from app.utils import random_string Session = scoped_session(sessionmaker(bind=connection)) Session: sqlalchemy.orm.Session class Client(Base, ModelMixin): def nb_user(self): def get_scopes(self) -> [Scope]: def create_new(cls, name, user_id) -> "Client": def get_icon_url(self): def last_user_login(self) -> "ClientUser": class Referral(Base, ModelMixin): def nb_user(self) -> int: def nb_paid_user(self) -> int: def link(self): def __repr__(self): def client_detail_referral(client_id): client = Client.get(client_id) if not client: flash("no such app", "warning") return redirect(url_for("developer.index")) if client.user_id != current_user.id: flash("you cannot see this app", "warning") return redirect(url_for("developer.index")) if request.method == "POST": referral_id = request.form.get("referral-id") if not referral_id: flash("A referral must be selected", "error") return redirect(request.url) referral = Referral.get(referral_id) if not referral or referral.user_id != current_user.id: flash("something went wrong, refresh the page", "error") return redirect(request.url) client.referral_id = referral.id Session.commit() flash(f"Referral {referral.name} is now attached to {client.name}", "success") return render_template("developer/client_details/referral.html", client=client)
null
180,705
from flask import render_template from flask_login import current_user, login_required from app.developer.base import developer_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(user_id=current_user.id).all() return render_template("developer/index.html", clients=clients)
null
180,706
from app.build_info import SHA1 from app.monitor.base import monitor_bp SHA1 = "dev" def git_sha1(): return SHA1
null
180,707
from app.build_info import SHA1 from app.monitor.base import monitor_bp def live(): return "live"
null
180,708
from app.build_info import SHA1 from app.monitor.base import monitor_bp def test_exception(): raise Exception("to make sure sentry works") return "never reach here"
null
180,709
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 def get_ns(hostname) -> [str]: try: answers = _get_dns_resolver().resolve(hostname, "NS", search=True) except Exception: return [] return [a.to_text() for a in answers]
null