mirror of
https://github.com/simple-login/app.git
synced 2024-09-20 15:05:59 +08:00
Create POST /api/api_key
This commit is contained in:
parent
5b3ec91300
commit
0d3a3e0c48
19
README.md
19
README.md
|
@ -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
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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"]
|
||||
|
|
Loading…
Reference in a new issue