Skip to content

Allow PDF Encryption on audit export#126

Merged
jllanosg merged 48 commits intodevelopmentfrom
feature/encrypt-pdf-on-export
Oct 12, 2024
Merged

Allow PDF Encryption on audit export#126
jllanosg merged 48 commits intodevelopmentfrom
feature/encrypt-pdf-on-export

Conversation

@jllanosg
Copy link
Copy Markdown
Collaborator

@jllanosg jllanosg commented Oct 5, 2024

Descripción

Agrega la funcionalidad de encriptación de reportes (pdf con contraseña).

Motivación y Contexto

HU19 - Encriptación de reportes

¿Cómo ha sido probado?

  • Al momento de exportar, seleccionar la opción pdf (encrypted)
  • Creando diferentes contraseñas con niveles de seguridad diferentes
  • Creando contraseñas aleatorias, con el nivel máximo de seguridad
  • Exportando el pdf asegurado con contraseña, manteniendo la integridad de su contenido y logrando "abrirlo" con la contraseña; sea esta generada aleatoriamente o escrita manualmente.

Capturas de pantalla (si es apropiado):

Tipos de cambios

  • Bugfix (cambio que no interrumpe el funcionamiento y que soluciona un problema)
  • New feature (cambio que no interrumpe el funcionamiento y que añade funcionalidad)
  • Breaking change (corrección o funcionalidad que podría causar que la funcionalidad existente cambie)

Lista de verificación:

  • Mi código sigue el estilo de código de este proyecto.
  • Mi cambio requiere una modificación en la documentación.
  • He actualizado la documentación en consecuencia.
  • Requiere nuevos tests.

Summary by CodeRabbit

  • Nuevas Funciones

    • Se ha añadido un componente PasswordStrengthCard para evaluar y mostrar la fortaleza de las contraseñas.
    • Se ha introducido un componente PasswordInput que permite alternar la visibilidad de la contraseña.
    • Se ha implementado un modal EncryptionModal para gestionar la encriptación de PDFs.
    • Se ha añadido la funcionalidad de generar PDFs encriptados a través de un nuevo endpoint en la API.
  • Mejoras en la Interfaz de Usuario

    • Nuevas entradas de localización para mejorar la experiencia del usuario en la gestión de contraseñas y encriptación.
  • Actualizaciones de Dependencias

    • Se han añadido nuevas dependencias para soportar la encriptación y la evaluación de contraseñas.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Oct 5, 2024

📝 Walkthrough
<details>
<summary>📝 Walkthrough</summary>

## Walkthrough
Se han realizado cambios en varios archivos del backend y frontend para añadir nuevas funcionalidades relacionadas con la generación de informes en PDF y la gestión de contraseñas. Se ha introducido una nueva dependencia en el archivo `package.json` del backend y frontend. Se ha añadido una función para generar PDFs encriptados en el backend y se han creado nuevos componentes en el frontend para gestionar la entrada de contraseñas y evaluar su fortaleza. Además, se han actualizado los archivos de localización para incluir nuevas cadenas relacionadas con estas funcionalidades.

## Changes

| Archivo                                      | Resumen de cambios                                                                                          |
|----------------------------------------------|-------------------------------------------------------------------------------------------------------------|
| backend/package.json                         | Se añadió la dependencia `"muhammara": "^5.0.1"` y `"uuid": "^10.0.0"`.                                   |
| backend/src/lib/report-generator.js         | Se añadió la función `generateEncryptedPdf(audit, password)` para generar PDFs encriptados.               |
| frontend/package.json                        | Se añadieron las dependencias `"@radix-ui/react-hover-card": "^1.1.2"` y `"check-password-strength": "^2.0.10"`. |
| frontend/src/components/card/PasswordStrengthCard.tsx | Se creó el componente `PasswordStrengthCard` para evaluar y mostrar la fortaleza de la contraseña.         |
| frontend/src/components/input/PasswordInput.tsx | Se creó el componente `PasswordInput` para gestionar la entrada de contraseñas con visibilidad opcional.   |
| frontend/src/components/ui/hover-card.tsx  | Se introdujeron los componentes `HoverCard`, `HoverCardTrigger` y `HoverCardContent` para la interfaz de usuario. |
| frontend/src/i18n/en-US/index.ts            | Se añadieron nuevas cadenas de texto relacionadas con la gestión de contraseñas y la encriptación.         |
| frontend/src/routes/audits/edit/AuditRoot.tsx | Se modificó el componente `AuditRoot` para incluir un modal de encriptación y gestionar la generación de PDFs encriptados. |
| frontend/src/routes/audits/edit/general/EncryptionModal.tsx | Se creó el componente `EncryptionModal` para manejar la encriptación de contraseñas en un modal.          |

## Possibly related PRs
- **#103**: Los cambios en este PR implican actualizaciones en el archivo `frontend/src/i18n/en-US/index.ts`, que es relevante porque el PR principal también modifica este archivo para añadir nuevas cadenas relacionadas con la gestión de contraseñas y funcionalidades de encriptación.

## Suggested reviewers
- Icksir
- caverav

</details>

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@jllanosg jllanosg self-assigned this Oct 5, 2024
@jllanosg jllanosg added the enhancement New feature or request label Oct 5, 2024
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 22

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 88306fe and e6bfca5.

⛔ Files ignored due to path filters (1)
  • backend/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (10)
  • backend/package.json (1 hunks)
  • backend/src/lib/report-generator.js (2 hunks)
  • backend/src/routes/audit.js (1 hunks)
  • frontend/package.json (1 hunks)
  • frontend/src/components/card/PasswordStrengthCard.tsx (1 hunks)
  • frontend/src/components/input/PasswordInput.tsx (1 hunks)
  • frontend/src/i18n/en-US/index.ts (4 hunks)
  • frontend/src/routes/audits/edit/AuditRoot.tsx (6 hunks)
  • frontend/src/routes/audits/edit/general/EncryptionModal.tsx (1 hunks)
  • package.json (1 hunks)
🧰 Additional context used
🪛 Biome
backend/src/lib/report-generator.js

[error] 18-18: A Node.js builtin module should be imported with the node: protocol.

Using the node: protocol is more explicit and signals that the imported module belongs to Node.js.
Unsafe fix: Add the node: protocol.

(lint/style/useNodejsImportProtocol)

frontend/src/components/input/PasswordInput.tsx

[error] 37-37: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)

🔇 Additional comments (4)
package.json (1)

16-16: La adición de la dependencia es apropiada para la nueva funcionalidad.

La inclusión de "check-password-strength" es coherente con los objetivos del PR de añadir encriptación de PDF. Esta dependencia ayudará a garantizar que las contraseñas utilizadas para la encriptación sean suficientemente fuertes.

Ejecutemos un script para verificar si hay advertencias de seguridad relacionadas con esta nueva dependencia:

frontend/src/components/input/PasswordInput.tsx (2)

1-16: ¡Bien hecho con las importaciones y la definición de tipos!

Las importaciones son apropiadas y la definición del tipo PasswordInputProps está bien estructurada. No hay problemas evidentes en esta sección.


18-29: La declaración del componente y la desestructuración de props están correctas.

Has seguido las mejores prácticas de React en la declaración del componente y la desestructuración de props. Los valores por defecto para disabled, requiredAlert y requiredField son apropiados.

frontend/src/i18n/en-US/index.ts (1)

680-681: ¡Bien hecho con la adición de la entrada de encriptación!

La nueva entrada para 'encryption' es clara y directa. Se alinea perfectamente con los objetivos del PR para la encriptación de PDF.

Comment thread backend/package.json
Comment thread frontend/src/components/input/PasswordInput.tsx
Comment thread frontend/src/components/input/PasswordInput.tsx
Comment thread frontend/src/components/input/PasswordInput.tsx
Comment thread frontend/package.json
Comment thread backend/src/lib/report-generator.js
Comment thread backend/src/lib/report-generator.js
Comment thread backend/src/lib/report-generator.js
Comment thread backend/src/lib/report-generator.js
Comment thread backend/src/lib/report-generator.js Outdated
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Comment thread backend/src/routes/audit.js Outdated
jllanosg and others added 2 commits October 5, 2024 19:59
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 64d73cd and 5f41308.

📒 Files selected for processing (4)
  • backend/src/routes/audit.js (1 hunks)
  • frontend/src/components/card/PasswordStrengthCard.tsx (1 hunks)
  • frontend/src/routes/audits/edit/AuditRoot.tsx (6 hunks)
  • frontend/src/routes/audits/edit/general/EncryptionModal.tsx (1 hunks)
🧰 Additional context used
🔇 Additional comments (2)
frontend/src/components/card/PasswordStrengthCard.tsx (1)

1-136: El componente 'PasswordStrengthCard' se implementó correctamente

El código es claro, bien estructurado y sigue buenas prácticas.

frontend/src/routes/audits/edit/AuditRoot.tsx (1)

208-214: Verifica la correcta implementación de 'EncryptionModal'

Es importante que el componente EncryptionModal utilice correctamente los props que le pasas, especialmente isGeneratingPDF, para proporcionar feedback al usuario durante el proceso de generación del PDF.

Revisa la implementación del modal para asegurarte de que los estados y eventos funcionan según lo esperado.

Comment thread frontend/src/components/card/PasswordStrengthCard.tsx
Comment thread frontend/src/routes/audits/edit/AuditRoot.tsx Outdated
Comment thread frontend/src/routes/audits/edit/AuditRoot.tsx Outdated
Comment thread frontend/src/routes/audits/edit/general/EncryptionModal.tsx
Comment thread frontend/src/routes/audits/edit/general/EncryptionModal.tsx
Comment thread backend/src/routes/audit.js
Comment thread backend/src/routes/audit.js
Comment thread backend/src/routes/audit.js
caverav
caverav previously approved these changes Oct 11, 2024
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 5f41308 and 0f1c107.

📒 Files selected for processing (2)
  • backend/src/lib/report-generator.js (2 hunks)
  • frontend/src/routes/audits/edit/AuditRoot.tsx (6 hunks)
🧰 Additional context used
🪛 Biome
backend/src/lib/report-generator.js

[error] 18-18: A Node.js builtin module should be imported with the node: protocol.

Using the node: protocol is more explicit and signals that the imported module belongs to Node.js.
Unsafe fix: Add the node: protocol.

(lint/style/useNodejsImportProtocol)


[error] 19-19: A Node.js builtin module should be imported with the node: protocol.

Using the node: protocol is more explicit and signals that the imported module belongs to Node.js.
Unsafe fix: Add the node: protocol.

(lint/style/useNodejsImportProtocol)

🔇 Additional comments (6)
frontend/src/routes/audits/edit/AuditRoot.tsx (5)

11-12: Importaciones realizadas correctamente

Las importaciones de EncryptionModal y toast se han añadido correctamente, lo que permite utilizar estos componentes en el archivo.


89-90: Inicialización correcta del estado para el manejo del modal y generación de PDF

Las variables de estado isOpenModal y isGeneratingPDF están correctamente inicializadas para controlar la visualización del modal de encriptación y el estado de generación del PDF.


92-132: Implementación adecuada de handleSubmitEncrypt

La función handleSubmitEncrypt está bien implementada, manejando la solicitud asíncrona para generar el PDF encriptado, gestionando errores y asegurando el restablecimiento del estado mediante el bloque finally.


176-180: Añadida la opción de exportación de PDF encriptado correctamente

La nueva entrada en fileTypes para pdf/encrypted se ha añadido correctamente, activando la apertura del modal de encriptación al seleccionarla.


206-212: Integración correcta del componente EncryptionModal

El componente EncryptionModal se ha integrado adecuadamente, pasando todas las propiedades necesarias y asegurando su correcto funcionamiento dentro del flujo de la aplicación.

backend/src/lib/report-generator.js (1)

18-19: Actualiza las importaciones de módulos nativos con el prefijo 'node:'

Es recomendable importar los módulos nativos de Node.js utilizando el prefijo 'node:' para mayor claridad y adherencia a las prácticas recomendadas.

🧰 Tools
🪛 Biome

[error] 18-18: A Node.js builtin module should be imported with the node: protocol.

Using the node: protocol is more explicit and signals that the imported module belongs to Node.js.
Unsafe fix: Add the node: protocol.

(lint/style/useNodejsImportProtocol)


[error] 19-19: A Node.js builtin module should be imported with the node: protocol.

Using the node: protocol is more explicit and signals that the imported module belongs to Node.js.
Unsafe fix: Add the node: protocol.

(lint/style/useNodejsImportProtocol)

Comment thread backend/src/lib/report-generator.js
Comment thread backend/src/lib/report-generator.js
Comment thread backend/src/lib/report-generator.js
massi-ponce
massi-ponce previously approved these changes Oct 11, 2024
Copy link
Copy Markdown
Collaborator

@massi-ponce massi-ponce left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@jllanosg jllanosg dismissed stale reviews from massi-ponce and caverav via 9d2c673 October 11, 2024 17:40
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Outside diff range comments (1)
backend/src/lib/report-generator.js (1)

Line range hint 112-117: Corrige el manejo de errores en 'generatePdf'

En la función generatePdf, si ocurre un error durante la conversión con libre.convert, actualmente se registra el error con console.log(err); pero se sigue resolviendo la promesa con resolve(pdf);, lo que podría resultar en que pdf sea undefined o incorrecto. Es importante rechazar la promesa con reject(err); cuando hay un error para manejar adecuadamente las fallas.

Aplica este cambio para corregir el manejo de errores:

 async function generatePdf(audit) {
   var docxReport = await generateDoc(audit);
   return new Promise((resolve, reject) =>
     libre.convert(docxReport, '.pdf', undefined, (err, pdf) => {
       if (err) {
         console.log(err);
-        resolve(pdf);
+        return reject(err);
       }
       resolve(pdf);
     }),
   );
 }

Con este cambio, la promesa se rechaza correctamente en caso de error, evitando posibles comportamientos inesperados.

🧰 Tools
🪛 Biome

[error] 18-18: A Node.js builtin module should be imported with the node: protocol.

Using the node: protocol is more explicit and signals that the imported module belongs to Node.js.
Unsafe fix: Add the node: protocol.

(lint/style/useNodejsImportProtocol)


[error] 19-19: A Node.js builtin module should be imported with the node: protocol.

Using the node: protocol is more explicit and signals that the imported module belongs to Node.js.
Unsafe fix: Add the node: protocol.

(lint/style/useNodejsImportProtocol)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 0f1c107 and 9d2c673.

⛔ Files ignored due to path filters (1)
  • backend/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (2)
  • backend/package.json (1 hunks)
  • backend/src/lib/report-generator.js (2 hunks)
🧰 Additional context used
🪛 Biome
backend/src/lib/report-generator.js

[error] 18-18: A Node.js builtin module should be imported with the node: protocol.

Using the node: protocol is more explicit and signals that the imported module belongs to Node.js.
Unsafe fix: Add the node: protocol.

(lint/style/useNodejsImportProtocol)


[error] 19-19: A Node.js builtin module should be imported with the node: protocol.

Using the node: protocol is more explicit and signals that the imported module belongs to Node.js.
Unsafe fix: Add the node: protocol.

(lint/style/useNodejsImportProtocol)

🔇 Additional comments (3)
backend/package.json (3)

41-41: Adición apropiada de la dependencia muhammara.

La inclusión de la biblioteca muhammara en la versión 5.0.1 es coherente con los objetivos del PR para permitir la encriptación de PDF en la exportación de auditorías. Esta es una adición necesaria y bien especificada.


47-47: Aclaración necesaria sobre el propósito de uuid.

Se ha añadido la dependencia uuid en la versión 10.0.0. Aunque es una biblioteca común para generar identificadores únicos, no está claro cómo se relaciona específicamente con la funcionalidad de encriptación de PDF.

Por favor, proporcione más información sobre el uso previsto de uuid en el contexto de este PR. ¿Se utilizará para nombrar archivos PDF encriptados o para algún otro propósito relacionado con la nueva funcionalidad?


41-47: ⚠️ Potential issue

Especificación de la versión de Node.js sigue siendo necesaria.

Aún no se ha abordado el problema de la falta de especificación de la versión de Node.js en el proyecto. Esto es crucial para garantizar la compatibilidad con las nuevas dependencias, especialmente muhammara.

Debe añadir la especificación de la versión de Node.js en el archivo package.json bajo la sección engines o proporcionar un archivo .nvmrc con la versión adecuada. No hacer esto podría llevar a problemas de compatibilidad en el futuro.

Para verificar la compatibilidad, ejecute el siguiente script:

Asegúrese de abordar cualquier advertencia que pueda surgir de este script.

Comment thread backend/src/lib/report-generator.js
Comment thread backend/src/lib/report-generator.js
Copy link
Copy Markdown
Collaborator

@massi-ponce massi-ponce left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

Copy link
Copy Markdown
Collaborator

@iTzGooDLife iTzGooDLife left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants