From 14d191790fcb791d0ca2645166ee4c8508800aea Mon Sep 17 00:00:00 2001 From: Your Name Date: Mon, 21 Apr 2025 12:32:45 -0600 Subject: [PATCH 1/3] login de admin y endpoints de admin validados, falta validar lo de qr --- Dockerfile | 2 + package-lock.json | 247 +++++++++++++- package.json | 8 + src/administrador/administrador.controller.ts | 67 ++-- .../administrador.documentation.ts | 314 ++++++++++++++++++ src/administrador/administrador.entity.ts | 6 + src/administrador/administrador.module.ts | 6 +- src/administrador/administrador.service.ts | 138 ++++++-- src/administrador/dto/change-password.dto.ts | 13 + .../dto/create-administrador.dto.ts | 18 +- .../dto/login-administrador.dto.ts | 13 + .../dto/update.administrador.dto.ts | 18 +- src/app.module.ts | 6 +- src/auth/auth.module.ts | 22 ++ src/auth/jwt-auth.guard.ts | 5 + src/auth/jwt.strategy.ts | 39 +++ 16 files changed, 855 insertions(+), 67 deletions(-) create mode 100644 src/administrador/administrador.documentation.ts create mode 100644 src/administrador/dto/change-password.dto.ts create mode 100644 src/administrador/dto/login-administrador.dto.ts create mode 100644 src/auth/auth.module.ts create mode 100644 src/auth/jwt-auth.guard.ts create mode 100644 src/auth/jwt.strategy.ts diff --git a/Dockerfile b/Dockerfile index 9619991..2ac73f4 100644 --- a/Dockerfile +++ b/Dockerfile @@ -5,6 +5,8 @@ WORKDIR /app COPY package*.json ./ RUN npm install +# Instalar explícitamente las dependencias de autenticación +RUN npm install bcryptjs @types/bcryptjs @nestjs/jwt @nestjs/passport passport passport-jwt @types/passport-jwt COPY . . diff --git a/package-lock.json b/package-lock.json index 8fc828d..5e57e9d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,15 +12,23 @@ "@nestjs/common": "^11.0.12", "@nestjs/config": "^4.0.2", "@nestjs/core": "^11.0.1", + "@nestjs/jwt": "^11.0.0", "@nestjs/mapped-types": "*", + "@nestjs/passport": "^11.0.5", "@nestjs/platform-express": "^11.0.1", "@nestjs/swagger": "^11.1.0", "@nestjs/typeorm": "^11.0.0", + "@types/bcrypt": "^5.0.2", + "@types/bcryptjs": "^2.4.6", + "@types/passport-jwt": "^4.0.1", "axios": "^1.8.4", + "bcryptjs": "^3.0.2", "class-transformer": "^0.5.1", "class-validator": "^0.14.1", "dotenv": "^16.4.7", "mysql2": "^3.14.0", + "passport": "^0.7.0", + "passport-jwt": "^4.0.1", "qrcode": "^1.5.4", "reflect-metadata": "^0.2.2", "rxjs": "^7.8.1", @@ -2369,6 +2377,19 @@ } } }, + "node_modules/@nestjs/jwt": { + "version": "11.0.0", + "resolved": "https://registry.npmjs.org/@nestjs/jwt/-/jwt-11.0.0.tgz", + "integrity": "sha512-v7YRsW3Xi8HNTsO+jeHSEEqelX37TVWgwt+BcxtkG/OfXJEOs6GZdbdza200d6KqId1pJQZ6UPj1F0M6E+mxaA==", + "license": "MIT", + "dependencies": { + "@types/jsonwebtoken": "9.0.7", + "jsonwebtoken": "9.0.2" + }, + "peerDependencies": { + "@nestjs/common": "^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0" + } + }, "node_modules/@nestjs/mapped-types": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/@nestjs/mapped-types/-/mapped-types-2.1.0.tgz", @@ -2389,6 +2410,16 @@ } } }, + "node_modules/@nestjs/passport": { + "version": "11.0.5", + "resolved": "https://registry.npmjs.org/@nestjs/passport/-/passport-11.0.5.tgz", + "integrity": "sha512-ulQX6mbjlws92PIM15Naes4F4p2JoxGnIJuUsdXQPT+Oo2sqQmENEZXM7eYuimocfHnKlcfZOuyzbA33LwUlOQ==", + "license": "MIT", + "peerDependencies": { + "@nestjs/common": "^10.0.0 || ^11.0.0", + "passport": "^0.5.0 || ^0.6.0 || ^0.7.0" + } + }, "node_modules/@nestjs/platform-express": { "version": "11.0.12", "resolved": "https://registry.npmjs.org/@nestjs/platform-express/-/platform-express-11.0.12.tgz", @@ -3109,11 +3140,25 @@ "@babel/types": "^7.20.7" } }, + "node_modules/@types/bcrypt": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/@types/bcrypt/-/bcrypt-5.0.2.tgz", + "integrity": "sha512-6atioO8Y75fNcbmj0G7UjI9lXN2pQ/IGJ2FWT4a/btd0Lk9lQalHLKhkgKVZ3r+spnmWUKfbMi1GEe9wyHQfNQ==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/bcryptjs": { + "version": "2.4.6", + "resolved": "https://registry.npmjs.org/@types/bcryptjs/-/bcryptjs-2.4.6.tgz", + "integrity": "sha512-9xlo6R2qDs5uixm0bcIqCeMCE6HiQsIyel9KQySStiyqNl2tnj2mP3DX1Nf56MD6KMenNNlBBsy3LJ7gUEQPXQ==", + "license": "MIT" + }, "node_modules/@types/body-parser": { "version": "1.19.5", "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.5.tgz", "integrity": "sha512-fB3Zu92ucau0iQ0JMCFQE7b/dv8Ot07NI3KaZIkIUNXq82k4eBAqUaneXfleGY9JWskeS9y+u0nXMyspcuQrCg==", - "dev": true, "license": "MIT", "dependencies": { "@types/connect": "*", @@ -3124,7 +3169,6 @@ "version": "3.4.38", "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz", "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==", - "dev": true, "license": "MIT", "dependencies": { "@types/node": "*" @@ -3170,7 +3214,6 @@ "version": "5.0.1", "resolved": "https://registry.npmjs.org/@types/express/-/express-5.0.1.tgz", "integrity": "sha512-UZUw8vjpWFXuDnjFTh7/5c2TWDlQqeXHi6hcN7F2XSVT5P+WmUnnbFS3KA6Jnc6IsEqI2qCVu2bK0R0J4A8ZQQ==", - "dev": true, "license": "MIT", "dependencies": { "@types/body-parser": "*", @@ -3182,7 +3225,6 @@ "version": "5.0.6", "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-5.0.6.tgz", "integrity": "sha512-3xhRnjJPkULekpSzgtoNYYcTWgEZkp4myc+Saevii5JPnHNvHMRlBSHDbs7Bh1iPPoVTERHEZXyhyLbMEsExsA==", - "dev": true, "license": "MIT", "dependencies": { "@types/node": "*", @@ -3212,7 +3254,6 @@ "version": "2.0.4", "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.4.tgz", "integrity": "sha512-D0CFMMtydbJAegzOyHjtiKPLlvnm3iTZyZRSZoLq2mRhDdmLfIWOCYPfQJ4cu2erKghU++QvjcUjp/5h7hESpA==", - "dev": true, "license": "MIT" }, "node_modules/@types/istanbul-lib-coverage": { @@ -3260,6 +3301,15 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/jsonwebtoken": { + "version": "9.0.7", + "resolved": "https://registry.npmjs.org/@types/jsonwebtoken/-/jsonwebtoken-9.0.7.tgz", + "integrity": "sha512-ugo316mmTYBl2g81zDFnZ7cfxlut3o+/EQdaP7J8QN2kY6lJ22hmQYCK5EHcJHbrW+dkCGSCPgbG8JtYj6qSrg==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/methods": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/@types/methods/-/methods-1.1.4.tgz", @@ -3271,19 +3321,46 @@ "version": "1.3.5", "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.5.tgz", "integrity": "sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w==", - "dev": true, "license": "MIT" }, "node_modules/@types/node": { "version": "22.13.10", "resolved": "https://registry.npmjs.org/@types/node/-/node-22.13.10.tgz", "integrity": "sha512-I6LPUvlRH+O6VRUqYOcMudhaIdUVWfsjnZavnsraHvpBwaEyMN29ry+0UVJhImYL16xsscu0aske3yA+uPOWfw==", - "devOptional": true, "license": "MIT", "dependencies": { "undici-types": "~6.20.0" } }, + "node_modules/@types/passport": { + "version": "1.0.17", + "resolved": "https://registry.npmjs.org/@types/passport/-/passport-1.0.17.tgz", + "integrity": "sha512-aciLyx+wDwT2t2/kJGJR2AEeBz0nJU4WuRX04Wu9Dqc5lSUtwu0WERPHYsLhF9PtseiAMPBGNUOtFjxZ56prsg==", + "license": "MIT", + "dependencies": { + "@types/express": "*" + } + }, + "node_modules/@types/passport-jwt": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@types/passport-jwt/-/passport-jwt-4.0.1.tgz", + "integrity": "sha512-Y0Ykz6nWP4jpxgEUYq8NoVZeCQPo1ZndJLfapI249g1jHChvRfZRO/LS3tqu26YgAS/laI1qx98sYGz0IalRXQ==", + "license": "MIT", + "dependencies": { + "@types/jsonwebtoken": "*", + "@types/passport-strategy": "*" + } + }, + "node_modules/@types/passport-strategy": { + "version": "0.2.38", + "resolved": "https://registry.npmjs.org/@types/passport-strategy/-/passport-strategy-0.2.38.tgz", + "integrity": "sha512-GC6eMqqojOooq993Tmnmp7AUTbbQSgilyvpCYQjT+H6JfG/g6RGc7nXEniZlp0zyKJ0WUdOiZWLBZft9Yug1uA==", + "license": "MIT", + "dependencies": { + "@types/express": "*", + "@types/passport": "*" + } + }, "node_modules/@types/qrcode": { "version": "1.5.5", "resolved": "https://registry.npmjs.org/@types/qrcode/-/qrcode-1.5.5.tgz", @@ -3298,21 +3375,18 @@ "version": "6.9.18", "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.9.18.tgz", "integrity": "sha512-kK7dgTYDyGqS+e2Q4aK9X3D7q234CIZ1Bv0q/7Z5IwRDoADNU81xXJK/YVyLbLTZCoIwUoDoffFeF+p/eIklAA==", - "dev": true, "license": "MIT" }, "node_modules/@types/range-parser": { "version": "1.2.7", "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz", "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==", - "dev": true, "license": "MIT" }, "node_modules/@types/send": { "version": "0.17.4", "resolved": "https://registry.npmjs.org/@types/send/-/send-0.17.4.tgz", "integrity": "sha512-x2EM6TJOybec7c52BX0ZspPodMsQUd5L6PRwOunVyVUhXiBSKf3AezDL8Dgvgt5o0UfKNfuA0eMLr2wLT4AiBA==", - "dev": true, "license": "MIT", "dependencies": { "@types/mime": "^1", @@ -3323,7 +3397,6 @@ "version": "1.15.7", "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.15.7.tgz", "integrity": "sha512-W8Ym+h8nhuRwaKPaDw34QUkwsGi6Rc4yYqvKFo5rm2FUEhCFbzVWrxXUxuKK8TASjWsysJY0nsmNCGhCOIsrOw==", - "dev": true, "license": "MIT", "dependencies": { "@types/http-errors": "*", @@ -4394,6 +4467,15 @@ ], "license": "MIT" }, + "node_modules/bcryptjs": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-3.0.2.tgz", + "integrity": "sha512-k38b3XOZKv60C4E2hVsXTolJWfkGRMbILBIe2IBITXciy5bOsTKot5kDrf3ZfufQtQOUN5mXceUEpU1rTl9Uog==", + "license": "BSD-3-Clause", + "bin": { + "bcrypt": "bin/bcrypt" + } + }, "node_modules/bin-version": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/bin-version/-/bin-version-6.0.0.tgz", @@ -4619,6 +4701,12 @@ "node": "*" } }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", + "license": "BSD-3-Clause" + }, "node_modules/buffer-from": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", @@ -5463,6 +5551,15 @@ "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", "license": "MIT" }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, "node_modules/ee-first": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", @@ -8132,6 +8229,49 @@ "graceful-fs": "^4.1.6" } }, + "node_modules/jsonwebtoken": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.2.tgz", + "integrity": "sha512-PRp66vJ865SSqOlgqS8hujT5U4AOgMfhrwYIuIhfKaoSCZcirrmASQr8CX7cUg+RMih+hgznrjp99o+W4pJLHQ==", + "license": "MIT", + "dependencies": { + "jws": "^3.2.2", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^7.5.4" + }, + "engines": { + "node": ">=12", + "npm": ">=6" + } + }, + "node_modules/jwa": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.1.tgz", + "integrity": "sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==", + "license": "MIT", + "dependencies": { + "buffer-equal-constant-time": "1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz", + "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==", + "license": "MIT", + "dependencies": { + "jwa": "^1.4.1", + "safe-buffer": "^5.0.1" + } + }, "node_modules/keyv": { "version": "4.5.4", "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", @@ -8231,6 +8371,42 @@ "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", "license": "MIT" }, + "node_modules/lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==", + "license": "MIT" + }, + "node_modules/lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==", + "license": "MIT" + }, + "node_modules/lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==", + "license": "MIT" + }, + "node_modules/lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==", + "license": "MIT" + }, + "node_modules/lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==", + "license": "MIT" + }, + "node_modules/lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==", + "license": "MIT" + }, "node_modules/lodash.memoize": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz", @@ -8245,6 +8421,12 @@ "dev": true, "license": "MIT" }, + "node_modules/lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==", + "license": "MIT" + }, "node_modules/log-symbols": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz", @@ -8996,6 +9178,42 @@ "node": ">= 0.8" } }, + "node_modules/passport": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/passport/-/passport-0.7.0.tgz", + "integrity": "sha512-cPLl+qZpSc+ireUvt+IzqbED1cHHkDoVYMo30jbJIdOOjQ1MQYZBPiNvmi8UM6lJuOpTPXJGZQk0DtC4y61MYQ==", + "license": "MIT", + "dependencies": { + "passport-strategy": "1.x.x", + "pause": "0.0.1", + "utils-merge": "^1.0.1" + }, + "engines": { + "node": ">= 0.4.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/jaredhanson" + } + }, + "node_modules/passport-jwt": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/passport-jwt/-/passport-jwt-4.0.1.tgz", + "integrity": "sha512-UCKMDYhNuGOBE9/9Ycuoyh7vP6jpeTp/+sfMJl7nLff/t6dps+iaeE0hhNkKN8/HZHcJ7lCdOyDxHdDoxoSvdQ==", + "license": "MIT", + "dependencies": { + "jsonwebtoken": "^9.0.0", + "passport-strategy": "^1.0.0" + } + }, + "node_modules/passport-strategy": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/passport-strategy/-/passport-strategy-1.0.0.tgz", + "integrity": "sha512-CB97UUvDKJde2V0KDWWB3lyf6PC3FaZP7YxZ2G8OAtn9p4HI9j9JLP9qjOGZFvyl8uwNT8qM+hGnz/n16NI7oA==", + "engines": { + "node": ">= 0.4.0" + } + }, "node_modules/path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", @@ -9077,6 +9295,11 @@ "node": ">=8" } }, + "node_modules/pause": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/pause/-/pause-0.0.1.tgz", + "integrity": "sha512-KG8UEiEVkR3wGEb4m5yZkVCzigAD+cVEJck2CzYZO37ZGJfctvVptVO192MwrtPhzONn6go8ylnOdMhKqi4nfg==" + }, "node_modules/peek-readable": { "version": "5.4.2", "resolved": "https://registry.npmjs.org/peek-readable/-/peek-readable-5.4.2.tgz", @@ -9918,7 +10141,6 @@ "version": "7.7.1", "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.1.tgz", "integrity": "sha512-hlq8tAfn0m/61p4BVRcPzIGr6LKiMwo4VM6dGi6pt4qcRkmNzTcWq6eCEjEh+qXjkMDvPlOFFSGwQjoEa6gyMA==", - "dev": true, "license": "ISC", "bin": { "semver": "bin/semver.js" @@ -11478,7 +11700,6 @@ "version": "6.20.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.20.0.tgz", "integrity": "sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg==", - "devOptional": true, "license": "MIT" }, "node_modules/universalify": { diff --git a/package.json b/package.json index 29753f5..8c10e20 100644 --- a/package.json +++ b/package.json @@ -23,15 +23,23 @@ "@nestjs/common": "^11.0.12", "@nestjs/config": "^4.0.2", "@nestjs/core": "^11.0.1", + "@nestjs/jwt": "^11.0.0", "@nestjs/mapped-types": "*", + "@nestjs/passport": "^11.0.5", "@nestjs/platform-express": "^11.0.1", "@nestjs/swagger": "^11.1.0", "@nestjs/typeorm": "^11.0.0", + "@types/bcrypt": "^5.0.2", + "@types/bcryptjs": "^2.4.6", + "@types/passport-jwt": "^4.0.1", "axios": "^1.8.4", + "bcryptjs": "^3.0.2", "class-transformer": "^0.5.1", "class-validator": "^0.14.1", "dotenv": "^16.4.7", "mysql2": "^3.14.0", + "passport": "^0.7.0", + "passport-jwt": "^4.0.1", "qrcode": "^1.5.4", "reflect-metadata": "^0.2.2", "rxjs": "^7.8.1", diff --git a/src/administrador/administrador.controller.ts b/src/administrador/administrador.controller.ts index f0b8cb0..0f6e321 100644 --- a/src/administrador/administrador.controller.ts +++ b/src/administrador/administrador.controller.ts @@ -1,57 +1,72 @@ -import { Body, Controller, Delete, Get, Param, ParseIntPipe, Patch, Post } from '@nestjs/common'; +import { Body, Controller, Delete, Get, Param, ParseIntPipe, Patch, Post, UseGuards } from '@nestjs/common'; import { AdministradorService } from './administrador.service'; import { Administrador } from './administrador.entity'; import { CreateAdministradorDto } from './dto/create-administrador.dto'; import { UpdateAdministradorDto } from './dto/update.administrador.dto'; -import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiBody } from '@nestjs/swagger'; +import { LoginAdministradorDto } from './dto/login-administrador.dto'; +import { ChangePasswordDto } from './dto/change-password.dto'; +import { ApiBearerAuth } from '@nestjs/swagger'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { AdministradorApiDocumentation } from './administrador.documentation'; -@ApiTags('Administradores') // Agrupa los endpoints en Swagger @Controller('administrador') +@ApiBearerAuth() +@AdministradorApiDocumentation.ApiController export class AdministradorController { constructor(private administradorService: AdministradorService) {} @Get() - @ApiOperation({ summary: 'Obtener todos los administradores' }) - @ApiResponse({ status: 200, description: 'Lista de administradores obtenida correctamente.' }) + @UseGuards(JwtAuthGuard) + @AdministradorApiDocumentation.ApiGetAll getAdministradores(): Promise { return this.administradorService.getAdministradores(); } @Get(':id') - @ApiOperation({ summary: 'Obtener un administrador por ID' }) - @ApiParam({ name: 'id', description: 'ID del administrador', example: 1 }) - @ApiResponse({ status: 200, description: 'Administrador obtenido correctamente.' }) - @ApiResponse({ status: 404, description: 'Administrador no encontrado.' }) + @UseGuards(JwtAuthGuard) + @AdministradorApiDocumentation.ApiGetOne getAdministrador(@Param('id', ParseIntPipe) id: number) { - return this.administradorService.getAdministrador(id) + return this.administradorService.getAdministrador(id); } @Post() - @ApiOperation({ summary: 'Registrar un nuevo administrador' }) - @ApiBody({ - description: 'Datos del administrador a registrar', - schema: { - type: 'object', - properties: { - id_tipo_user: { type: 'integer', example: 1 } - } - } - }) - @ApiResponse({ status: 201, description: 'Administrador registrado exitosamente.' }) - @ApiResponse({ status: 400, description: 'Datos inválidos.' }) + @AdministradorApiDocumentation.ApiCreate createAdministrador(@Body() newAdministrador: CreateAdministradorDto) { - return this.administradorService.createAdministrador(newAdministrador) + return this.administradorService.createAdministrador(newAdministrador); + } + + @Post('login') + @AdministradorApiDocumentation.ApiLogin + login(@Body() loginData: LoginAdministradorDto) { + return this.administradorService.login(loginData.correo, loginData.password); + } + + @Patch(':id/change-password') + @UseGuards(JwtAuthGuard) + @AdministradorApiDocumentation.ApiChangePassword + changePassword( + @Param('id', ParseIntPipe) id: number, + @Body() changePasswordDto: ChangePasswordDto + ) { + return this.administradorService.changePassword( + id, + changePasswordDto.currentPassword, + changePasswordDto.newPassword + ); } @Delete(':id') + @UseGuards(JwtAuthGuard) + @AdministradorApiDocumentation.ApiRemove deleteAdministrador(@Param('id', ParseIntPipe) id: number) { - return this.administradorService.deleteAdministrador(id) + return this.administradorService.deleteAdministrador(id); } @Patch(':id') + @UseGuards(JwtAuthGuard) + @AdministradorApiDocumentation.ApiUpdate updateAdministrador(@Param('id', ParseIntPipe) id: number, @Body() administrador: UpdateAdministradorDto) { - return this.administradorService.updateAdministrador(id, administrador) + return this.administradorService.updateAdministrador(id, administrador); } - } diff --git a/src/administrador/administrador.documentation.ts b/src/administrador/administrador.documentation.ts new file mode 100644 index 0000000..063bad1 --- /dev/null +++ b/src/administrador/administrador.documentation.ts @@ -0,0 +1,314 @@ +import { ApiBody, ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger'; +import { applyDecorators } from '@nestjs/common'; + +export class AdministradorApiDocumentation { + // Decorador para toda la clase del controlador + static ApiController = ApiTags('Administradores'); + + // Documentación para crear un administrador + static ApiCreate = applyDecorators( + ApiOperation({ + summary: 'Registrar un nuevo administrador', + description: 'Crea un nuevo administrador con correo, contraseña y tipo de administrador' + }), + ApiBody({ + description: 'Datos del administrador a registrar', + schema: { + type: 'object', + required: ['correo', 'password', 'id_tipo_user'], + properties: { + correo: { + type: 'string', + format: 'email', + example: 'admin@ejemplo.com', + description: 'Correo electrónico del administrador' + }, + password: { + type: 'string', + format: 'password', + example: 'Password123', + description: 'Contraseña del administrador (mínimo 6 caracteres)' + }, + id_tipo_user: { + type: 'integer', + example: 1, + description: 'ID del tipo de usuario administrador' + } + } + } + }), + ApiResponse({ + status: 201, + description: 'Administrador registrado exitosamente', + schema: { + type: 'object', + properties: { + id_admnistrador: { type: 'number', example: 1 }, + correo: { type: 'string', example: 'admin@ejemplo.com' }, + id_tipo_user: { type: 'number', example: 1 } + } + } + }), + ApiResponse({ status: 400, description: 'Datos del administrador inválidos' }), + ApiResponse({ status: 409, description: 'El correo ya está registrado' }) + ); + + // Documentación para iniciar sesión + static ApiLogin = applyDecorators( + ApiOperation({ + summary: 'Iniciar sesión como administrador', + description: 'Autentica un administrador con correo y contraseña, y devuelve un token JWT' + }), + ApiBody({ + description: 'Credenciales de inicio de sesión', + schema: { + type: 'object', + required: ['correo', 'password'], + properties: { + correo: { + type: 'string', + format: 'email', + example: 'admin@ejemplo.com', + description: 'Correo electrónico del administrador' + }, + password: { + type: 'string', + format: 'password', + example: 'Password123', + description: 'Contraseña del administrador' + } + } + } + }), + ApiResponse({ + status: 200, + description: 'Inicio de sesión exitoso', + schema: { + type: 'object', + properties: { + access_token: { + type: 'string', + example: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...', + description: 'Token JWT para autenticación' + }, + id_administrador: { + type: 'number', + example: 1, + description: 'ID del administrador autenticado' + }, + correo: { + type: 'string', + example: 'admin@ejemplo.com', + description: 'Correo del administrador autenticado' + }, + tipo_user: { + type: 'number', + example: 1, + description: 'Tipo de usuario del administrador' + } + } + } + }), + ApiResponse({ status: 401, description: 'Credenciales inválidas' }) + ); + + // Documentación para obtener todos los administradores + static ApiGetAll = applyDecorators( + ApiOperation({ + summary: 'Obtener todos los administradores', + description: 'Retorna una lista de todos los administradores registrados (requiere autenticación)' + }), + ApiResponse({ + status: 200, + description: 'Lista de administradores obtenida correctamente', + schema: { + type: 'array', + items: { + type: 'object', + properties: { + id_admnistrador: { type: 'number', example: 1 }, + correo: { type: 'string', example: 'admin@ejemplo.com' }, + id_tipo_user: { type: 'number', example: 1 }, + tipoUser: { + type: 'array', + items: { + type: 'object', + properties: { + id_tipo_user: { type: 'number', example: 1 }, + tipo_user: { type: 'string', example: 'Administrador General' } + } + } + } + } + } + } + }), + ApiResponse({ status: 401, description: 'No autorizado' }) + ); + + // Documentación para obtener un administrador por ID + static ApiGetOne = applyDecorators( + ApiOperation({ + summary: 'Obtener un administrador por ID', + description: 'Retorna los datos de un administrador específico según su ID (requiere autenticación)' + }), + ApiParam({ + name: 'id', + description: 'ID del administrador', + type: 'number', + example: 1 + }), + ApiResponse({ + status: 200, + description: 'Administrador obtenido correctamente', + schema: { + type: 'object', + properties: { + id_admnistrador: { type: 'number', example: 1 }, + correo: { type: 'string', example: 'admin@ejemplo.com' }, + id_tipo_user: { type: 'number', example: 1 }, + tipoUser: { + type: 'array', + items: { + type: 'object', + properties: { + id_tipo_user: { type: 'number', example: 1 }, + tipo_user: { type: 'string', example: 'Administrador General' } + } + } + } + } + } + }), + ApiResponse({ status: 404, description: 'Administrador no encontrado' }), + ApiResponse({ status: 401, description: 'No autorizado' }) + ); + + // Documentación para actualizar un administrador + static ApiUpdate = applyDecorators( + ApiOperation({ + summary: 'Actualizar datos de un administrador', + description: 'Actualiza la información de un administrador existente (requiere autenticación)' + }), + ApiParam({ + name: 'id', + description: 'ID del administrador a actualizar', + type: 'number', + example: 1 + }), + ApiBody({ + description: 'Datos a actualizar del administrador', + schema: { + type: 'object', + properties: { + correo: { + type: 'string', + format: 'email', + example: 'nuevo_admin@ejemplo.com', + description: 'Nuevo correo electrónico del administrador' + }, + password: { + type: 'string', + format: 'password', + example: 'NuevaPassword123', + description: 'Nueva contraseña del administrador (mínimo 6 caracteres)' + }, + id_tipo_user: { + type: 'integer', + example: 2, + description: 'Nuevo tipo de usuario administrador' + } + } + } + }), + ApiResponse({ + status: 200, + description: 'Administrador actualizado correctamente', + schema: { + type: 'object', + properties: { + id_admnistrador: { type: 'number', example: 1 }, + correo: { type: 'string', example: 'nuevo_admin@ejemplo.com' }, + id_tipo_user: { type: 'number', example: 2 } + } + } + }), + ApiResponse({ status: 400, description: 'Datos de actualización inválidos' }), + ApiResponse({ status: 404, description: 'Administrador no encontrado' }), + ApiResponse({ status: 401, description: 'No autorizado' }) + ); + + // Documentación para cambiar contraseña + static ApiChangePassword = applyDecorators( + ApiOperation({ + summary: 'Cambiar contraseña de un administrador', + description: 'Permite a un administrador cambiar su contraseña verificando primero la contraseña actual (requiere autenticación)' + }), + ApiParam({ + name: 'id', + description: 'ID del administrador', + type: 'number', + example: 1 + }), + ApiBody({ + description: 'Datos para cambio de contraseña', + schema: { + type: 'object', + required: ['currentPassword', 'newPassword'], + properties: { + currentPassword: { + type: 'string', + format: 'password', + example: 'Password123', + description: 'Contraseña actual del administrador' + }, + newPassword: { + type: 'string', + format: 'password', + example: 'NuevaPassword123', + description: 'Nueva contraseña del administrador (mínimo 6 caracteres)' + } + } + } + }), + ApiResponse({ + status: 200, + description: 'Contraseña actualizada correctamente', + schema: { + type: 'object', + properties: { + message: { type: 'string', example: 'Contraseña actualizada correctamente' } + } + } + }), + ApiResponse({ status: 400, description: 'Contraseña actual incorrecta' }), + ApiResponse({ status: 404, description: 'Administrador no encontrado' }), + ApiResponse({ status: 401, description: 'No autorizado' }) + ); + + // Documentación para eliminar un administrador + static ApiRemove = applyDecorators( + ApiOperation({ + summary: 'Eliminar un administrador', + description: 'Elimina permanentemente un administrador por su ID (requiere autenticación)' + }), + ApiParam({ + name: 'id', + description: 'ID del administrador a eliminar', + type: 'number', + example: 1 + }), + ApiResponse({ + status: 200, + description: 'Administrador eliminado correctamente', + schema: { + type: 'object', + properties: { + affected: { type: 'number', example: 1 } + } + } + }), + ApiResponse({ status: 404, description: 'Administrador no encontrado' }), + ApiResponse({ status: 401, description: 'No autorizado' }) + ); +} \ No newline at end of file diff --git a/src/administrador/administrador.entity.ts b/src/administrador/administrador.entity.ts index 483ba96..f414872 100644 --- a/src/administrador/administrador.entity.ts +++ b/src/administrador/administrador.entity.ts @@ -6,6 +6,12 @@ export class Administrador { @PrimaryGeneratedColumn() id_admnistrador: number + @Column({ unique: true }) + correo: string + + @Column() + password: string + /* @ManyToOne(() => TipoUser, (tipoUser) => tipoUser.administradores) @JoinColumn({ name: "id_tipo_user" }) diff --git a/src/administrador/administrador.module.ts b/src/administrador/administrador.module.ts index 17ed104..e2a9b80 100644 --- a/src/administrador/administrador.module.ts +++ b/src/administrador/administrador.module.ts @@ -3,9 +3,13 @@ import { AdministradorService } from './administrador.service'; import { AdministradorController } from './administrador.controller'; import { TypeOrmModule } from '@nestjs/typeorm'; import { Administrador } from './administrador.entity'; +import { AuthModule } from '../auth/auth.module'; @Module({ - imports: [TypeOrmModule.forFeature([Administrador])], + imports: [ + TypeOrmModule.forFeature([Administrador]), + AuthModule + ], controllers: [AdministradorController], providers: [AdministradorService], exports: [AdministradorService], diff --git a/src/administrador/administrador.service.ts b/src/administrador/administrador.service.ts index 2dce554..db067f7 100644 --- a/src/administrador/administrador.service.ts +++ b/src/administrador/administrador.service.ts @@ -4,36 +4,115 @@ import { Administrador } from './administrador.entity'; import { Repository } from 'typeorm'; import { CreateAdministradorDto } from './dto/create-administrador.dto'; import { UpdateAdministradorDto } from './dto/update.administrador.dto'; +import * as bcrypt from 'bcryptjs'; +import { JwtService } from '@nestjs/jwt'; @Injectable() export class AdministradorService { constructor( - @InjectRepository(Administrador) private administradorRepository: Repository + @InjectRepository(Administrador) private administradorRepository: Repository, + private jwtService: JwtService ) {} async createAdministrador(administrador: CreateAdministradorDto) { - - //revisar el where + // Verificar si ya existe un administrador con el mismo correo const administradorFound = await this.administradorRepository.findOne({ where: { - id_admnistrador: administrador.id_tipo_user + correo: administrador.correo } - }) + }); if (administradorFound) { - return new HttpException('Administrador already exists', HttpStatus.CONFLICT) + throw new HttpException('El correo ya está registrado', HttpStatus.CONFLICT); } + // Encriptar la contraseña + const hashedPassword = await this.hashPassword(administrador.password); + + // Crear y guardar el nuevo administrador + const newAdministrador = this.administradorRepository.create({ + correo: administrador.correo, + password: hashedPassword, + id_tipo_user: administrador.id_tipo_user + }); - //Falta regresar el return - //return this.administradorRepository.save(administradorFound) + const savedAdministrador = await this.administradorRepository.save(newAdministrador); + + // Excluir la contraseña de la respuesta + const { password, ...result } = savedAdministrador; + return result; + } + + async login(correo: string, password: string) { + // Buscar administrador por correo + const administrador = await this.administradorRepository.findOne({ + where: { correo }, + relations: ['tipoUser'] + }); + + if (!administrador) { + throw new HttpException('Credenciales inválidas', HttpStatus.UNAUTHORIZED); + } + + // Verificar contraseña + const isPasswordValid = await bcrypt.compare(password, administrador.password); + if (!isPasswordValid) { + throw new HttpException('Credenciales inválidas', HttpStatus.UNAUTHORIZED); + } + + // Generar token JWT + const payload = { + sub: administrador.id_admnistrador, + correo: administrador.correo, + id_tipo_user: administrador.id_tipo_user + }; + + return { + access_token: this.jwtService.sign(payload), + id_administrador: administrador.id_admnistrador, + correo: administrador.correo, + tipo_user: administrador.id_tipo_user + }; + } + + async changePassword(id_admnistrador: number, currentPassword: string, newPassword: string) { + // Buscar administrador + const administrador = await this.administradorRepository.findOne({ + where: { id_admnistrador } + }); + + if (!administrador) { + throw new HttpException('Administrador no encontrado', HttpStatus.NOT_FOUND); + } + + // Verificar contraseña actual + const isPasswordValid = await bcrypt.compare(currentPassword, administrador.password); + if (!isPasswordValid) { + throw new HttpException('Contraseña actual incorrecta', HttpStatus.BAD_REQUEST); + } + + // Hashear y actualizar nueva contraseña + administrador.password = await this.hashPassword(newPassword); + await this.administradorRepository.save(administrador); + + return { message: 'Contraseña actualizada correctamente' }; + } + + private async hashPassword(password: string): Promise { + const salt = await bcrypt.genSalt(); + return bcrypt.hash(password, salt); } getAdministradores() { return this.administradorRepository.find({ - relations: ['tipoUser'] - }) + relations: ['tipoUser'], + select: { + id_admnistrador: true, + correo: true, + id_tipo_user: true + } + }); } async getAdministrador(id_admnistrador: number) { @@ -41,24 +120,29 @@ export class AdministradorService { where: { id_admnistrador }, - relations: ['tipoUser'] - }) + relations: ['tipoUser'], + select: { + id_admnistrador: true, + correo: true, + id_tipo_user: true + } + }); - if (!Administrador) { - return new HttpException('User not found', HttpStatus.NOT_FOUND); + if (!administradorFound) { + throw new HttpException('Administrador no encontrado', HttpStatus.NOT_FOUND); } - return administradorFound + return administradorFound; } async deleteAdministrador(id_admnistrador: number) { - const result = await this.administradorRepository.delete({ id_admnistrador }) + const result = await this.administradorRepository.delete({ id_admnistrador }); if (result.affected === 0) { - return new HttpException('User not found', HttpStatus.NOT_FOUND); + throw new HttpException('Administrador no encontrado', HttpStatus.NOT_FOUND); } - return result + return result; } async updateAdministrador(id_admnistrador: number, administrador: UpdateAdministradorDto) { @@ -66,14 +150,22 @@ export class AdministradorService { where: { id_admnistrador } - }) + }); if (!administradorFound) { - return new HttpException('User not found', HttpStatus.NOT_FOUND) + throw new HttpException('Administrador no encontrado', HttpStatus.NOT_FOUND); } - const updateAdministrador = Object.assign(administradorFound, administrador) - return this.administradorRepository.save(updateAdministrador) - } + // Si se incluye una nueva contraseña, hashearla + if (administrador.password) { + administrador.password = await this.hashPassword(administrador.password); + } + const updateAdministrador = Object.assign(administradorFound, administrador); + const savedAdministrador = await this.administradorRepository.save(updateAdministrador); + + // Excluir la contraseña de la respuesta + const { password, ...result } = savedAdministrador; + return result; + } } diff --git a/src/administrador/dto/change-password.dto.ts b/src/administrador/dto/change-password.dto.ts new file mode 100644 index 0000000..b091bbe --- /dev/null +++ b/src/administrador/dto/change-password.dto.ts @@ -0,0 +1,13 @@ +import { IsNotEmpty, MinLength } from 'class-validator'; +import { ApiProperty } from '@nestjs/swagger'; + +export class ChangePasswordDto { + @ApiProperty({ description: 'Contraseña actual del administrador' }) + @IsNotEmpty({ message: 'La contraseña actual es requerida' }) + currentPassword: string; + + @ApiProperty({ description: 'Nueva contraseña del administrador' }) + @MinLength(6, { message: 'La nueva contraseña debe tener al menos 6 caracteres' }) + @IsNotEmpty({ message: 'La nueva contraseña es requerida' }) + newPassword: string; +} \ No newline at end of file diff --git a/src/administrador/dto/create-administrador.dto.ts b/src/administrador/dto/create-administrador.dto.ts index fedb2b3..9efa3d5 100644 --- a/src/administrador/dto/create-administrador.dto.ts +++ b/src/administrador/dto/create-administrador.dto.ts @@ -1,3 +1,19 @@ +import { IsEmail, IsNotEmpty, IsNumber, MinLength } from 'class-validator'; +import { ApiProperty } from '@nestjs/swagger'; + export class CreateAdministradorDto { - id_tipo_user: number + @ApiProperty({ example: 'admin@example.com', description: 'Correo del administrador' }) + @IsEmail({}, { message: 'El correo no es válido' }) + @IsNotEmpty({ message: 'El correo es requerido' }) + correo: string; + + @ApiProperty({ example: 'Password123', description: 'Contraseña del administrador' }) + @MinLength(6, { message: 'La contraseña debe tener al menos 6 caracteres' }) + @IsNotEmpty({ message: 'La contraseña es requerida' }) + password: string; + + @ApiProperty({ example: 1, description: 'ID del tipo de usuario' }) + @IsNumber({}, { message: 'El tipo de usuario debe ser un número' }) + @IsNotEmpty({ message: 'El tipo de usuario es requerido' }) + id_tipo_user: number; } \ No newline at end of file diff --git a/src/administrador/dto/login-administrador.dto.ts b/src/administrador/dto/login-administrador.dto.ts new file mode 100644 index 0000000..79de46f --- /dev/null +++ b/src/administrador/dto/login-administrador.dto.ts @@ -0,0 +1,13 @@ +import { IsEmail, IsNotEmpty, MinLength } from 'class-validator'; +import { ApiProperty } from '@nestjs/swagger'; + +export class LoginAdministradorDto { + @ApiProperty({ example: 'admin@example.com', description: 'Correo del administrador' }) + @IsEmail({}, { message: 'El correo no es válido' }) + @IsNotEmpty({ message: 'El correo es requerido' }) + correo: string; + + @ApiProperty({ example: 'Password123', description: 'Contraseña del administrador' }) + @IsNotEmpty({ message: 'La contraseña es requerida' }) + password: string; +} \ No newline at end of file diff --git a/src/administrador/dto/update.administrador.dto.ts b/src/administrador/dto/update.administrador.dto.ts index f1355f2..9fe0eee 100644 --- a/src/administrador/dto/update.administrador.dto.ts +++ b/src/administrador/dto/update.administrador.dto.ts @@ -1,3 +1,19 @@ +import { IsEmail, IsNumber, IsOptional, MinLength } from 'class-validator'; +import { ApiProperty } from '@nestjs/swagger'; + export class UpdateAdministradorDto { - id_tipo_user?: number + @ApiProperty({ example: 'admin@example.com', description: 'Correo del administrador', required: false }) + @IsEmail({}, { message: 'El correo no es válido' }) + @IsOptional() + correo?: string; + + @ApiProperty({ example: 'Password123', description: 'Contraseña del administrador', required: false }) + @MinLength(6, { message: 'La contraseña debe tener al menos 6 caracteres' }) + @IsOptional() + password?: string; + + @ApiProperty({ example: 1, description: 'ID del tipo de usuario', required: false }) + @IsNumber({}, { message: 'El tipo de usuario debe ser un número' }) + @IsOptional() + id_tipo_user?: number; } \ No newline at end of file diff --git a/src/app.module.ts b/src/app.module.ts index 4bd13a1..053ee00 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -25,6 +25,7 @@ import { AsistenciaModule } from './asistencia/asistencia.module'; import { ParticipanteEventoModule } from './participante_evento/participante_evento.module'; import { ValidacionesModule } from './validaciones/validaciones.module'; import { AlumnosModule } from './alumnos/alumnos.module'; +import { AuthModule } from './auth/auth.module'; @Module({ @@ -42,8 +43,8 @@ import { AlumnosModule } from './alumnos/alumnos.module'; port: Number(process.env.db_port), - synchronize: false, - dropSchema: false, // elimina la base de datos + synchronize: true, + dropSchema: true, // elimina la base de datos // logging: true, // Habilita los logs para depuración autoLoadEntities: true, // Carga automáticamente las entidades @@ -66,6 +67,7 @@ import { AlumnosModule } from './alumnos/alumnos.module'; retryAttempts: 10, // Intentos para reconectar retryDelay: 3000, // Tiempo entre reintentos }), + AuthModule, CuestionarioModule, TipoCuestionarioModule, CuestionarioSeccionModule, diff --git a/src/auth/auth.module.ts b/src/auth/auth.module.ts new file mode 100644 index 0000000..dc5a2a9 --- /dev/null +++ b/src/auth/auth.module.ts @@ -0,0 +1,22 @@ +import { Module } from '@nestjs/common'; +import { JwtModule } from '@nestjs/jwt'; +import { PassportModule } from '@nestjs/passport'; +import { TypeOrmModule } from '@nestjs/typeorm'; +import { Administrador } from '../administrador/administrador.entity'; +import { JwtStrategy } from './jwt.strategy'; + +@Module({ + imports: [ + PassportModule.register({ defaultStrategy: 'jwt' }), + JwtModule.register({ + secret: process.env.JWT_SECRET || 'tu_clave_secreta', + signOptions: { + expiresIn: '24h', // Tokens expiran en 24 horas + }, + }), + TypeOrmModule.forFeature([Administrador]), + ], + providers: [JwtStrategy], + exports: [PassportModule, JwtModule], +}) +export class AuthModule {} \ No newline at end of file diff --git a/src/auth/jwt-auth.guard.ts b/src/auth/jwt-auth.guard.ts new file mode 100644 index 0000000..18588a5 --- /dev/null +++ b/src/auth/jwt-auth.guard.ts @@ -0,0 +1,5 @@ +import { Injectable } from '@nestjs/common'; +import { AuthGuard } from '@nestjs/passport'; + +@Injectable() +export class JwtAuthGuard extends AuthGuard('jwt') {} \ No newline at end of file diff --git a/src/auth/jwt.strategy.ts b/src/auth/jwt.strategy.ts new file mode 100644 index 0000000..f830986 --- /dev/null +++ b/src/auth/jwt.strategy.ts @@ -0,0 +1,39 @@ +import { Injectable, UnauthorizedException } from '@nestjs/common'; +import { PassportStrategy } from '@nestjs/passport'; +import { ExtractJwt, Strategy } from 'passport-jwt'; +import { Repository } from 'typeorm'; +import { InjectRepository } from '@nestjs/typeorm'; +import { Administrador } from '../administrador/administrador.entity'; + +@Injectable() +export class JwtStrategy extends PassportStrategy(Strategy) { + constructor( + @InjectRepository(Administrador) + private administradorRepository: Repository, + ) { + super({ + jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), + ignoreExpiration: false, + secretOrKey: process.env.JWT_SECRET || 'tu_clave_secreta', + }); + } + + async validate(payload: any) { + const { sub: id_admnistrador } = payload; + + const administrador = await this.administradorRepository.findOne({ + where: { id_admnistrador }, + select: { + id_admnistrador: true, + correo: true, + id_tipo_user: true + } + }); + + if (!administrador) { + throw new UnauthorizedException('Token inválido'); + } + + return administrador; + } +} \ No newline at end of file From 4e472e9e33c4f48bc80d25dc7a94af8e0e7a360d Mon Sep 17 00:00:00 2001 From: Your Name Date: Fri, 25 Apr 2025 09:37:58 -0600 Subject: [PATCH 2/3] csv de respuestas corregido --- .../cuestionario_respondido.service.ts | 140 ++++++++++++------ 1 file changed, 91 insertions(+), 49 deletions(-) diff --git a/src/cuestionario_respondido/cuestionario_respondido.service.ts b/src/cuestionario_respondido/cuestionario_respondido.service.ts index 6320b83..de9f5d1 100644 --- a/src/cuestionario_respondido/cuestionario_respondido.service.ts +++ b/src/cuestionario_respondido/cuestionario_respondido.service.ts @@ -400,72 +400,114 @@ recibas tu constancia.

throw new NotFoundException(`Cuestionario con ID ${idCuestionario} no encontrado`); } - // Obtener todas las respuestas para este cuestionario con sus relaciones - const respuestas = await this.dataSource.query(` + // Obtener todas las preguntas del cuestionario para los encabezados + const preguntas = await this.dataSource.query(` SELECT + p.id_pregunta, + p.pregunta, + p.id_tipo_pregunta + FROM pregunta p + JOIN seccion_pregunta sp ON p.id_pregunta = sp.id_pregunta + JOIN seccion s ON sp.id_seccion = s.id_seccion + JOIN cuestionario_seccion cs ON s.id_seccion = cs.id_seccion + WHERE cs.id_cuestionario = ? + ORDER BY sp.posicion, p.id_pregunta + `, [idCuestionario]); + + // Obtener los participantes que han respondido este cuestionario + const participantes = await this.dataSource.query(` + SELECT DISTINCT cr.id_cuestionario_respondido, cr.fecha_respuesta, p.id_participante, - p.correo AS correo_participante, - c.id_cuestionario, - c.nombre_form AS nombre_cuestionario, - e.id_evento, - e.nombre_evento, - preg.id_pregunta, - preg.pregunta, - -- Para respuestas abiertas - rpa.respuesta AS respuesta_abierta, - -- Para respuestas cerradas - o.id_opcion, - o.opcion AS respuesta_cerrada + p.correo AS correo_participante FROM cuestionario_respondido cr JOIN participante p ON cr.id_participante = p.id_participante - JOIN cuestionario c ON cr.id_cuestionario = c.id_cuestionario - LEFT JOIN evento e ON c.id_evento = e.id_evento - -- Respuestas abiertas - LEFT JOIN respuesta_participante_abierta rpa ON rpa.id_cuestionario_respondido = cr.id_cuestionario_respondido - LEFT JOIN pregunta preg_abierta ON rpa.id_pregunta = preg_abierta.id_pregunta - -- Respuestas cerradas - LEFT JOIN respuesta_participante_cerrada rpc ON rpc.id_cuestionario_respondido = cr.id_cuestionario_respondido - LEFT JOIN pregunta_opcion po ON rpc.id_pregunta_opcion = po.id_pregunta_opcion - LEFT JOIN pregunta preg ON po.id_pregunta = preg.id_pregunta - LEFT JOIN opcion o ON po.id_opcion = o.id_opcion - WHERE c.id_cuestionario = ? - ORDER BY cr.id_cuestionario_respondido, preg.id_pregunta + WHERE cr.id_cuestionario = ? + ORDER BY cr.fecha_respuesta DESC `, [idCuestionario]); + // Obtener todas las respuestas para este cuestionario + const respuestasAbiertas = await this.dataSource.query(` + SELECT + cr.id_cuestionario_respondido, + p.id_pregunta, + rpa.respuesta + FROM respuesta_participante_abierta rpa + JOIN pregunta p ON rpa.id_pregunta = p.id_pregunta + JOIN cuestionario_respondido cr ON rpa.id_cuestionario_respondido = cr.id_cuestionario_respondido + WHERE cr.id_cuestionario = ? + `, [idCuestionario]); + + const respuestasCerradas = await this.dataSource.query(` + SELECT + cr.id_cuestionario_respondido, + p.id_pregunta, + o.opcion + FROM respuesta_participante_cerrada rpc + JOIN pregunta_opcion po ON rpc.id_pregunta_opcion = po.id_pregunta_opcion + JOIN pregunta p ON po.id_pregunta = p.id_pregunta + JOIN opcion o ON po.id_opcion = o.id_opcion + JOIN cuestionario_respondido cr ON rpc.id_cuestionario_respondido = cr.id_cuestionario_respondido + WHERE cr.id_cuestionario = ? + `, [idCuestionario]); + + // Crear un mapa de respuestas por participante y pregunta + const respuestasPorParticipante = new Map(); + + // Agregar respuestas abiertas al mapa + respuestasAbiertas.forEach(respuesta => { + const key = `${respuesta.id_cuestionario_respondido}_${respuesta.id_pregunta}`; + respuestasPorParticipante.set(key, respuesta.respuesta); + }); + + // Agregar respuestas cerradas al mapa (posiblemente múltiples por pregunta) + respuestasCerradas.forEach(respuesta => { + const key = `${respuesta.id_cuestionario_respondido}_${respuesta.id_pregunta}`; + const respuestaActual = respuestasPorParticipante.get(key); + + if (respuestaActual) { + // Si ya hay una respuesta para esta pregunta, agregar esta opción + respuestasPorParticipante.set(key, `${respuestaActual}, ${respuesta.opcion}`); + } else { + respuestasPorParticipante.set(key, respuesta.opcion); + } + }); + // Preparar los datos para el CSV const datosReporte: string[][] = []; - // Agregar encabezados - const encabezados: string[] = [ - 'ID Respuesta', - 'Fecha Respuesta', + // Agregar encabezados con datos del participante seguidos por las preguntas + const encabezados = [ 'ID Participante', - 'Correo Participante', - 'Evento', - 'Cuestionario', - 'Pregunta', - 'Respuesta' + 'Correo', + 'Fecha Respuesta' ]; + // Agregar cada pregunta como un encabezado + preguntas.forEach(pregunta => { + encabezados.push(pregunta.pregunta); + }); + datosReporte.push(encabezados); - // Procesar los resultados para el CSV - for (const fila of respuestas) { - const respuesta = fila.respuesta_abierta || fila.respuesta_cerrada || ''; + // Crear una fila por cada participante + participantes.forEach(participante => { + const fila = [ + participante.id_participante.toString(), + participante.correo_participante, + new Date(participante.fecha_respuesta).toLocaleString() + ]; - datosReporte.push([ - fila.id_cuestionario_respondido?.toString() || '', - new Date(fila.fecha_respuesta).toLocaleString(), - fila.id_participante?.toString() || '', - fila.correo_participante || '', - fila.nombre_evento || 'Sin evento', - fila.nombre_cuestionario || '', - fila.pregunta || '', - respuesta - ]); - } + // Agregar cada respuesta en el orden de las preguntas + preguntas.forEach(pregunta => { + const key = `${participante.id_cuestionario_respondido}_${pregunta.id_pregunta}`; + const respuesta = respuestasPorParticipante.get(key) || ''; + fila.push(respuesta); + }); + + datosReporte.push(fila); + }); // Generar CSV de forma manual con valores separados por comas y líneas con saltos de línea // Escapar valores que contengan comas para evitar problemas con el formato CSV From 210cc139d90253c41e9a8229a7872ad2ffd940b6 Mon Sep 17 00:00:00 2001 From: Your Name Date: Fri, 25 Apr 2025 09:41:01 -0600 Subject: [PATCH 3/3] sync y drop false --- src/app.module.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/app.module.ts b/src/app.module.ts index 053ee00..42dc231 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -43,8 +43,8 @@ import { AuthModule } from './auth/auth.module'; port: Number(process.env.db_port), - synchronize: true, - dropSchema: true, // elimina la base de datos + synchronize: false, + dropSchema: false, // elimina la base de datos // logging: true, // Habilita los logs para depuración autoLoadEntities: true, // Carga automáticamente las entidades