问题描述
我在用户服务中创建了一个后钩子,该钩子应该清理“ find”方法的响应,从而破坏了身份验证服务。
后钩 sanitizeResponse 应该验证查询是否与电子邮件或cpf有关,如果是,则应删除一些字段并添加一些新字段。
这是 users.hooks.js
const { authenticate } = require('@feathersjs/authentication').hooks;
const {
// eslint-disable-next-line no-unused-vars
hashPassword,protect
} = require('@feathersjs/authentication-local').hooks;
const sanitizeResponse = (context) => {
const query = context.params.query;
if(!query.email && !query.cpf)
return context;
if(context.result.total){
context.result.data[0] = {exists: 1,id: context.result.data[0].id};
}else{
context.result.data[0] = {exists: 0};
}
};
module.exports = {
before: {
all: [],find: [authenticate('jwt')],get: [ authenticate('jwt') ],create: [ hashPassword('password') ],update: [ hashPassword('password'),authenticate('jwt') ],patch: [ hashPassword('password'),remove: [ authenticate('jwt') ]
},after: {
all: [
// Make sure the password field is never sent to the client
// Always must be the last hook
protect('password')
],find: [sanitizeResponse],get: [],create: [],update: [],patch: [],remove: []
},error: {
all: [],find: [],remove: []
}
};
在编写此钩子之前,身份验证曾经可以正常工作,但是此后它开始向我发送“未经身份验证”的响应。
我没有更改feathersjs-cli生成的user.class.js和authentication.js文件中的任何内容。
我想知道我做错了什么?有没有一种更好的方法可以对响应进行消毒?
谢谢您的帮助!
解决方法
身份验证流程需要能够检索完整的用户信息,以将其添加到请求中,比较密码等。您可能想跳过sanitizeResponse
hook for internal calls(当context.params.provider
为undefined
时):
const sanitizeResponse = (context) => {
const query = context.params.query;
if(!context.params.provider || (!query.email && !query.cpf))
return context;
if(context.result.total){
context.result.data[0] = {exists: 1,id: context.result.data[0].id};
}else{
context.result.data[0] = {exists: 0};
}
};