Create POST /api/api_key

This commit is contained in:
Son NK 2020-07-04 11:41:31 +02:00
parent 5b3ec91300
commit 0d3a3e0c48
3 changed files with 63 additions and 1 deletions

View File

@ -791,6 +791,25 @@ Output: if api key is correct, return a json with user name and whether user is
If api key is incorrect, return 401.
#### POST /api/api_key
Create a new API Key
Input:
- `Authentication` header that contains the api key
- Or the correct cookie is set, i.e. user is already logged in on the web
- device: device's name
Output
- 401 if user is not authenticated
- 201 with the `api_key`
```json
{
"api_key": "long string"
}
```
### Alias endpoints
#### GET /api/v4/alias/options

View File

@ -1,6 +1,8 @@
from flask import jsonify, g
from flask import jsonify, g, request
from app.api.base import api_bp, require_api_auth
from app.extensions import db
from app.models import ApiKey
@api_bp.route("/user_info")
@ -19,3 +21,25 @@ def user_info():
"in_trial": user.in_trial(),
}
)
@api_bp.route("/api_key", methods=["POST"])
@require_api_auth
def create_api_key():
"""Used to create a new api key
Input:
- device
Output:
- api_key
"""
data = request.get_json()
if not data:
return jsonify(error="request body cannot be empty"), 400
device = data.get("device")
api_key = ApiKey.create(user_id=g.user.id, name=device)
db.session.commit()
return jsonify(api_key=api_key.code), 201

View File

@ -35,3 +35,22 @@ def test_wrong_api_key(flask_client):
assert r.status_code == 401
assert r.json == {"error": "Wrong api key"}
def test_create_api_key(flask_client):
# create user, user is activated
User.create(email="a@b.c", password="password", name="Test User", activated=True)
db.session.commit()
# login user
flask_client.post(
url_for("auth.login"),
data={"email": "a@b.c", "password": "password"},
follow_redirects=True,
)
# create api key
r = flask_client.post(url_for("api.create_api_key"), json={"device": "Test device"})
assert r.status_code == 201
assert r.json["api_key"]