0

Estoy creando un administrador con AdminJS, Node.js, Express.js y MongoDB, al momento de crear el resource de los usuarios, sale un error al renderizar el password:

introducir la descripción de la imagen aquí

Estoy utilizando los componentes por default de ComponentLoader, adjunto el código del archivo user.resource.ts:

import argon2 from "argon2";
import passwordsFeature from "@adminjs/passwords";
import { User } from "../models/index.js";
import AdminJS, { ActionRequest, ComponentLoader } from "adminjs";

const componentLoader = new ComponentLoader();

const UserResource = {
  resource: User,
  options: {
    properties: {
      password: { isVisible: false }, 
      newPassword: {
        type: "string",
        isVisible: { list: false, filter: false, show: false, edit: true },
      },
    },
    actions: {
      edit: {
        before: async (request: any) => {
          if (request.payload.newPassword) {
            const hashedPassword = await argon2.hash(
              request.payload.newPassword
            );
            request.payload.password = hashedPassword; 
            delete request.payload.newPassword; 
          }
          return request;
        },
      },
      new: {
        before: async (request: any) => {
          if (request.payload.password) {
            const hashedPassword = await argon2.hash(request.payload.password);
            request.payload.password = hashedPassword;
          }
          return request;
        },
      },
    },
  },
  features: [
    passwordsFeature({
      properties: {
        encryptedPassword: "password",
        password: "newPassword",
      },
      hash: argon2.hash,
      componentLoader,
    }),
  ],
};

export default UserResource;

Este es el código del archivo index.ts:

import AdminJS, { ComponentLoader } from "adminjs";
import AdminJSExpress from "@adminjs/express";
import express from "express";
import session from "express-session";
import * as AdminJSMongoose from "@adminjs/mongoose";
import connectDB from "./config/db.js";
import { Category, Post, Product, User } from "./models/index.js";
import argon2 from "argon2";
import UserResource from "./resources/user.resource.js";

const PORT = 3000;

const componentLoader = new ComponentLoader();

AdminJS.registerAdapter({
  Resource: AdminJSMongoose.Resource,
  Database: AdminJSMongoose.Database,
});

const start = async () => {
  const app = express();

  
  await connectDB();

  app.use(
    session({
      secret: "mysecret", 
      resave: false,
      saveUninitialized: true,
      cookie: { secure: process.env.NODE_ENV === "production" }, 
    })
  );

  const adminOptions = {
    resources: [UserResource, Category, Post, Product],
  };

  const admin = new AdminJS(adminOptions);

  
  const authenticate = async (email: string, password: string) => {
    const user = await User.findOne({ email });
    if (user && (await argon2.verify(user.password, password))) {
      return user; 
    }
    return null; 
  };

  const adminRouter = AdminJSExpress.buildAuthenticatedRouter(
    admin,
    {
      authenticate: async (email, password) => {
        const user = await authenticate(email, password); 
        if (user) {
          return { email: user.email, role: user.role }; 
        }
        return null;
      },
      cookieName: "adminjs",
      cookiePassword: , 
    },
    null,
    {
      resave: false,
      saveUninitialized: true,
      secret: "sessionsecret", 
      cookie: { secure: process.env.NODE_ENV === "production" }, 
    }
  );

  
  app.use(admin.options.rootPath, adminRouter);

  app.listen(PORT, () => {
    console.log(
      `AdminJS started on http://localhost:${PORT}${admin.options.rootPath}`
    );
  });
};

start();

Y este del package.json:

{
  "name": "admin-wellfit",
  "version": "1.0.0",
  "description": "admin for wellfit proyect",
  "main": "./index.ts",
  "author": "OF",
  "license": "MIT",
  "type": "module",
  "devDependencies": {
    "@types/bcrypt": "^5.0.2",
    "@types/express": "^5.0.0",
    "@types/express-session": "^1.18.0",
    "nodemon": "^3.1.7",
    "ts-node": "^10.9.2",
    "tslib": "^2.7.0",
    "typescript": "^5.6.2"
  },
  "dependencies": {
    "@adminjs/express": "^6.1.0",
    "@adminjs/mongoose": "^4.1.0",
    "@adminjs/passwords": "^4.0.0",
    "adminjs": "^7.8.13",
    "argon2": "^0.41.1",
    "bcrypt": "^5.1.1",
    "express": "^4.21.0",
    "express-formidable": "^1.2.0",
    "express-session": "^1.18.0",
    "mongoose": "^8.6.4"
  },
  "scripts": {
    "build": "tsc",
    "start": "node dist/index.js",
    "dev": "tsc && nodemon --no-warnings dist/index.js"
  }
}

No sé si estoy implementando bien los resources, ya he investigado y leído la documentación, pero no encuentro una solución que me ayude a que se rendericen los campos para ocultar y modificar la contraseña, si alguien pudiera ayudarme a identificar el error e implementar bien el resource se lo agradecería demasiado.

0

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

Examina otras preguntas con la etiqueta o formula tu propia pregunta.