Compare commits
2
Commits
707ba4aaff
...
ba9e09f342
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ba9e09f342 | ||
|
|
9d9e190328 |
@@ -1,7 +1,8 @@
|
|||||||
|
import json
|
||||||
from typing import Any
|
from typing import Any
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
from ariadne import MutationType, QueryType, convert_kwargs_to_snake_case
|
from ariadne import MutationType, ObjectType, QueryType, convert_kwargs_to_snake_case
|
||||||
from graphql import GraphQLError
|
from graphql import GraphQLError
|
||||||
from sqlalchemy import select
|
from sqlalchemy import select
|
||||||
|
|
||||||
@@ -19,6 +20,8 @@ from app.models import AuditEvent, OAuthClient, User
|
|||||||
query = QueryType()
|
query = QueryType()
|
||||||
mutation = MutationType()
|
mutation = MutationType()
|
||||||
|
|
||||||
|
audit_event = ObjectType("AuditEvent")
|
||||||
|
|
||||||
|
|
||||||
# me – возвращает `info.context["user"]`;
|
# me – возвращает `info.context["user"]`;
|
||||||
@query.field("me")
|
@query.field("me")
|
||||||
@@ -128,3 +131,10 @@ def resolve_disable_user(_, info: Any, user_id: int) -> User:
|
|||||||
actor = info.context.get("user")
|
actor = info.context.get("user")
|
||||||
write_event(db, "user.disabled", actor_id=actor.id if actor else None)
|
write_event(db, "user.disabled", actor_id=actor.id if actor else None)
|
||||||
return user
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
@audit_event.field("metadata")
|
||||||
|
def resolve_metadata(obj: AuditEvent, info: Any) -> str | None:
|
||||||
|
if obj.metadata_json is None:
|
||||||
|
return None
|
||||||
|
return json.dumps(obj.metadata_json, ensure_ascii=False)
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from ariadne import ScalarType, load_schema_from_path, make_executable_schema
|
||||||
|
from ariadne import snake_case_fallback_resolvers
|
||||||
|
from ariadne.asgi import GraphQL
|
||||||
|
|
||||||
|
from app.graphql.context import get_context_value
|
||||||
|
from app.graphql.directives import IsAdminDirective, IsAuthenticatedDirective
|
||||||
|
from app.graphql.resolvers import audit_event, mutation, query
|
||||||
|
|
||||||
|
datetime_scalar = ScalarType("DateTime")
|
||||||
|
|
||||||
|
|
||||||
|
@datetime_scalar.serializer
|
||||||
|
def _serialize_datetime(value: Any) -> str:
|
||||||
|
if isinstance(value, datetime):
|
||||||
|
return value.isoformat()
|
||||||
|
return str(value)
|
||||||
|
|
||||||
|
|
||||||
|
# Загрузить SDL-схему из файла (в Ariadne есть функция load_schema_from_path)
|
||||||
|
type_defs = load_schema_from_path(str(Path(__file__).parent / "schema.graphql"))
|
||||||
|
|
||||||
|
# Собрать исполняемую схему через `make_executable_schema`, передав:
|
||||||
|
schema = make_executable_schema(
|
||||||
|
# типы;
|
||||||
|
type_defs,
|
||||||
|
# объекты `query` и `mutation` из `resolvers.py`;
|
||||||
|
query,
|
||||||
|
mutation,
|
||||||
|
audit_event,
|
||||||
|
datetime_scalar,
|
||||||
|
snake_case_fallback_resolvers,
|
||||||
|
# словарь директив `{"isAuthenticated": ..., "isAdmin": ...}`.
|
||||||
|
directives={
|
||||||
|
"isAuthenticated": IsAuthenticatedDirective,
|
||||||
|
"isAdmin": IsAdminDirective,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
# Обернуть схему в ASGI-приложение `GraphQL(schema, context_value=..., debug=True)`.
|
||||||
|
graphql_app = GraphQL(schema, context_value=get_context_value, debug=True)
|
||||||
+10
@@ -1,8 +1,18 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
|
from fastapi.staticfiles import StaticFiles
|
||||||
|
|
||||||
from app.auth.router import router as auth_router
|
from app.auth.router import router as auth_router
|
||||||
from app.config import settings
|
from app.config import settings
|
||||||
|
from app.graphql.schema import graphql_app
|
||||||
|
|
||||||
app = FastAPI(title=settings.app_name)
|
app = FastAPI(title=settings.app_name)
|
||||||
|
|
||||||
app.include_router(auth_router)
|
app.include_router(auth_router)
|
||||||
|
app.mount("/graphql", graphql_app)
|
||||||
|
app.mount(
|
||||||
|
"/admin",
|
||||||
|
StaticFiles(directory=str(Path(__file__).parent / "static"), html=True),
|
||||||
|
name="admin",
|
||||||
|
)
|
||||||
|
|||||||
@@ -0,0 +1,133 @@
|
|||||||
|
async function api(path, body) {
|
||||||
|
const res = await fetch(path, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
const json = await res.json().catch(() => ({}));
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(json.detail || res.statusText);
|
||||||
|
}
|
||||||
|
return json;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function gql(query, variables) {
|
||||||
|
const headers = { "Content-Type": "application/json" };
|
||||||
|
const token = localStorage.getItem("access_token");
|
||||||
|
if (token) {
|
||||||
|
headers.Authorization = `Bearer ${token}`;
|
||||||
|
}
|
||||||
|
const res = await fetch("/graphql", {
|
||||||
|
method: "POST",
|
||||||
|
headers,
|
||||||
|
body: JSON.stringify({ query, variables }),
|
||||||
|
});
|
||||||
|
const json = await res.json();
|
||||||
|
if (json.errors && json.errors.length) {
|
||||||
|
throw new Error(json.errors[0].message);
|
||||||
|
}
|
||||||
|
return json.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
const CLIENTS_QUERY = `
|
||||||
|
query { clients { id clientId name isConfidential redirectUris createdAt } }
|
||||||
|
`;
|
||||||
|
|
||||||
|
document.addEventListener("DOMContentLoaded", () => {
|
||||||
|
const loginForm = document.getElementById("login-form");
|
||||||
|
const panel = document.getElementById("panel");
|
||||||
|
const statusEl = document.getElementById("status");
|
||||||
|
const clientsBody = document.getElementById("clients-body");
|
||||||
|
const createBtn = document.getElementById("create-client");
|
||||||
|
const logoutBtn = document.getElementById("logout");
|
||||||
|
|
||||||
|
function setStatus(message, ok = false) {
|
||||||
|
statusEl.textContent = message || "";
|
||||||
|
statusEl.classList.toggle("ok", ok);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setLoggedIn(isLoggedIn) {
|
||||||
|
loginForm.classList.toggle("hidden", isLoggedIn);
|
||||||
|
panel.classList.toggle("hidden", !isLoggedIn);
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderClients(clients) {
|
||||||
|
clientsBody.textContent = "";
|
||||||
|
for (const client of clients) {
|
||||||
|
const row = document.createElement("tr");
|
||||||
|
const cells = [
|
||||||
|
client.id,
|
||||||
|
client.clientId,
|
||||||
|
client.name,
|
||||||
|
client.isConfidential ? "yes" : "no",
|
||||||
|
(client.redirectUris || []).join(", "),
|
||||||
|
client.createdAt,
|
||||||
|
];
|
||||||
|
for (const value of cells) {
|
||||||
|
const td = document.createElement("td");
|
||||||
|
td.textContent = value;
|
||||||
|
row.appendChild(td);
|
||||||
|
}
|
||||||
|
clientsBody.appendChild(row);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadClients() {
|
||||||
|
try {
|
||||||
|
const data = await gql(CLIENTS_QUERY);
|
||||||
|
renderClients(data.clients);
|
||||||
|
setStatus("");
|
||||||
|
} catch (err) {
|
||||||
|
renderClients([]);
|
||||||
|
setStatus(err.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleLogin(event) {
|
||||||
|
event.preventDefault();
|
||||||
|
setStatus("");
|
||||||
|
const email = document.getElementById("email").value;
|
||||||
|
const password = document.getElementById("password").value;
|
||||||
|
try {
|
||||||
|
const { access_token } = await api("/auth/login", { email, password });
|
||||||
|
localStorage.setItem("access_token", access_token);
|
||||||
|
setLoggedIn(true);
|
||||||
|
await loadClients();
|
||||||
|
} catch (err) {
|
||||||
|
setStatus(err.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleCreateClient() {
|
||||||
|
const name = prompt("Название клиента");
|
||||||
|
if (!name) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await gql(
|
||||||
|
"mutation ($name: String!) { createClient(name: $name) { id clientId name } }",
|
||||||
|
{ name }
|
||||||
|
);
|
||||||
|
setStatus("");
|
||||||
|
await loadClients();
|
||||||
|
} catch (err) {
|
||||||
|
setStatus(err.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleLogout() {
|
||||||
|
localStorage.removeItem("access_token");
|
||||||
|
setLoggedIn(false);
|
||||||
|
setStatus("");
|
||||||
|
loginForm.reset();
|
||||||
|
}
|
||||||
|
|
||||||
|
loginForm.addEventListener("submit", handleLogin);
|
||||||
|
createBtn.addEventListener("click", handleCreateClient);
|
||||||
|
logoutBtn.addEventListener("click", handleLogout);
|
||||||
|
|
||||||
|
if (localStorage.getItem("access_token")) {
|
||||||
|
setLoggedIn(true);
|
||||||
|
loadClients();
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Vault Admin</title>
|
||||||
|
<style>
|
||||||
|
:root {
|
||||||
|
--bg: #f4f6f8;
|
||||||
|
--card: #ffffff;
|
||||||
|
--border: #d7dce1;
|
||||||
|
--text: #1f2933;
|
||||||
|
--muted: #6b7280;
|
||||||
|
--accent: #2563eb;
|
||||||
|
--accent-hover: #1d4ed8;
|
||||||
|
--danger: #b91c1c;
|
||||||
|
}
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
||||||
|
background: var(--bg);
|
||||||
|
color: var(--text);
|
||||||
|
}
|
||||||
|
.wrap {
|
||||||
|
max-width: 880px;
|
||||||
|
margin: 40px auto;
|
||||||
|
padding: 0 16px;
|
||||||
|
}
|
||||||
|
.card {
|
||||||
|
background: var(--card);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
h1 { font-size: 20px; margin: 0 0 16px; }
|
||||||
|
label {
|
||||||
|
display: block;
|
||||||
|
font-size: 13px;
|
||||||
|
color: var(--muted);
|
||||||
|
margin: 12px 0 4px;
|
||||||
|
}
|
||||||
|
input[type="email"],
|
||||||
|
input[type="password"] {
|
||||||
|
width: 100%;
|
||||||
|
padding: 8px 10px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 6px;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
button {
|
||||||
|
font: inherit;
|
||||||
|
padding: 8px 14px;
|
||||||
|
border: 1px solid transparent;
|
||||||
|
border-radius: 6px;
|
||||||
|
background: var(--accent);
|
||||||
|
color: #fff;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
button:hover { background: var(--accent-hover); }
|
||||||
|
button.secondary {
|
||||||
|
background: #fff;
|
||||||
|
color: var(--text);
|
||||||
|
border-color: var(--border);
|
||||||
|
}
|
||||||
|
button.secondary:hover { background: #f0f2f4; }
|
||||||
|
.toolbar {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
.actions { display: flex; gap: 8px; }
|
||||||
|
table {
|
||||||
|
width: 100%;
|
||||||
|
border-collapse: collapse;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
th, td {
|
||||||
|
text-align: left;
|
||||||
|
padding: 8px 10px;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
th {
|
||||||
|
font-size: 12px;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.03em;
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
#status {
|
||||||
|
min-height: 20px;
|
||||||
|
margin-top: 14px;
|
||||||
|
font-size: 14px;
|
||||||
|
color: var(--danger);
|
||||||
|
white-space: pre-wrap;
|
||||||
|
}
|
||||||
|
#status.ok { color: #15803d; }
|
||||||
|
.hidden { display: none; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="wrap">
|
||||||
|
<form id="login-form" class="card">
|
||||||
|
<h1>Vault — вход</h1>
|
||||||
|
<label for="email">Email</label>
|
||||||
|
<input id="email" type="email" autocomplete="username" required>
|
||||||
|
<label for="password">Пароль</label>
|
||||||
|
<input id="password" type="password" autocomplete="current-password" required>
|
||||||
|
<div style="margin-top:16px">
|
||||||
|
<button type="submit">Войти</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div id="panel" class="card hidden">
|
||||||
|
<div class="toolbar">
|
||||||
|
<h1 style="margin:0">Клиенты</h1>
|
||||||
|
<div class="actions">
|
||||||
|
<button id="create-client" type="button">Создать клиента</button>
|
||||||
|
<button id="logout" type="button" class="secondary">Выйти</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>ID</th>
|
||||||
|
<th>Client ID</th>
|
||||||
|
<th>Название</th>
|
||||||
|
<th>Confidential</th>
|
||||||
|
<th>Redirect URIs</th>
|
||||||
|
<th>Создан</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody id="clients-body"></tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="status" role="status" aria-live="polite"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script src="app.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Reference in New Issue
Block a user