Skip to content

Feature/api migration and personal mode #49

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 22 additions & 9 deletions src/api/allowedUsers.api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,6 @@ export const updateAllowedUsersSettings = async (settings: AllowedUsersSettings)
}
};

console.log('Sending to backend:', JSON.stringify(nestedSettings, null, 2));

const response = await fetch(`${config.baseURL}/api/settings`, {
method: 'POST',
Expand All @@ -118,10 +117,8 @@ export const updateAllowedUsersSettings = async (settings: AllowedUsersSettings)
});

const text = await response.text();
console.log('Backend response:', response.status, text);

if (!response.ok) {
console.error('Backend error:', response.status, text);
throw new Error(`HTTP error! status: ${response.status}, response: ${text}`);
}

Expand All @@ -147,9 +144,14 @@ export const getReadNpubs = async (page = 1, pageSize = 20): Promise<AllowedUser
const text = await response.text();
try {
const data = JSON.parse(text);
// Transform backend response to expected format
// Transform backend response to expected format - map tier_name to tier
const transformedNpubs = (data.npubs || []).map((npub: any) => ({
...npub,
tier: npub.tier_name || npub.tier || 'basic'
}));

return {
npubs: data.npubs || [],
npubs: transformedNpubs,
total: data.pagination?.total || 0,
page: data.pagination?.page || page,
pageSize: data.pagination?.pageSize || pageSize
Expand All @@ -161,13 +163,16 @@ export const getReadNpubs = async (page = 1, pageSize = 20): Promise<AllowedUser

export const addReadNpub = async (npub: string, tier: string): Promise<{ success: boolean, message: string }> => {
const token = readToken();
const requestBody = { npub, tier };


const response = await fetch(`${config.baseURL}/api/allowed-npubs/read`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
},
body: JSON.stringify({ npub, tier }),
body: JSON.stringify(requestBody),
});

if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
Expand Down Expand Up @@ -213,9 +218,14 @@ export const getWriteNpubs = async (page = 1, pageSize = 20): Promise<AllowedUse
const text = await response.text();
try {
const data = JSON.parse(text);
// Transform backend response to expected format
// Transform backend response to expected format - map tier_name to tier
const transformedNpubs = (data.npubs || []).map((npub: any) => ({
...npub,
tier: npub.tier_name || npub.tier || 'basic'
}));

return {
npubs: data.npubs || [],
npubs: transformedNpubs,
total: data.pagination?.total || 0,
page: data.pagination?.page || page,
pageSize: data.pagination?.pageSize || pageSize
Expand All @@ -227,13 +237,16 @@ export const getWriteNpubs = async (page = 1, pageSize = 20): Promise<AllowedUse

export const addWriteNpub = async (npub: string, tier: string): Promise<{ success: boolean, message: string }> => {
const token = readToken();
const requestBody = { npub, tier };


const response = await fetch(`${config.baseURL}/api/allowed-npubs/write`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
},
body: JSON.stringify({ npub, tier }),
body: JSON.stringify(requestBody),
});

if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { useState, useEffect } from 'react';
import { Button, Input, Table, Space, Modal, Form, Select, message, Popconfirm } from 'antd';
import { PlusOutlined, UploadOutlined, DeleteOutlined, DownloadOutlined } from '@ant-design/icons';
import { PlusOutlined, UploadOutlined, DeleteOutlined, DownloadOutlined, EditOutlined } from '@ant-design/icons';
import { useAllowedUsersNpubs, useAllowedUsersValidation } from '@app/hooks/useAllowedUsers';
import { AllowedUsersSettings, AllowedUsersMode } from '@app/types/allowedUsers.types';
import * as S from './NPubManagement.styles';
Expand Down Expand Up @@ -30,10 +30,13 @@ export const NPubManagement: React.FC<NPubManagementProps> = ({
mode
}) => {
const [isAddModalVisible, setIsAddModalVisible] = useState(false);
const [isEditModalVisible, setIsEditModalVisible] = useState(false);
const [isBulkModalVisible, setIsBulkModalVisible] = useState(false);
const [bulkText, setBulkText] = useState('');
const [unifiedUsers, setUnifiedUsers] = useState<UnifiedUser[]>([]);
const [editingUser, setEditingUser] = useState<UnifiedUser | null>(null);
const [addForm] = Form.useForm<AddNpubFormData>();
const [editForm] = Form.useForm<AddNpubFormData>();

const readNpubs = useAllowedUsersNpubs('read');
const writeNpubs = useAllowedUsersNpubs('write');
Expand All @@ -47,7 +50,7 @@ export const NPubManagement: React.FC<NPubManagementProps> = ({
readNpubs.npubs.forEach(npub => {
allNpubs.set(npub.npub, {
npub: npub.npub,
tier: npub.tier,
tier: npub.tier || settings.tiers[0]?.name || 'basic',
readAccess: true,
writeAccess: false,
added_at: npub.added_at
Expand All @@ -59,10 +62,12 @@ export const NPubManagement: React.FC<NPubManagementProps> = ({
const existing = allNpubs.get(npub.npub);
if (existing) {
existing.writeAccess = true;
// Preserve the tier from read access, or use write tier, or fallback
existing.tier = existing.tier || npub.tier || settings.tiers[0]?.name || 'basic';
} else {
allNpubs.set(npub.npub, {
npub: npub.npub,
tier: npub.tier,
tier: npub.tier || settings.tiers[0]?.name || 'basic',
readAccess: false,
writeAccess: true,
added_at: npub.added_at
Expand All @@ -71,7 +76,7 @@ export const NPubManagement: React.FC<NPubManagementProps> = ({
});

setUnifiedUsers(Array.from(allNpubs.values()));
}, [readNpubs.npubs, writeNpubs.npubs]);
}, [readNpubs.npubs, writeNpubs.npubs, settings.tiers]);
const tierOptions = settings.tiers.map(tier => {
const displayFormat = tier.unlimited
? 'unlimited'
Expand Down Expand Up @@ -108,16 +113,19 @@ export const NPubManagement: React.FC<NPubManagementProps> = ({
const user = unifiedUsers.find(u => u.npub === npub);
if (!user) return;

// Ensure we have a valid tier - fallback to first available tier if undefined
const tierToUse = user.tier || settings.tiers[0]?.name || 'basic';

try {
if (type === 'read') {
if (enabled) {
await readNpubs.addNpub(npub, user.tier);
await readNpubs.addNpub(npub, tierToUse);
} else {
await readNpubs.removeNpub(npub);
}
} else {
if (enabled) {
await writeNpubs.addNpub(npub, user.tier);
await writeNpubs.addNpub(npub, tierToUse);
} else {
await writeNpubs.removeNpub(npub);
}
Expand All @@ -127,6 +135,67 @@ export const NPubManagement: React.FC<NPubManagementProps> = ({
}
};

const handleEditUser = (user: UnifiedUser) => {
setEditingUser(user);
setIsEditModalVisible(true);
// Set form values after modal is visible
setTimeout(() => {
editForm.setFieldsValue({
npub: user.npub,
tier: user.tier,
readAccess: user.readAccess,
writeAccess: user.writeAccess
});
}, 0);
};

const handleSaveEdit = async () => {
try {
const values = await editForm.validateFields();
const originalUser = editingUser!;

// Check what actually changed
const readChanged = originalUser.readAccess !== values.readAccess;
const writeChanged = originalUser.writeAccess !== values.writeAccess;
const tierChanged = originalUser.tier !== values.tier;

// Handle read access changes
if (readChanged || (tierChanged && values.readAccess)) {
if (values.readAccess) {
// Remove old entry if exists and re-add with new tier
if (originalUser.readAccess) {
await readNpubs.removeNpub(values.npub);
}
await readNpubs.addNpub(values.npub, values.tier);
} else {
// Remove read access
await readNpubs.removeNpub(values.npub);
}
}

// Handle write access changes
if (writeChanged || (tierChanged && values.writeAccess)) {
if (values.writeAccess) {
// Remove old entry if exists and re-add with new tier
if (originalUser.writeAccess) {
await writeNpubs.removeNpub(values.npub);
}
await writeNpubs.addNpub(values.npub, values.tier);
} else {
// Remove write access
await writeNpubs.removeNpub(values.npub);
}
}

setIsEditModalVisible(false);
setEditingUser(null);
editForm.resetFields();
} catch (error) {
console.error('Edit user error:', error);
message.error('Failed to update user');
}
};

const handleRemoveUser = async (npub: string) => {
try {
// Remove from both lists
Expand Down Expand Up @@ -257,17 +326,27 @@ export const NPubManagement: React.FC<NPubManagementProps> = ({
title: 'Actions',
key: 'actions',
render: (_: any, record: UnifiedUser) => (
<Popconfirm
title="Are you sure you want to remove this user completely?"
onConfirm={() => handleRemoveUser(record.npub)}
>
<Space size="small">
<Button
type="text"
danger
icon={<DeleteOutlined />}
icon={<EditOutlined />}
size="small"
onClick={() => handleEditUser(record)}
title="Edit user"
/>
</Popconfirm>
<Popconfirm
title="Are you sure you want to remove this user completely?"
onConfirm={() => handleRemoveUser(record.npub)}
>
<Button
type="text"
danger
icon={<DeleteOutlined />}
size="small"
title="Remove user"
/>
</Popconfirm>
</Space>
)
}
];
Expand Down Expand Up @@ -346,21 +425,81 @@ export const NPubManagement: React.FC<NPubManagementProps> = ({
</Form.Item>

<Form.Item
name="readAccess"
label="Permissions"
style={{ marginBottom: 0 }}
>
<Space direction="vertical">
<Form.Item name="readAccess" valuePropName="checked" style={{ marginBottom: 8 }}>
<S.PermissionLabel>
<S.StyledSwitch size="small" /> Read Access
</S.PermissionLabel>
</Form.Item>
<Form.Item name="writeAccess" valuePropName="checked" style={{ marginBottom: 0 }}>
<S.PermissionLabel>
<S.StyledSwitch size="small" /> Write Access
</S.PermissionLabel>
</Form.Item>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', color: 'var(--text-main-color)' }}>
<Form.Item name="readAccess" valuePropName="checked" style={{ marginBottom: 0 }}>
<S.StyledSwitch size="small" />
</Form.Item>
<span>Read Access</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', color: 'var(--text-main-color)' }}>
<Form.Item name="writeAccess" valuePropName="checked" style={{ marginBottom: 0 }}>
<S.StyledSwitch size="small" />
</Form.Item>
<span>Write Access</span>
</div>
</Space>
</Form.Item>
</Form>
</Modal>

{/* Edit User Modal */}
<Modal
title="Edit User"
open={isEditModalVisible}
onOk={handleSaveEdit}
onCancel={() => {
setIsEditModalVisible(false);
setEditingUser(null);
editForm.resetFields();
}}
destroyOnClose
>
<Form
form={editForm}
layout="vertical"
initialValues={{
npub: editingUser?.npub || '',
tier: editingUser?.tier || '',
readAccess: editingUser?.readAccess || false,
writeAccess: editingUser?.writeAccess || false
}}
>
<Form.Item
name="npub"
label="NPUB"
>
<Input disabled />
</Form.Item>

<Form.Item
name="tier"
label="Tier"
rules={[{ required: true, message: 'Please select a tier' }]}
>
<Select placeholder="Select tier" options={tierOptions} />
</Form.Item>

<Form.Item
label="Permissions"
style={{ marginBottom: 0 }}
>
<Space direction="vertical">
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', color: 'var(--text-main-color)' }}>
<Form.Item name="readAccess" valuePropName="checked" style={{ marginBottom: 0 }}>
<S.StyledSwitch size="small" />
</Form.Item>
<span>Read Access</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', color: 'var(--text-main-color)' }}>
<Form.Item name="writeAccess" valuePropName="checked" style={{ marginBottom: 0 }}>
<S.StyledSwitch size="small" />
</Form.Item>
<span>Write Access</span>
</div>
</Space>
</Form.Item>
</Form>
Expand Down
Loading