UI REST API: accounts, bearer auth, API apps, sessions, OpenAPI docs
- flask-smorest API under /api/v1 with a uniform JSON error shape; spec at /api/openapi.json, Swagger UI at /api/docs, ReDoc at /api/redoc - Register/login/logout/me with hashed, expiring bearer tokens, documented as an OpenAPI bearer security scheme - API application and client-session management endpoints - CORS restricted to the configured UI origin(s) - Flask no longer serves static files: it is API-only - Login and registration metrics Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9af8a4be8b
commit
e026e56ee3
13 files changed
+626
-1
No files matched your search
@@ -0,0 +1,50 @@
|
||||
"""JSON REST API used by the web UI, mounted at /api/v1."""
|
||||
|
||||
from flask import Flask, jsonify
|
||||
from flask_smorest import Api
|
||||
from werkzeug.exceptions import HTTPException
|
||||
|
||||
from scrobbler.schemas import ErrorSchema
|
||||
|
||||
BEARER = [{"bearerAuth": []}]
|
||||
|
||||
|
||||
class ScrobblerApi(Api):
|
||||
ERROR_SCHEMA = ErrorSchema
|
||||
|
||||
def handle_http_exception(self, error: HTTPException):
|
||||
"""Render every HTTP error as {"error": {"code", "message", "details"?}}."""
|
||||
data = getattr(error, "data", None) or {}
|
||||
body = {
|
||||
"code": data.get("code") or error.name.lower().replace(" ", "_"),
|
||||
"message": data.get("message") or error.description,
|
||||
}
|
||||
details = data.get("errors") or data.get("messages")
|
||||
if details:
|
||||
body["details"] = details
|
||||
response = jsonify({"error": body})
|
||||
response.status_code = error.code or 500
|
||||
for name, value in (data.get("headers") or {}).items():
|
||||
response.headers[name] = value
|
||||
return response
|
||||
|
||||
|
||||
api = ScrobblerApi()
|
||||
|
||||
|
||||
def init_app(app: Flask) -> None:
|
||||
api.init_app(app)
|
||||
api.spec.components.security_scheme(
|
||||
"bearerAuth",
|
||||
{
|
||||
"type": "http",
|
||||
"scheme": "bearer",
|
||||
"description": "Token from POST /api/v1/auth/login",
|
||||
},
|
||||
)
|
||||
|
||||
from scrobbler.api import apps, auth, sessions
|
||||
|
||||
api.register_blueprint(auth.blp, url_prefix="/api/v1/auth")
|
||||
api.register_blueprint(apps.blp, url_prefix="/api/v1/apps")
|
||||
api.register_blueprint(sessions.blp, url_prefix="/api/v1/sessions")
|
||||
@@ -0,0 +1,45 @@
|
||||
from flask import g
|
||||
from flask_smorest import Blueprint, abort
|
||||
|
||||
from scrobbler.api.decorators import authenticated
|
||||
from scrobbler.schemas import ApiAppCreateSchema, ApiAppSchema, ErrorSchema
|
||||
from scrobbler.services import accounts
|
||||
|
||||
blp = Blueprint(
|
||||
"ui_apps",
|
||||
__name__,
|
||||
description=(
|
||||
"API applications. Each has an API key and shared secret that a scrobbling "
|
||||
"client uses against the Last.fm-compatible `/2.0/` endpoint."
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@blp.route("", methods=["GET"])
|
||||
@authenticated(blp)
|
||||
@blp.response(200, ApiAppSchema(many=True))
|
||||
def list_apps():
|
||||
"""List your API applications"""
|
||||
return accounts.list_api_apps(g.user)
|
||||
|
||||
|
||||
@blp.route("", methods=["POST"])
|
||||
@authenticated(blp)
|
||||
@blp.arguments(ApiAppCreateSchema)
|
||||
@blp.response(201, ApiAppSchema)
|
||||
def create_app(body):
|
||||
"""Create an API application"""
|
||||
return accounts.create_api_app(g.user, body["name"])
|
||||
|
||||
|
||||
@blp.route("/<string:api_key>", methods=["DELETE"])
|
||||
@authenticated(blp)
|
||||
@blp.response(204)
|
||||
@blp.alt_response(404, schema=ErrorSchema, description="No such application")
|
||||
def delete_app(api_key):
|
||||
"""Delete an API application
|
||||
|
||||
Also revokes every session issued to it.
|
||||
"""
|
||||
if not accounts.delete_api_app(g.user, api_key):
|
||||
abort(404, code="not_found", message="No such application")
|
||||
@@ -0,0 +1,61 @@
|
||||
from flask import g
|
||||
from flask_smorest import Blueprint, abort
|
||||
|
||||
from scrobbler import metrics
|
||||
from scrobbler.api.decorators import authenticated, bearer_token
|
||||
from scrobbler.schemas import ErrorSchema, LoginSchema, RegisterSchema, TokenSchema, UserSchema
|
||||
from scrobbler.services import accounts
|
||||
|
||||
blp = Blueprint("ui_auth", __name__, description="Web UI accounts and login")
|
||||
|
||||
|
||||
@blp.route("/register", methods=["POST"])
|
||||
@blp.arguments(RegisterSchema)
|
||||
@blp.response(201, TokenSchema)
|
||||
@blp.alt_response(409, schema=ErrorSchema, description="Username taken")
|
||||
@blp.alt_response(400, schema=ErrorSchema, description="Invalid username or password")
|
||||
def register(body):
|
||||
"""Create an account
|
||||
|
||||
Registers a user and logs them in, returning a bearer token.
|
||||
"""
|
||||
try:
|
||||
user = accounts.register(body["username"], body["email"], body["password"])
|
||||
except accounts.AccountError as err:
|
||||
abort(409 if err.code == "username_taken" else 400, code=err.code, message=err.message)
|
||||
return {"token": accounts.issue_ui_token(user), "user": user}
|
||||
|
||||
|
||||
@blp.route("/login", methods=["POST"])
|
||||
@blp.arguments(LoginSchema)
|
||||
@blp.response(200, TokenSchema)
|
||||
@blp.alt_response(401, schema=ErrorSchema, description="Wrong username or password")
|
||||
def login(body):
|
||||
"""Log in
|
||||
|
||||
Exchanges a username and password for a bearer token valid for 30 days.
|
||||
"""
|
||||
user = accounts.authenticate(body["username"], body["password"])
|
||||
metrics.ui_logins_total.labels(result="success" if user else "failure").inc()
|
||||
if user is None:
|
||||
abort(401, code="invalid_credentials", message="Wrong username or password")
|
||||
return {"token": accounts.issue_ui_token(user), "user": user}
|
||||
|
||||
|
||||
@blp.route("/logout", methods=["POST"])
|
||||
@authenticated(blp)
|
||||
@blp.response(204)
|
||||
def logout():
|
||||
"""Log out
|
||||
|
||||
Revokes the bearer token used for this request.
|
||||
"""
|
||||
accounts.revoke_ui_token(bearer_token())
|
||||
|
||||
|
||||
@blp.route("/me", methods=["GET"])
|
||||
@authenticated(blp)
|
||||
@blp.response(200, UserSchema)
|
||||
def me():
|
||||
"""Current user"""
|
||||
return g.user
|
||||
@@ -0,0 +1,43 @@
|
||||
import functools
|
||||
|
||||
from flask import g, request
|
||||
from flask_smorest import Blueprint, abort
|
||||
|
||||
from scrobbler.api import BEARER
|
||||
from scrobbler.schemas import ErrorSchema
|
||||
from scrobbler.services import accounts
|
||||
|
||||
|
||||
def bearer_token() -> str | None:
|
||||
header = request.headers.get("Authorization", "")
|
||||
scheme, _, token = header.partition(" ")
|
||||
return token.strip() if scheme.lower() == "bearer" and token.strip() else None
|
||||
|
||||
|
||||
def require_ui_token(func):
|
||||
@functools.wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
token = bearer_token()
|
||||
user = accounts.resolve_ui_token(token) if token else None
|
||||
if user is None:
|
||||
abort(
|
||||
401,
|
||||
code="unauthorized",
|
||||
message="Missing, invalid or expired bearer token",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
g.user = user
|
||||
return func(*args, **kwargs)
|
||||
|
||||
return wrapper
|
||||
|
||||
|
||||
def authenticated(blp: Blueprint):
|
||||
"""Require a UI bearer token and document it (security scheme + 401) in OpenAPI."""
|
||||
|
||||
def decorator(func):
|
||||
func = require_ui_token(func)
|
||||
func = blp.alt_response(401, schema=ErrorSchema, description="Not authenticated")(func)
|
||||
return blp.doc(security=BEARER)(func)
|
||||
|
||||
return decorator
|
||||
@@ -0,0 +1,33 @@
|
||||
from flask import g
|
||||
from flask_smorest import Blueprint, abort
|
||||
|
||||
from scrobbler.api.decorators import authenticated
|
||||
from scrobbler.schemas import ErrorSchema, SessionSchema
|
||||
from scrobbler.services import accounts
|
||||
|
||||
blp = Blueprint(
|
||||
"ui_sessions",
|
||||
__name__,
|
||||
description="Last.fm session keys issued to scrobbling clients on your behalf.",
|
||||
)
|
||||
|
||||
|
||||
@blp.route("", methods=["GET"])
|
||||
@authenticated(blp)
|
||||
@blp.response(200, SessionSchema(many=True))
|
||||
def list_sessions():
|
||||
"""List client sessions"""
|
||||
return accounts.list_sessions(g.user)
|
||||
|
||||
|
||||
@blp.route("/<int:session_id>", methods=["DELETE"])
|
||||
@authenticated(blp)
|
||||
@blp.response(204)
|
||||
@blp.alt_response(404, schema=ErrorSchema, description="No such session")
|
||||
def revoke_session(session_id):
|
||||
"""Revoke a client session
|
||||
|
||||
The client's session key stops working immediately (Last.fm error 9).
|
||||
"""
|
||||
if not accounts.revoke_session(g.user, session_id):
|
||||
abort(404, code="not_found", message="No such session")
|
||||
Reference in new issue
Block a user