new_custom_alias.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. from flask import g
  2. from flask import jsonify, request
  3. from flask_cors import cross_origin
  4. from app.api.base import api_bp, verify_api_key
  5. from app.config import MAX_NB_EMAIL_FREE_PLAN
  6. from app.dashboard.views.custom_alias import verify_prefix_suffix
  7. from app.extensions import db
  8. from app.log import LOG
  9. from app.models import GenEmail, AliasUsedOn
  10. from app.utils import convert_to_id
  11. @api_bp.route("/alias/custom/new", methods=["POST"])
  12. @cross_origin()
  13. @verify_api_key
  14. def new_custom_alias():
  15. """
  16. Create a new custom alias
  17. Input:
  18. alias_prefix, for ex "www_groupon_com"
  19. alias_suffix, either .random_letters@simplelogin.co or @my-domain.com
  20. optional "hostname" in args
  21. Output:
  22. 201 if success
  23. 409 if the alias already exists
  24. """
  25. user = g.user
  26. if not user.can_create_new_alias():
  27. LOG.d("user %s cannot create any custom alias", user)
  28. return (
  29. jsonify(
  30. error="You have reached the limitation of a free account with the maximum of "
  31. f"{MAX_NB_EMAIL_FREE_PLAN} aliases, please upgrade your plan to create more aliases"
  32. ),
  33. 400,
  34. )
  35. user_custom_domains = [cd.domain for cd in user.verified_custom_domains()]
  36. hostname = request.args.get("hostname")
  37. data = request.get_json()
  38. if not data:
  39. return jsonify(error="request body cannot be empty"), 400
  40. alias_prefix = data.get("alias_prefix", "").strip()
  41. alias_suffix = data.get("alias_suffix", "").strip()
  42. alias_prefix = convert_to_id(alias_prefix)
  43. if not verify_prefix_suffix(user, alias_prefix, alias_suffix, user_custom_domains):
  44. return jsonify(error="wrong alias prefix or suffix"), 400
  45. full_alias = alias_prefix + alias_suffix
  46. if GenEmail.get_by(email=full_alias):
  47. LOG.d("full alias already used %s", full_alias)
  48. return jsonify(error=f"alias {full_alias} already exists"), 409
  49. gen_email = GenEmail.create(user_id=user.id, email=full_alias)
  50. db.session.commit()
  51. if hostname:
  52. AliasUsedOn.create(gen_email_id=gen_email.id, hostname=hostname)
  53. db.session.commit()
  54. return jsonify(alias=full_alias), 201