Apostrophe CMS创建关联apostrophe-user的公开Profile模块问题咨询
问题1:登出后用户档案不显示的问题
原因
该问题的根本原因不是用户缺少published状态,而是apostrophe-users模块默认的权限策略禁止匿名用户读取用户数据,关联查询(join)时会默认执行权限校验,匿名用户没有读取用户数据的权限,所以关联返回的_user字段为空,自然没有内容渲染。你手动添加published字段不会生效,因为apostrophe-users默认没有把发布状态纳入权限判断逻辑。
解决方案
你只需要在profiles模块的_user关联配置中添加withPermissions: false参数,跳过本次关联查询的权限校验即可:
// lib/modules/profiles/index.js 对应的join配置修改为 { name: '_user', label: 'User', type: 'joinByOne', withType: 'apostrophe-user', idField: 'userId', withJoins: true, // 新增该行,跳过关联查询的权限检查 withPermissions: false }
注意:跳过敏检后不要在公开模板输出用户敏感信息(如未脱敏的邮箱、手机号等),避免数据泄露。之前新增的
published字段无实际作用,可以删除。
问题2:配置登录用户仅可编辑自身个人档案
完全可以实现,你只需要在profiles模块中增加权限校验逻辑即可,示例代码如下:
// lib/modules/profiles/index.js 新增construct配置 module.exports = { extend: 'apostrophe-pieces', name: 'profile', label: 'Profile', pluralLabel: 'Profiles', slugPrefix: 'profile-', addFields: [ // 你原来的字段配置保持不变 ], // 新增以下逻辑 construct: function(self, options) { // 新建档案时自动绑定当前登录用户,无需手动选择 self.beforeSave = async function(req, piece, options, callback) { if (req.user && !piece.userId) { piece.userId = req.user._id; } return callback(null); }; // 重写编辑权限校验逻辑 self.canEdit = function(req, piece) { // 管理员保留所有档案的编辑权限 if (req.user?.permissions?.admin) { return true; } // 普通用户仅可编辑绑定了自己ID的档案 return req.user && piece.userId === req.user._id; }; } };
内容的提问来源于stack exchange,提问作者Felix
相关产品推荐
相关产品推荐

