"""Token routes.""" from flask import jsonify, make_response, request from settings import db, app from auth import token_auth, basic_auth from models.user import User from errors import error_response # todo - put in basic_auth basic_auth.scheme = "Custom" basic_auth.realm = "Incorrect Credentials" @app.route("/api/auth/tokens", methods=["POST"]) @basic_auth.login_required def get_token(): """Get token.""" token = basic_auth.current_user().get_token() refresh_token = basic_auth.current_user().get_refresh_token() db.session.commit() response = make_response( jsonify( { "token": token, "username": basic_auth.current_user().username, "user_id": basic_auth.current_user().id, } ) ) response.set_cookie( "refresh_token", value=refresh_token, httponly=app.config["SESSION_COOKIE_HTTPONLY"], secure=app.config["SESSION_COOKIE_SECURE"], samesite=app.config["SESSION_COOKIE_SAMESITE"], ) return response @app.route("/api/auth/tokens", methods=["DELETE"]) @token_auth.login_required def revoke_token(): """Revoke token.""" token_auth.current_user().revoke_tokens() db.session.commit() response = make_response(jsonify({"success": True})) response.delete_cookie( "refresh_token", httponly=app.config["SESSION_COOKIE_HTTPONLY"], secure=app.config["SESSION_COOKIE_SECURE"], samesite=app.config["SESSION_COOKIE_SAMESITE"], ) return response @app.route("/api/auth/refresh", methods=["GET"]) def refresh_token(): """Refresh token.""" refresh_token = request.cookies.get("refresh_token") if refresh_token is None: return error_response(400, "Bad request, no refresh token") user = User.query.filter_by(refresh_token=refresh_token).first() if user is not None: access_token = user.get_token() db.session.commit() return { "token": access_token, "user_id": user.id, } return error_response(401, "Invalid refresh token")