new_custom_alias.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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, User
  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. optional "note"
  22. Output:
  23. 201 if success
  24. 409 if the alias already exists
  25. """
  26. user: User = g.user
  27. if not user.can_create_new_alias():
  28. LOG.d("user %s cannot create any custom alias", user)
  29. return (
  30. jsonify(
  31. error="You have reached the limitation of a free account with the maximum of "
  32. f"{MAX_NB_EMAIL_FREE_PLAN} aliases, please upgrade your plan to create more aliases"
  33. ),
  34. 400,
  35. )
  36. user_custom_domains = [cd.domain for cd in user.verified_custom_domains()]
  37. hostname = request.args.get("hostname")
  38. data = request.get_json()
  39. if not data:
  40. return jsonify(error="request body cannot be empty"), 400
  41. alias_prefix = data.get("alias_prefix", "").strip()
  42. alias_suffix = data.get("alias_suffix", "").strip()
  43. note = data.get("note")
  44. alias_prefix = convert_to_id(alias_prefix)
  45. if not verify_prefix_suffix(user, alias_prefix, alias_suffix, user_custom_domains):
  46. return jsonify(error="wrong alias prefix or suffix"), 400
  47. full_alias = alias_prefix + alias_suffix
  48. if GenEmail.get_by(email=full_alias):
  49. LOG.d("full alias already used %s", full_alias)
  50. return jsonify(error=f"alias {full_alias} already exists"), 409
  51. gen_email = GenEmail.create(
  52. user_id=user.id, email=full_alias, mailbox_id=user.default_mailbox_id, note=note
  53. )
  54. db.session.commit()
  55. if hostname:
  56. AliasUsedOn.create(gen_email_id=gen_email.id, hostname=hostname)
  57. db.session.commit()
  58. return jsonify(alias=full_alias), 201