gpt4 book ai didi

ruby-on-rails - devise_token_auth - 是否可以验证用户!不会使过滤器链失败?

转载 作者:行者123 更新时间:2023-12-04 06:29:25 25 4
gpt4 key购买 nike

我有一个 API 需要根据是否有登录用户返回结果。我正在使用 devise_token_auth在 rails 端,ng_token_auth 在客户端(Angular)。

在我的 Controller 中,我想做如下事情:

  • 尝试对用户进行身份验证,但如果身份验证失败,请不要让过滤器链失败。
  • 在创建响应负载时使用 current_user(current_user 将包含 nil 或经过身份验证的用户)。

  • 以这段代码为例:
    class Api::MyController < Api::ApiController
    before_filter :authenticate_user!

    def index
    if current_user
    # Create the result json using current_user
    else
    # Create the result json without user data
    end

    render json: result
    end
    end

    只有经过身份验证的用户才能通过authenticate_user!调用并获取 index 方法。 我要 到达那里的所有用户,包括经过身份验证的和未经身份验证的。

    最佳答案

    您可以尝试以下操作(未测试,因为我目前没有安装 Rails)。

    skip_before_filter :authenticate_user!, only: [:index_auth_failed]

    before_filter do
    authenticate_user! rescue redirect_to index_auth_failed
    end

    def index
    # current_user exists
    end

    def index_auth_failed
    # current_user does not exist
    end

    关于ruby-on-rails - devise_token_auth - 是否可以验证用户!不会使过滤器链失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32176890/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com