app-MAIL-temp/app/dashboard/views/custom_alias.py

66 lines
2.3 KiB
Python
Raw Normal View History

2019-08-30 22:42:06 +02:00
from flask import render_template, redirect, url_for, flash, request, session
2019-07-06 23:25:52 +02:00
from flask_login import login_required, current_user
from flask_wtf import FlaskForm
from wtforms import StringField, validators
2019-08-30 22:42:06 +02:00
from app.config import EMAIL_DOMAIN, HIGHLIGHT_GEN_EMAIL_ID
2019-07-06 23:25:52 +02:00
from app.dashboard.base import dashboard_bp
from app.extensions import db
from app.log import LOG
2019-11-18 15:10:16 +01:00
from app.models import GenEmail, DeletedAlias
2019-07-22 21:12:22 +02:00
from app.utils import convert_to_id, random_string
2019-07-06 23:25:52 +02:00
class CustomAliasForm(FlaskForm):
email = StringField("Email", validators=[validators.DataRequired()])
@dashboard_bp.route("/custom_alias", methods=["GET", "POST"])
@login_required
def custom_alias():
# check if user has the right to create custom alias
if not current_user.can_create_custom_email():
# notify admin
LOG.error("user %s tries to create custom alias", current_user)
flash("ony premium user can choose custom alias", "warning")
return redirect(url_for("dashboard.index"))
form = CustomAliasForm()
error = ""
if form.validate_on_submit():
email = form.email.data
email = convert_to_id(email)
2019-07-22 21:12:22 +02:00
email_suffix = request.form.get("email-suffix")
if len(email) < 3:
error = "email must be at least 3 letters"
2019-07-06 23:25:52 +02:00
else:
2019-07-22 21:12:22 +02:00
full_email = f"{email}.{email_suffix}@{EMAIL_DOMAIN}"
2019-07-06 23:25:52 +02:00
# check if email already exists
2019-11-18 15:10:16 +01:00
if GenEmail.get_by(email=full_email) or DeletedAlias.get_by(
email=full_email
):
2019-07-06 23:25:52 +02:00
error = "email already chosen, please choose another one"
else:
# create the new alias
LOG.d("create custom alias %s for user %s", full_email, current_user)
2019-08-30 22:42:06 +02:00
gen_email = GenEmail.create(
email=full_email, user_id=current_user.id, custom=True
)
2019-07-06 23:25:52 +02:00
db.session.commit()
flash(f"Email alias {full_email} has been created", "success")
2019-08-30 22:42:06 +02:00
session[HIGHLIGHT_GEN_EMAIL_ID] = gen_email.id
2019-07-06 23:25:52 +02:00
return redirect(url_for("dashboard.index"))
2019-07-22 21:12:22 +02:00
email_suffix = random_string(6)
return render_template(
"dashboard/custom_alias.html",
form=form,
error=error,
email_suffix=email_suffix,
EMAIL_DOMAIN=EMAIL_DOMAIN,
)