Flutter Supabase社交应用:关注帖查询与私密帖权限实现咨询
在Flutter Supabase中实现社交应用帖子查询与权限控制
场景一:获取关注用户的帖子
核心思路是先拿到当前用户的following列表,再筛选发布者UUID在该列表内的所有帖子:
获取当前登录用户UUID
final currentUserUuid = supabase.auth.currentUser?.uuid; if (currentUserUuid == null) { // 处理未登录逻辑 return; }查询当前用户的关注列表
final followingData = await supabase .from('connections') .select('following') .eq('uuid', currentUserUuid) .single(); final List<String> followingUuids = List<String>.from(followingData['following']);拉取关注用户的所有帖子(按发布时间倒序)
final followedPosts = await supabase .from('posts') .select('*, users(*)') // 可选:关联查询发布者详情 .in_('uuid', followingUuids) .order('created_at', ascending: false);
场景二:私密帖子的权限控制
要实现仅circle内用户可查看私密帖子,必须结合Supabase行级安全(RLS)策略和前端查询,从底层拦截无权限访问:
第一步:配置Supabase RLS策略
在Supabase控制台完成以下操作:
- 开启
posts表的行级安全开关 - 创建读取权限策略,SQL条件如下:
-- 公开帖子所有人可见;私密帖子仅作者circle内用户可见 (is_public = true) OR (EXISTS ( SELECT 1 FROM connections WHERE connections.uuid = posts.uuid AND current_setting('request.jwt.claims')::json->>'sub' = ANY(connections.circle) ))
同时,为connections表配置基础访问策略,确保权限校验能正常读取circle字段:
CREATE POLICY "允许访问connections必要数据" ON connections FOR SELECT USING ( -- 用户可查看自己的全量数据,或仅查看其他用户的circle字段用于权限判断 uuid = current_setting('request.jwt.claims')::json->>'sub' OR true );
第二步:Flutter前端查询实现
前端无需额外做权限过滤,直接正常查询即可,RLS会自动拦截无权限的私密帖子:
// 查询当前用户可见的所有帖子(含公开帖+有权限的私密帖) final visiblePosts = await supabase .from('posts') .select('*, users(*)') .order('created_at', ascending: false); // 单独查询某用户(如用户B)的帖子 final userBPosts = await supabase .from('posts') .select('*, users(*)') .eq('uuid', 'user_b_uuid') .order('created_at', ascending: false);
此时若当前用户不在用户B的circle列表中,返回结果只会包含用户B的公开帖子,私密帖会被RLS自动过滤。
内容的提问来源于stack exchange,提问作者Raj A
相关产品推荐
相关产品推荐

