Add /api/v5/alias/options

This commit is contained in:
Son NK 2020-11-14 16:45:22 +01:00
parent f452c79aec
commit 9cfb6d412a
3 changed files with 147 additions and 14 deletions

View File

@ -306,3 +306,77 @@ def options_v4():
ret["suffixes"] = list([suffix[1], suffix[2]] for suffix in suffixes)
return jsonify(ret)
@api_bp.route("/v5/alias/options")
@require_api_auth
def options_v5():
"""
Return what options user has when creating new alias.
Same as v4 but uses a better format. To be used with /v2/alias/custom/new
Input:
a valid api-key in "Authentication" header and
optional "hostname" in args
Output: cf README
can_create: bool
suffixes: [
{
suffix: "suffix",
signed_suffix: "signed_suffix"
}
]
prefix_suggestion: str
recommendation: Optional dict
alias: str
hostname: str
"""
user = g.user
hostname = request.args.get("hostname")
ret = {
"can_create": user.can_create_new_alias(),
"suffixes": [],
"prefix_suggestion": "",
}
# recommendation alias if exist
if hostname:
# put the latest used alias first
q = (
db.session.query(AliasUsedOn, Alias, User)
.filter(
AliasUsedOn.alias_id == Alias.id,
Alias.user_id == user.id,
AliasUsedOn.hostname == hostname,
)
.order_by(desc(AliasUsedOn.created_at))
)
r = q.first()
if r:
_, alias, _ = r
LOG.d("found alias %s %s %s", alias, hostname, user)
ret["recommendation"] = {"alias": alias.email, "hostname": hostname}
# custom alias suggestion and suffix
if hostname:
# keep only the domain name of hostname, ignore TLD and subdomain
# for ex www.groupon.com -> groupon
domain_name = hostname
if "." in hostname:
parts = hostname.split(".")
domain_name = parts[-2]
domain_name = convert_to_id(domain_name)
ret["prefix_suggestion"] = domain_name
# List of (is_custom_domain, alias-suffix, time-signed alias-suffix)
suffixes = available_suffixes(user)
# custom domain should be put first
ret["suffixes"] = [
{"suffix": suffix[1], "signed_suffix": suffix[2]} for suffix in suffixes
]
return jsonify(ret)

View File

@ -190,7 +190,7 @@ Output:
### Alias endpoints
#### GET /api/v4/alias/options
#### GET /api/v5/alias/options
User alias info and suggestion. Used by the first extension screen when user opens the extension.
@ -200,25 +200,29 @@ Input:
Output: a json with the following field:
- can_create: boolean. Whether user can create new alias
- suffixes: list of `[suffix, signed-suffix]`. List of alias `suffix` that user can use. The `signed-suffix` is necessary to avoid request tampering.
- suffixes: list of dictionary with `suffix` and `signed-suffix`. List of alias `suffix` that user can use. The `signed-suffix` is necessary to avoid request tampering.
- prefix_suggestion: string. Suggestion for the `alias prefix`. Usually this is the website name extracted from `hostname`. If no `hostname`, then the `prefix_suggestion` is empty.
- recommendation: optional field, dictionary. If an alias is already used for this website, the recommendation will be returned. There are 2 subfields in `recommendation`: `alias` which is the recommended alias and `hostname` is the website on which this alias is used before.
For ex:
```json
{
"can_create": true,
"prefix_suggestion": "",
"suffixes": [
[
"@ab.cd",
"@ab.cd.Xq2BOA.zBebBB-QYikFkbPZ9CPKGpJ2-PU"
],
[
".yeah@local1.localhost",
".yeah@local1.localhost.Xq2BOA.dM9gyHyHcSXuJ8ps4i3wpJZ_Frw"
]
]
"can_create": true,
"prefix_suggestion": "test",
"suffixes": [
{
"signed_suffix": ".cat@d1.test.X6_7OQ.0e9NbZHE_bQvuAapT6NdBml9m6Q",
"suffix": ".cat@d1.test"
},
{
"signed_suffix": ".chat@d2.test.X6_7OQ.TTgCrfqPj7UmlY723YsDTHhkess",
"suffix": ".chat@d2.test"
},
{
"signed_suffix": ".yeah@sl.local.X6_7OQ.i8XL4xsMsn7dxDEWU8eF-Zap0qo",
"suffix": ".yeah@sl.local"
}
]
}
```

View File

@ -1,3 +1,5 @@
import json
from flask import url_for
from app.extensions import db
@ -194,3 +196,56 @@ def test_different_scenarios_v4(flask_client):
)
assert r.json["recommendation"]["alias"] == alias.email
assert r.json["recommendation"]["hostname"] == "www.test.com"
def test_different_scenarios_v5(flask_client):
user = User.create(
email="a@b.c", password="password", name="Test User", activated=True
)
db.session.commit()
# create api_key
api_key = ApiKey.create(user.id, "for test")
db.session.commit()
# <<< without hostname >>>
r = flask_client.get(
"/api/v5/alias/options", headers={"Authentication": api_key.code}
)
assert r.status_code == 200
assert r.json["can_create"]
assert r.json["suffixes"]
assert r.json["prefix_suggestion"] == "" # no hostname => no suggestion
for suffix_payload in r.json["suffixes"]:
suffix, signed_suffix = (
suffix_payload["suffix"],
suffix_payload["signed_suffix"],
)
assert signed_suffix.startswith(suffix)
# <<< with hostname >>>
r = flask_client.get(
"/api/v5/alias/options?hostname=www.test.com",
headers={"Authentication": api_key.code},
)
print(json.dumps(r.json, indent=2))
assert r.json["prefix_suggestion"] == "test"
# <<< with recommendation >>>
alias = Alias.create_new(user, prefix="test")
db.session.commit()
AliasUsedOn.create(
alias_id=alias.id, hostname="www.test.com", user_id=alias.user_id
)
db.session.commit()
r = flask_client.get(
url_for("api.options_v4", hostname="www.test.com"),
headers={"Authentication": api_key.code},
)
assert r.json["recommendation"]["alias"] == alias.email
assert r.json["recommendation"]["hostname"] == "www.test.com"