feat: add portal api key management

This commit is contained in:
QiuSW
2026-07-03 11:51:46 +08:00
parent d61a641b7e
commit 35f4c9c494
18 changed files with 323 additions and 29 deletions
+16
View File
@@ -0,0 +1,16 @@
from django import forms
class ApiKeyCreateForm(forms.Form):
name = forms.CharField(
label="名称",
max_length=80,
required=False,
widget=forms.TextInput(
attrs={
"autocomplete": "off",
"class": "form-control",
"placeholder": "例如:桌面端",
}
),
)
+86
View File
@@ -0,0 +1,86 @@
{% extends "portal/base.html" %}
{% block title %}API Key - cmhub{% endblock %}
{% block content %}
<div class="d-flex flex-column gap-4">
<div>
<h1 class="h3 mb-1">API Key</h1>
<div class="text-secondary">{{ user.email }}</div>
</div>
{% if new_api_key %}
<div class="alert alert-warning mb-0">
<div class="fw-semibold mb-2">新 Key 只显示一次</div>
<input class="form-control font-monospace key-value" type="text" value="{{ new_api_key.raw_key }}" readonly>
<div class="small mt-2">prefix:<code>{{ new_api_key.key_prefix }}</code></div>
</div>
{% endif %}
<section class="cmhub-surface">
<h2 class="h5 mb-3">生成 Key</h2>
<form method="post" class="row g-3 align-items-end">
{% csrf_token %}
<div class="col-md-8">
<label class="form-label" for="{{ form.name.id_for_label }}">{{ form.name.label }}</label>
{{ form.name }}
{% if form.name.errors %}
<div class="text-danger small mt-1">{{ form.name.errors|striptags }}</div>
{% endif %}
</div>
<div class="col-md-4">
<button class="btn btn-primary w-100" type="submit">生成</button>
</div>
</form>
</section>
<section class="cmhub-surface">
<h2 class="h5 mb-3">Key 列表</h2>
{% if api_keys %}
<div class="table-responsive">
<table class="table align-middle mb-0">
<thead>
<tr>
<th scope="col">prefix</th>
<th scope="col">名称</th>
<th scope="col">状态</th>
<th scope="col">最近使用</th>
<th scope="col">创建时间</th>
<th scope="col" class="text-end">操作</th>
</tr>
</thead>
<tbody>
{% for api_key in api_keys %}
<tr>
<td><code>{{ api_key.key_prefix }}</code></td>
<td>{{ api_key.name|default:"-" }}</td>
<td>
{% if api_key.status == "active" %}
<span class="badge text-bg-success">active</span>
{% else %}
<span class="badge text-bg-secondary">revoked</span>
{% endif %}
</td>
<td>{{ api_key.last_used_at|date:"Y-m-d H:i"|default:"-" }}</td>
<td>{{ api_key.created_at|date:"Y-m-d H:i" }}</td>
<td class="text-end">
{% if api_key.status == "active" %}
<form method="post" action="{% url 'portal-apikey-delete' api_key.pk %}">
{% csrf_token %}
<button class="btn btn-sm btn-outline-danger" type="submit">删除</button>
</form>
{% else %}
<span class="text-secondary small">已删除</span>
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<div class="text-secondary">暂无 API Key</div>
{% endif %}
</section>
</div>
{% endblock %}
+10
View File
@@ -65,6 +65,15 @@
background: #ffffff;
padding: 18px;
}
.cmhub-surface {
border: 1px solid var(--cmhub-line);
border-radius: 8px;
background: #ffffff;
padding: 20px;
}
.key-value {
word-break: break-all;
}
</style>
</head>
<body>
@@ -74,6 +83,7 @@
<div class="ms-auto d-flex gap-2">
{% if user.is_authenticated %}
<a class="btn btn-sm btn-outline-secondary" href="{% url 'portal-dashboard' %}">控制台</a>
<a class="btn btn-sm btn-outline-secondary" href="{% url 'portal-apikeys' %}">API Key</a>
<form method="post" action="{% url 'portal-logout' %}">
{% csrf_token %}
<button class="btn btn-sm btn-outline-secondary" type="submit">退出</button>
@@ -15,6 +15,15 @@
<div class="display-6 fw-semibold">{{ balance.points_balance }}</div>
</div>
</div>
<div class="col-md-4">
<div class="metric d-flex flex-column gap-3">
<div>
<div class="text-secondary small">接口凭证</div>
<div class="h5 mb-0">API Key</div>
</div>
<a class="btn btn-primary align-self-start" href="{% url 'portal-apikeys' %}">管理</a>
</div>
</div>
</div>
</div>
{% endblock %}
+100 -1
View File
@@ -5,9 +5,10 @@ from django.contrib.auth import get_user, get_user_model
from django.core import mail
from django.core.cache import cache
from django.test import Client, TestCase, override_settings
from rest_framework.test import APIClient
from apps.billing.models import PointsLedger
from apps.users.models import UserWallet
from apps.users.models import ApiKey, UserWallet
@override_settings(EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend")
@@ -112,3 +113,101 @@ class PortalAccountFlowTests(TestCase):
)
self.assertEqual(response.status_code, 403)
def test_apikeys_requires_session_login(self):
response = self.client.get("/apikeys")
self.assertEqual(response.status_code, 302)
self.assertTrue(response["Location"].startswith("/login?next="))
def test_create_api_key_shows_plaintext_once_and_stores_only_hash(self):
user = self.create_verified_user()
self.client.force_login(user)
response = self.client.post("/apikeys", {"name": "desktop"}, follow=True)
self.assertEqual(response.status_code, 200)
api_key = ApiKey.objects.get(user=user)
new_api_key = response.context["new_api_key"]
raw_key = new_api_key["raw_key"]
self.assertTrue(raw_key.startswith("sk_cmhub_"))
self.assertEqual(api_key.name, "desktop")
self.assertEqual(api_key.key_prefix, raw_key[: ApiKey.KEY_PREFIX_LENGTH])
self.assertNotEqual(api_key.key_hash, raw_key)
self.assertNotIn(raw_key, str(api_key.__dict__))
self.assertTrue(api_key.matches_key(raw_key))
self.assertContains(response, raw_key)
self.assertContains(response, api_key.key_prefix)
self.assertNotContains(response, api_key.key_hash)
second_response = self.client.get("/apikeys")
self.assertEqual(second_response.status_code, 200)
self.assertNotContains(second_response, raw_key)
self.assertContains(second_response, api_key.key_prefix)
self.assertNotContains(second_response, api_key.key_hash)
def test_apikey_list_only_shows_current_user_prefix(self):
user = self.create_verified_user()
other_user = self.create_verified_user()
own_key, own_raw_key = ApiKey.create_for_user(user, name="desktop")
other_key, other_raw_key = ApiKey.create_for_user(other_user, name="other")
self.client.force_login(user)
response = self.client.get("/apikeys")
self.assertEqual(response.status_code, 200)
self.assertContains(response, own_key.key_prefix)
self.assertContains(response, "desktop")
self.assertNotContains(response, own_raw_key)
self.assertNotContains(response, own_key.key_hash)
self.assertNotContains(response, other_key.key_prefix)
self.assertNotContains(response, other_raw_key)
self.assertNotContains(response, other_key.key_hash)
def test_delete_api_key_revokes_it_and_external_api_returns_403(self):
user = self.create_verified_user()
api_key, raw_key = ApiKey.create_for_user(user, name="desktop")
self.client.force_login(user)
response = self.client.post(f"/apikeys/{api_key.pk}/delete")
self.assertEqual(response.status_code, 302)
self.assertEqual(response["Location"], "/apikeys")
api_key.refresh_from_db()
self.assertEqual(api_key.status, ApiKey.Status.REVOKED)
api_client = APIClient()
api_response = api_client.get(
"/api/v1/balance",
HTTP_AUTHORIZATION=f"Bearer {raw_key}",
)
self.assertEqual(api_response.status_code, 403)
self.assertEqual(api_response.data["error"]["code"], "account_disabled")
def test_delete_api_key_does_not_allow_other_users_key(self):
user = self.create_verified_user()
other_user = self.create_verified_user()
other_key, _raw_key = ApiKey.create_for_user(other_user, name="other")
self.client.force_login(user)
response = self.client.post(f"/apikeys/{other_key.pk}/delete")
self.assertEqual(response.status_code, 404)
other_key.refresh_from_db()
self.assertEqual(other_key.status, ApiKey.Status.ACTIVE)
def test_apikey_create_and_delete_posts_are_csrf_protected(self):
user = self.create_verified_user()
api_key, _raw_key = ApiKey.create_for_user(user, name="desktop")
csrf_client = Client(enforce_csrf_checks=True)
csrf_client.force_login(user)
create_response = csrf_client.post("/apikeys", {"name": "new"})
delete_response = csrf_client.post(f"/apikeys/{api_key.pk}/delete")
self.assertEqual(create_response.status_code, 403)
self.assertEqual(delete_response.status_code, 403)
api_key.refresh_from_db()
self.assertEqual(api_key.status, ApiKey.Status.ACTIVE)
+3 -1
View File
@@ -2,7 +2,7 @@ from allauth.account.views import LoginView, LogoutView, SignupView
from django.urls import path
from django.views.generic import RedirectView
from .views import DashboardView
from .views import ApiKeyDeleteView, ApiKeyListCreateView, DashboardView
urlpatterns = [
path("", RedirectView.as_view(pattern_name="portal-dashboard", permanent=False), name="portal-home"),
@@ -10,4 +10,6 @@ urlpatterns = [
path("login", LoginView.as_view(), name="portal-login"),
path("logout", LogoutView.as_view(), name="portal-logout"),
path("dashboard", DashboardView.as_view(), name="portal-dashboard"),
path("apikeys", ApiKeyListCreateView.as_view(), name="portal-apikeys"),
path("apikeys/<int:pk>/delete", ApiKeyDeleteView.as_view(), name="portal-apikey-delete"),
]
+47 -1
View File
@@ -1,7 +1,17 @@
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView
from django.shortcuts import get_object_or_404, redirect
from django.urls import reverse_lazy
from django.views import View
from django.views.generic import FormView, TemplateView
from apps.billing.services import get_balance_snapshot
from apps.users.models import ApiKey
from .forms import ApiKeyCreateForm
NEW_API_KEY_SESSION_KEY = "portal_new_api_key"
class DashboardView(LoginRequiredMixin, TemplateView):
@@ -11,3 +21,39 @@ class DashboardView(LoginRequiredMixin, TemplateView):
context = super().get_context_data(**kwargs)
context["balance"] = get_balance_snapshot(self.request.user)
return context
class ApiKeyListCreateView(LoginRequiredMixin, FormView):
template_name = "portal/apikeys.html"
form_class = ApiKeyCreateForm
success_url = reverse_lazy("portal-apikeys")
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["api_keys"] = ApiKey.objects.filter(user=self.request.user).order_by(
"-created_at",
"-id",
)
context["new_api_key"] = self.request.session.pop(NEW_API_KEY_SESSION_KEY, None)
return context
def form_valid(self, form):
name = form.cleaned_data["name"].strip()
api_key, raw_key = ApiKey.create_for_user(self.request.user, name=name)
self.request.session[NEW_API_KEY_SESSION_KEY] = {
"name": api_key.name,
"key_prefix": api_key.key_prefix,
"raw_key": raw_key,
}
messages.success(self.request, "API Key 已生成")
return super().form_valid(form)
class ApiKeyDeleteView(LoginRequiredMixin, View):
def post(self, request, pk):
api_key = get_object_or_404(ApiKey, pk=pk, user=request.user)
if api_key.status != ApiKey.Status.REVOKED:
api_key.status = ApiKey.Status.REVOKED
api_key.save(update_fields=("status", "updated_at"))
messages.success(request, "API Key 已删除")
return redirect("portal-apikeys")