- У меня есть конечная точка POST API, которая получает данные пользователя, включая пароль.
- Я хочу зашифровать пароль с помощью AES-256-CBC и сохранить его в MongoDB.
- У меня также есть конечная точка GET API, которая извлекает пользовательские данные, и я хочу расшифровать сохраненные пароли перед отправкой ответа на client
- Кроме того, в моем приложении есть панель поиска, но я сталкиваюсь с проблемами с шифрованием и расшифровкой паролей, поскольку это мешает функции поиска. Ранее я пробовал использовать bcrypt и crypto, но эти подходы делали невозможным эффективный поиск пользователей по имени пользователя или другим критериям.
Код: Выделить всё
import { NextApiRequest, NextApiResponse } from "next";
< pre class="snippet-code-js lang-js Prettyprint-override">
Код: Выделить всё
import { NextApiRequest, NextApiResponse } from "next";
import connectMongo from "../../lib/mongoose";
import { form } from "../../models/Form";
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method === "GET") {
try {
await connectMongo();
const forms = await form.find(
{},
{ name: 1, username: 1, password: 1, notes: 1, url: 1, _id: 0 }
);
res.status(200).json({ success: true, data: forms });
} catch (error) {
console.error(error);
res.status(500).json({ success: false, error: "Failed to fetch data" });
}
} else {
res.status(405).json({ message: "Method not allowed" });
}
}Код: Выделить всё
import { NextApiRequest, NextApiResponse } from "next";
import connectMongo from "../../lib/mongoose";
import { form } from "../../models/Form";
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method === "POST") {
// Handle POST request to save data
const { name, username, password, notes, url } = req.body;
try {
await connectMongo();
const newForm = await form.create({
name,
username,
password,
notes,
url,
});
res.status(201).json({ success: true, data: newForm });
} catch (error) {
console.error(error);
res.status(500).json({ success: false, error: "Failed to save data" });
}
}
}и это главная страница, содержащая пароли:
Код: Выделить всё
"use client";
import React, { useState, useEffect } from "react";
import Image from "next/image";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Input } from "@/components/ui/input";
interface FormData {
name: string;
username: string;
password: string;
notes: string;
url: string;
}
const Passwords = ({ search }: { search: string }) => {
const [selectedItem, setSelectedItem] = useState(null);
const [forms, setForms] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(`/api/get`);
const result = await response.json();
if (result.success) {
const filteredData = search
? result.data.filter(
(item: { username: string }) => item.username === search
)
: result.data;
setForms(filteredData);
} else {
console.error("Failed to fetch data:", result.error);
}
} catch (error) {
console.error("Error fetching data:", error);
}
};
fetchData();
}, [search]);
const handleItemClick = (item: FormData) => {
setSelectedItem(item); // Set clicked item's data
};
const handleBack = () => {
setSelectedItem(null); // Reset selectedItem to null to show the list
};
return (
{selectedItem ? (
// Render selected item's details
Name
Username
Password
Notes
URL
Edit
Back
) : (
// Render the list of items
{forms.map((form, index) => (
{form.name}
{form.username}
{
handleItemClick(form);
}}>
))}
)}
);
};
export default Passwords;Код: Выделить всё
Подробнее здесь: https://stackoverflow.com/questions/793 ... ctionality