用途:这是面向 Phoenix LiveView 认证工作的技能,要求在编写 on_mount 钩子、LiveView 认证 plug 或 LiveView 模块中的会话处理之前先调用。它需要 phoenix-scopes 提供 Scope 结构;访问控制可参考 phoenix-authorization-patterns,编写 LiveView 模块前可参考 phoenix-liveview-essentials。
主要规则:只用 on_mount 回调,不在 mount/3 中直接检查认证;:halt 必须带 flash 重定向,不能静默断开连接;on_mount 钩子只定义一次,通过路由中的 live_session 引用,不在多个模块重复认证逻辑;用 import Phoenix.Controller, except: [redirect: 2, put_flash: 3] 解决导入冲突,让 LiveView 的 redirect/2 和 put_flash/3 优先;对可能渲染未认证用户的模板使用 assigns[:current_scope] 括号访问,避免 @current_scope 抛 KeyError;每个 LiveView 回调加 @impl true。
用法:在 UserAuth 中定义 on_mount 钩子(如 :require_authenticated_user、:redirect_if_authenticated、:mount_current_scope),用 mix compile 验证;在 router 中为 live_session 绑定钩子并分组路由,用 mix phx.routes 验证;用 mix test test/my_app_web/live/ 运行认证测试并核对重定向元组。同时提供 assets/on_mount_template.ex 模板。
适用场景:Phoenix 1.7 的 current_user 与 Phoenix 1.8+ 的 Scope,含基于角色的变体。限制:实现细节与版本适配以官方文档为准,资料未提供收费、价格等信息。