aminghadersohi commented on code in PR #37973: URL: https://github.com/apache/superset/pull/37973#discussion_r2911773199
########## superset-frontend/src/features/apiKeys/ApiKeyList.tsx: ########## @@ -0,0 +1,224 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +import { useEffect, useState } from 'react'; +import { SupersetClient } from '@superset-ui/core'; +import { t } from '@apache-superset/core/translation'; +import { css, useTheme } from '@apache-superset/core/theme'; +import { + Button, + Table, + Modal, + Tag, + Tooltip, +} from '@superset-ui/core/components'; +import { useToasts } from 'src/components/MessageToasts/withToasts'; +import { ApiKeyCreateModal } from './ApiKeyCreateModal'; + +export interface ApiKey { + uuid: string; + name: string; + key_prefix: string; + active: boolean; + created_on: string; + expires_on: string | null; + revoked_on: string | null; + last_used_on: string | null; + scopes: string | null; +} + +export function ApiKeyList() { + const theme = useTheme(); + const { addDangerToast, addSuccessToast } = useToasts(); + const [apiKeys, setApiKeys] = useState<ApiKey[]>([]); + const [loading, setLoading] = useState(false); + const [showCreateModal, setShowCreateModal] = useState(false); + + async function fetchApiKeys() { + setLoading(true); + try { + const response = await SupersetClient.get({ + endpoint: '/api/v1/security/api_keys/', + }); + setApiKeys(response.json.result || []); + } catch (error) { + addDangerToast(t('Failed to fetch API keys')); + } finally { + setLoading(false); + } + } + + useEffect(() => { + fetchApiKeys(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + function handleRevokeKey(keyUuid: string) { + Modal.confirm({ + title: t('Revoke API Key'), + content: t( + 'Are you sure you want to revoke this API key? This action cannot be undone.', + ), + okText: t('Revoke'), + okType: 'danger', + cancelText: t('Cancel'), + onOk: async () => { + try { + await SupersetClient.delete({ + endpoint: `/api/v1/security/api_keys/${keyUuid}`, + }); + addSuccessToast(t('API key revoked successfully')); + fetchApiKeys(); + } catch (error) { + addDangerToast(t('Failed to revoke API key')); + } + }, + }); + } + + const formatDate = (dateString: string | null) => { + if (!dateString) return '-'; + return new Date(dateString).toLocaleDateString(undefined, { + year: 'numeric', + month: 'short', + day: 'numeric', + }); + }; + + const getStatusBadge = (key: ApiKey) => { + if (key.revoked_on) { + return <Tag color="error">{t('Revoked')}</Tag>; + } + if (key.expires_on && new Date(key.expires_on) < new Date()) { + return <Tag color="warning">{t('Expired')}</Tag>; + } + return <Tag color="success">{t('Active')}</Tag>; + }; + + const columns = [ + { + title: t('Name'), + dataIndex: 'name', + key: 'name', + }, + { + title: t('Key Prefix'), + dataIndex: 'key_prefix', + key: 'key_prefix', + render: (prefix: string) => ( + <code + css={css` + background: ${theme.colorFillSecondary}; + padding: 2px 6px; + border-radius: 3px; + `} + > + {prefix}... + </code> + ), + }, + { + title: t('Created'), + dataIndex: 'created_on', + key: 'created_on', + render: formatDate, + }, + { + title: t('Last Used'), + dataIndex: 'last_used_on', + key: 'last_used_on', + render: formatDate, + }, + { + title: t('Status'), + key: 'status', + render: (_: unknown, record: ApiKey) => getStatusBadge(record), + }, + { + title: t('Actions'), + key: 'actions', + render: (_: unknown, record: ApiKey) => ( + <> + {!record.revoked_on && ( + <Tooltip title={t('Revoke this API key')}> + <Button + type="link" + danger + onClick={() => handleRevokeKey(record.uuid)} + > + {t('Revoke')} + </Button> + </Tooltip> + )} + </> + ), + }, + ]; + + return ( + <div> + <div + css={css` + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: ${theme.sizeUnit * 4}px; + `} + > + <div> + <p + css={css` + margin-bottom: ${theme.sizeUnit * 2}px; + `} + > + {t('API keys allow scoped programmatic access to Superset.')} + </p> + <p + css={css` + margin-bottom: 0; + `} + > + {t('Keys are shown only once at creation. Store them securely.')} + </p> + </div> + <Button type="primary" onClick={() => setShowCreateModal(true)}> + {t('Create API Key')} + </Button> + </div> + <Table + columns={columns} + data={apiKeys} + loading={loading} + rowKey="uuid" + pagination={{ pageSize: 10 }} + /> + {showCreateModal && ( + <ApiKeyCreateModal + show={showCreateModal} + onHide={() => { + setShowCreateModal(false); + fetchApiKeys(); + }} + onSuccess={() => { + fetchApiKeys(); + }} + /> + )} Review Comment: Fixed — removed the duplicate `fetchApiKeys()` call from `onHide`. Now only `onSuccess` refreshes the list after key creation, avoiding the redundant network request. ########## superset/migrations/versions/2026-02-14_12-00_f1a2b3c4d5e6_add_fab_api_key_table.py: ########## @@ -0,0 +1,73 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +"""add FAB api key table + +Revision ID: f1a2b3c4d5e6 +Revises: a1b2c3d4e5f6 +Create Date: 2026-02-14 12:00:00.000000 + +""" + +import sqlalchemy as sa +from alembic import op + +# revision identifiers, used by Alembic. +revision = "f1a2b3c4d5e6" +down_revision = "a1b2c3d4e5f6" + + +def upgrade() -> None: + """Create ab_api_key table for FAB API key authentication. + + This table is managed by FAB's SecurityManager. For fresh installs, + FAB's create_all() handles table creation. This migration ensures + existing Superset installs get the table on upgrade. + """ + conn = op.get_bind() + inspector = sa.inspect(conn) + if "ab_api_key" in inspector.get_table_names(): + return + + op.create_table( + "ab_api_key", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("uuid", sa.String(length=36), nullable=False), + sa.Column("name", sa.String(length=256), nullable=False), + sa.Column("key_hash", sa.String(length=256), nullable=False), + sa.Column("key_prefix", sa.String(length=16), nullable=False), + sa.Column("user_id", sa.Integer(), nullable=False), + sa.Column("scopes", sa.Text(), nullable=True), + sa.Column( + "active", sa.Boolean(), nullable=False, server_default=sa.text("true") + ), + sa.Column("created_on", sa.DateTime(), nullable=True), + sa.Column("expires_on", sa.DateTime(), nullable=True), + sa.Column("revoked_on", sa.DateTime(), nullable=True), + sa.Column("last_used_on", sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(["user_id"], ["ab_user.id"], ondelete="CASCADE"), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint("uuid"), + ) + + with op.batch_alter_table("ab_api_key") as batch_op: + batch_op.create_index("idx_api_key_prefix", ["key_prefix"]) + batch_op.create_index("idx_api_key_user_id", ["user_id"]) + + +def downgrade() -> None: + """Drop ab_api_key table.""" + op.drop_table("ab_api_key") Review Comment: Fixed — downgrade now mirrors upgrade's guard by checking `if 'ab_api_key' not in inspector.get_table_names()` before dropping, so FAB-managed installs won't lose a table this migration didn't create. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
