Hola de nuevo. También les quiero dejar mi aporte de cómo elaboré mis validaciones para los nuevos endpoints con los routes de login, recovery y change-password. Primero, creé un nuevo archivo dentro de los schemas llamado ++auth.schema.js++ con el siguiente contenido:
const Joi = require('joi');
const email = Joi.string().email(),
password = Joi.string().min(8),
newPassword = Joi.string().min(8),
token = Joi.string().regex(
/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_.+/=]*$/
);
const loginAuthSchema = Joi.object({
email: email.required(),
password: password.required(),
});
const recoveryAuthSchema = Joi.object({
email: email.required(),
});
const changePasswordAuthSchema = Joi.object({
token: token.required(),
newPassword: newPassword.required(),
});
module.exports = {
loginAuthSchema,
recoveryAuthSchema,
changePasswordAuthSchema,
};
Finalmente, importé el middleware de validatorHandler y el schema creado anteriormente dentro de ++auth.router++:
const express = require('express'),
passport = require('passport'),
AuthService = require('./../services/auth.service'),
service = new AuthService(),
router = express.Router(),
validatorHandler = require('../middlewares/validator.handler'),
{
loginAuthSchema,
recoveryAuthSchema,
changePasswordAuthSchema,
} = require('../schemas/auth.schema');
router.post(
'/login',
validatorHandler(loginAuthSchema, 'body'),
passport.authenticate('local', { session: false }),
async (req, res, next) => {
try {
const user = req.user;
res.json(service.signToken(user));
} catch (error) {
next(error);
}
}
);
router.post(
'/recovery',
validatorHandler(recoveryAuthSchema, 'body'),
async (req, res, next) => {
try {
const { email } = req.body;
const rta = await service.sendRecovery(email);
res.json(rta);
} catch (error) {
next(error);
}
}
);
router.post(
'/change-password',
validatorHandler(changePasswordAuthSchema, 'body'),
async (req, res, next) => {
try {
const { token, newPassword } = req.body;
const rta = await service.changePassword(token, newPassword);
res.json(rta);
} catch (error) {
next(error);
}
}
);
module.exports = router;
