2020-01-05 21:15:16 +01:00
|
|
|
from flask import g
|
|
|
|
from flask import jsonify, request
|
|
|
|
from flask_cors import cross_origin
|
|
|
|
|
2020-04-24 14:08:00 +02:00
|
|
|
from app.api.base import api_bp, require_api_auth
|
2020-05-23 19:18:24 +02:00
|
|
|
from app.api.serializer import (
|
|
|
|
get_alias_info_v2,
|
|
|
|
serialize_alias_info_v2,
|
|
|
|
)
|
2020-02-07 15:30:46 +01:00
|
|
|
from app.config import MAX_NB_EMAIL_FREE_PLAN
|
2020-01-05 21:15:16 +01:00
|
|
|
from app.extensions import db
|
|
|
|
from app.log import LOG
|
2020-03-17 11:51:40 +01:00
|
|
|
from app.models import Alias, AliasUsedOn, AliasGeneratorEnum
|
2020-01-05 21:15:16 +01:00
|
|
|
|
|
|
|
|
|
|
|
@api_bp.route("/alias/random/new", methods=["POST"])
|
|
|
|
@cross_origin()
|
2020-04-24 14:08:00 +02:00
|
|
|
@require_api_auth
|
2020-01-05 21:15:16 +01:00
|
|
|
def new_random_alias():
|
|
|
|
"""
|
|
|
|
Create a new random alias
|
2020-03-11 12:24:30 +01:00
|
|
|
Input:
|
|
|
|
(Optional) note
|
2020-01-05 21:15:16 +01:00
|
|
|
Output:
|
|
|
|
201 if success
|
|
|
|
|
|
|
|
"""
|
|
|
|
user = g.user
|
|
|
|
if not user.can_create_new_alias():
|
|
|
|
LOG.d("user %s cannot create new random alias", user)
|
|
|
|
return (
|
|
|
|
jsonify(
|
|
|
|
error=f"You have reached the limitation of a free account with the maximum of "
|
|
|
|
f"{MAX_NB_EMAIL_FREE_PLAN} aliases, please upgrade your plan to create more aliases"
|
|
|
|
),
|
|
|
|
400,
|
|
|
|
)
|
|
|
|
|
2020-03-11 12:24:30 +01:00
|
|
|
note = None
|
2020-03-11 14:02:35 +01:00
|
|
|
data = request.get_json(silent=True)
|
2020-03-11 12:24:30 +01:00
|
|
|
if data:
|
|
|
|
note = data.get("note")
|
|
|
|
|
2020-01-05 21:15:16 +01:00
|
|
|
scheme = user.alias_generator
|
2020-02-07 15:30:46 +01:00
|
|
|
mode = request.args.get("mode")
|
|
|
|
if mode:
|
|
|
|
if mode == "word":
|
|
|
|
scheme = AliasGeneratorEnum.word.value
|
|
|
|
elif mode == "uuid":
|
|
|
|
scheme = AliasGeneratorEnum.uuid.value
|
|
|
|
else:
|
|
|
|
return jsonify(error=f"{mode} must be either word or alias"), 400
|
|
|
|
|
2020-03-17 11:51:40 +01:00
|
|
|
alias = Alias.create_new_random(user=user, scheme=scheme, note=note)
|
2020-01-05 21:15:16 +01:00
|
|
|
db.session.commit()
|
|
|
|
|
|
|
|
hostname = request.args.get("hostname")
|
|
|
|
if hostname:
|
2020-03-20 12:29:11 +01:00
|
|
|
AliasUsedOn.create(alias_id=alias.id, hostname=hostname, user_id=alias.user_id)
|
2020-01-05 21:15:16 +01:00
|
|
|
db.session.commit()
|
|
|
|
|
2020-03-26 19:50:22 +01:00
|
|
|
return (
|
2020-05-23 19:18:24 +02:00
|
|
|
jsonify(alias=alias.email, **serialize_alias_info_v2(get_alias_info_v2(alias))),
|
2020-03-26 19:50:22 +01:00
|
|
|
201,
|
|
|
|
)
|