From d0776b770f6d42ffea02fb72fd502ebba1ed86cf Mon Sep 17 00:00:00 2001 From: Son NK <> Date: Sat, 4 Jul 2020 12:10:04 +0200 Subject: [PATCH] add GET /api/logout --- README.md | 15 ++++++++++++++- app/api/views/user_info.py | 20 +++++++++++++++++++- tests/api/test_user_info.py | 18 ++++++++++++++++++ 3 files changed, 51 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 572e0221..a8cbee97 100644 --- a/README.md +++ b/README.md @@ -791,7 +791,7 @@ 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 +#### POST /api/api_key Create a new API Key @@ -810,6 +810,19 @@ Output } ``` +#### GET /api/logout + +Log user out + +Input: +- `Authentication` header that contains the api key +- Or the correct cookie is set, i.e. user is already logged in on the web + +Output: +- 401 if user is not authenticated +- 200 if success + + ### Alias endpoints #### GET /api/v4/alias/options diff --git a/app/api/views/user_info.py b/app/api/views/user_info.py index e4cdf292..76290526 100644 --- a/app/api/views/user_info.py +++ b/app/api/views/user_info.py @@ -1,6 +1,8 @@ -from flask import jsonify, g, request +from flask import jsonify, g, request, make_response +from flask_login import logout_user from app.api.base import api_bp, require_api_auth +from app.config import SESSION_COOKIE_NAME from app.extensions import db from app.models import ApiKey @@ -43,3 +45,19 @@ def create_api_key(): db.session.commit() return jsonify(api_key=api_key.code), 201 + + +@api_bp.route("/logout", methods=["GET"]) +@require_api_auth +def logout(): + """ + Log user out on the web, i.e. remove the cookie + + Output: + - 200 + """ + logout_user() + response = make_response(jsonify(msg="User is logged out"), 200) + response.delete_cookie(SESSION_COOKIE_NAME) + + return response diff --git a/tests/api/test_user_info.py b/tests/api/test_user_info.py index 6ab734ee..ce2c9f25 100644 --- a/tests/api/test_user_info.py +++ b/tests/api/test_user_info.py @@ -54,3 +54,21 @@ def test_create_api_key(flask_client): assert r.status_code == 201 assert r.json["api_key"] + + +def test_logout(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, + ) + + # logout + r = flask_client.get(url_for("auth.logout"), follow_redirects=True,) + + assert r.status_code == 200