Can delete API token from UI

This commit is contained in:
2025-11-18 14:51:05 +01:00
parent 02e5575892
commit b5832df746
4 changed files with 114 additions and 6 deletions

View File

@@ -1,7 +1,7 @@
use crate::controllers::HttpResult; use crate::controllers::HttpResult;
use crate::extractors::auth_extractor::{AuthExtractor, AuthenticatedMethod}; use crate::extractors::auth_extractor::{AuthExtractor, AuthenticatedMethod};
use crate::users::{APIToken, BaseAPIToken}; use crate::users::{APIToken, APITokenID, BaseAPIToken};
use actix_web::HttpResponse; use actix_web::{HttpResponse, web};
/// Create a new token /// Create a new token
pub async fn create(auth: AuthExtractor) -> HttpResult { pub async fn create(auth: AuthExtractor) -> HttpResult {
@@ -34,3 +34,15 @@ pub async fn get_list(auth: AuthExtractor) -> HttpResult {
.collect::<Vec<_>>(), .collect::<Vec<_>>(),
)) ))
} }
#[derive(serde::Deserialize)]
pub struct TokenIDInPath {
id: APITokenID,
}
/// Delete an API access token
pub async fn delete(auth: AuthExtractor, path: web::Path<TokenIDInPath>) -> HttpResult {
let token = APIToken::load(&auth.user.email, &path.id).await?;
token.delete(&auth.user.email).await?;
Ok(HttpResponse::Accepted().finish())
}

View File

@@ -115,6 +115,10 @@ async fn main() -> std::io::Result<()> {
// API Tokens controller // API Tokens controller
.route("/api/token", web::post().to(tokens_controller::create)) .route("/api/token", web::post().to(tokens_controller::create))
.route("/api/tokens", web::get().to(tokens_controller::get_list)) .route("/api/tokens", web::get().to(tokens_controller::get_list))
.route(
"/api/token/{id}",
web::delete().to(tokens_controller::delete),
)
}) })
.workers(4) .workers(4)
.bind(&AppConfig::get().listen_address)? .bind(&AppConfig::get().listen_address)?

View File

@@ -43,4 +43,16 @@ export class TokensApi {
}) })
).data; ).data;
} }
/**
* Delete a token
*/
static async Delete(t: Token): Promise<void> {
return (
await APIClient.exec({
uri: `/token/${t.id}`,
method: "DELETE",
})
).data;
}
} }

View File

@@ -2,7 +2,7 @@ import AddIcon from "@mui/icons-material/Add";
import RefreshIcon from "@mui/icons-material/Refresh"; import RefreshIcon from "@mui/icons-material/Refresh";
import { Alert, AlertTitle, IconButton, Tooltip } from "@mui/material"; import { Alert, AlertTitle, IconButton, Tooltip } from "@mui/material";
import type { GridColDef } from "@mui/x-data-grid"; import type { GridColDef } from "@mui/x-data-grid";
import { DataGrid } from "@mui/x-data-grid"; import { DataGrid, GridActionsCellItem } from "@mui/x-data-grid";
import { QRCodeCanvas } from "qrcode.react"; import { QRCodeCanvas } from "qrcode.react";
import React from "react"; import React from "react";
import { APIClient } from "../api/ApiClient"; import { APIClient } from "../api/ApiClient";
@@ -12,6 +12,11 @@ import { AsyncWidget } from "../widgets/AsyncWidget";
import { CopyTextChip } from "../widgets/CopyTextChip"; import { CopyTextChip } from "../widgets/CopyTextChip";
import { MatrixGWRouteContainer } from "../widgets/MatrixGWRouteContainer"; import { MatrixGWRouteContainer } from "../widgets/MatrixGWRouteContainer";
import { TimeWidget } from "../widgets/TimeWidget"; import { TimeWidget } from "../widgets/TimeWidget";
import DeleteIcon from "@mui/icons-material/DeleteOutlined";
import { useSnackbar } from "../hooks/contexts_provider/SnackbarProvider";
import { useConfirm } from "../hooks/contexts_provider/ConfirmDialogProvider";
import { useAlert } from "../hooks/contexts_provider/AlertDialogProvider";
import { time } from "../utils/DateUtils";
export function APITokensRoute(): React.ReactElement { export function APITokensRoute(): React.ReactElement {
const count = React.useRef(0); const count = React.useRef(0);
@@ -127,6 +132,30 @@ function TokensListGrid(p: {
list: Token[]; list: Token[];
onReload: () => void; onReload: () => void;
}): React.ReactElement { }): React.ReactElement {
const snackbar = useSnackbar();
const confirm = useConfirm();
const alert = useAlert();
// Delete a token
const handleDeleteClick = (token: Token) => async () => {
try {
if (
!(await confirm(
`Do you really want to delete the token named '${token.name}' ?`
))
)
return;
await TokensApi.Delete(token);
p.onReload();
snackbar("The token was successfully deleted!");
} catch (e) {
console.error(e);
alert(`Failed to delete API token! ${e}`);
}
};
const columns: GridColDef<(typeof p.list)[number]>[] = [ const columns: GridColDef<(typeof p.list)[number]>[] = [
{ field: "id", headerName: "ID", flex: 1 }, { field: "id", headerName: "ID", flex: 1 },
{ {
@@ -159,7 +188,18 @@ function TokensListGrid(p: {
headerName: "Last usage", headerName: "Last usage",
flex: 3, flex: 3,
renderCell(params) { renderCell(params) {
return <TimeWidget time={params.row.last_used} />; return (
<span
style={{
color:
params.row.last_used + params.row.max_inactivity < time()
? "red"
: undefined,
}}
>
<TimeWidget time={params.row.last_used} />
</span>
);
}, },
}, },
{ {
@@ -167,7 +207,18 @@ function TokensListGrid(p: {
headerName: "Max inactivity", headerName: "Max inactivity",
flex: 3, flex: 3,
renderCell(params) { renderCell(params) {
return <TimeWidget time={params.row.max_inactivity} isDuration />; return (
<span
style={{
color:
params.row.last_used + params.row.max_inactivity < time()
? "red"
: undefined,
}}
>
<TimeWidget time={params.row.max_inactivity} isDuration />
</span>
);
}, },
}, },
{ {
@@ -175,7 +226,18 @@ function TokensListGrid(p: {
headerName: "Expiration", headerName: "Expiration",
flex: 3, flex: 3,
renderCell(params) { renderCell(params) {
return <TimeWidget time={params.row.expiration} showDate />; return (
<span
style={{
color:
params.row.expiration && params.row.expiration < time()
? "red"
: undefined,
}}
>
<TimeWidget time={params.row.expiration} showDate />
</span>
);
}, },
}, },
{ {
@@ -184,6 +246,24 @@ function TokensListGrid(p: {
flex: 2, flex: 2,
type: "boolean", type: "boolean",
}, },
{
field: "actions",
type: "actions",
headerName: "Actions",
flex: 2,
cellClassName: "actions",
getActions: ({ row }) => {
return [
<GridActionsCellItem
key={row.id}
icon={<DeleteIcon />}
label="Delete"
onClick={handleDeleteClick(row)}
color="inherit"
/>,
];
},
},
]; ];
if (p.list.length === 0) if (p.list.length === 0)