custom_domain.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. from flask import render_template, request, redirect, url_for, flash
  2. from flask_login import login_required, current_user
  3. from flask_wtf import FlaskForm
  4. from wtforms import StringField, validators
  5. from app.config import EMAIL_SERVERS_WITH_PRIORITY
  6. from app.dashboard.base import dashboard_bp
  7. from app.email_utils import get_email_domain_part
  8. from app.extensions import db
  9. from app.models import CustomDomain
  10. # todo: add more validation
  11. class NewCustomDomainForm(FlaskForm):
  12. domain = StringField("domain", validators=[validators.DataRequired()])
  13. @dashboard_bp.route("/custom_domain", methods=["GET", "POST"])
  14. @login_required
  15. def custom_domain():
  16. custom_domains = CustomDomain.query.filter_by(user_id=current_user.id).all()
  17. new_custom_domain_form = NewCustomDomainForm()
  18. errors = {}
  19. if request.method == "POST":
  20. if request.form.get("form-name") == "create":
  21. if not current_user.is_premium():
  22. flash("Only premium plan can add custom domain", "warning")
  23. return redirect(url_for("dashboard.custom_domain"))
  24. if new_custom_domain_form.validate():
  25. new_domain = new_custom_domain_form.domain.data.lower().strip()
  26. if CustomDomain.get_by(domain=new_domain):
  27. flash(f"{new_domain} already added", "warning")
  28. elif get_email_domain_part(current_user.email) == new_domain:
  29. flash(
  30. "You cannot add a domain that you are currently using for your personal email. "
  31. "Please change your personal email to your real email",
  32. "error",
  33. )
  34. else:
  35. new_custom_domain = CustomDomain.create(
  36. domain=new_domain, user_id=current_user.id
  37. )
  38. db.session.commit()
  39. flash(
  40. f"New domain {new_custom_domain.domain} is created", "success"
  41. )
  42. return redirect(
  43. url_for(
  44. "dashboard.domain_detail_dns",
  45. custom_domain_id=new_custom_domain.id,
  46. )
  47. )
  48. return render_template(
  49. "dashboard/custom_domain.html",
  50. custom_domains=custom_domains,
  51. new_custom_domain_form=new_custom_domain_form,
  52. EMAIL_SERVERS_WITH_PRIORITY=EMAIL_SERVERS_WITH_PRIORITY,
  53. errors=errors,
  54. )