gpt4 book ai didi

ruby-on-rails - 在设计 [Rails 4] 之上滚动 token 认证机制

转载 作者:行者123 更新时间:2023-12-03 17:51:56 25 4
gpt4 key购买 nike

阿罗哈,

在发现 Devise 的 token_authenticable 已贬值后,我现在尝试推出自己的解决方案,但是我认为我在设计的 sign_in 方法上遇到了问题:

规范:

context "with an admin user" do
before(:each) { @user = FactoryGirl.create(:user, account_type: 'admin') }
it "should respond with a 200 status" do
post :verify, "token"=> @user.authentication_token
response.status.should eq(200)
end
end

错误:
1) UsersController#verify with an admin user should respond with a 200 status
Failure/Error: post :verify, "token"=> @user.authentication_token
NoMethodError:
undefined method `user' for nil:NilClass
# ./app/controllers/application_controller.rb:24:in `authenticate_user_from_token!'
# ./spec/controllers/users_controller_spec.rb:39:in `block (4 levels) in <top (required)>'

application_controller.rb:
class ApplicationController < ActionController::Base
# If there's a token present we're using the api authentication
# mechanism, else we fall back to devise auth
before_filter :authenticate_user_from_token!, :authenticate_user!

# Setup an AccessDenied error
class AccessDenied < StandardError; end
# setup a handler
rescue_from AccessDenied, :with => :access_denied


private

# API requests should be made to the resource path
# with the requesters token as params.
#
# This method extracts the params, checks if they are
# valid and then signs the user in using devise' sign_in method

def authenticate_user_from_token!
user = User.find_by_authentication_token params[:token]

if !user.nil? && user.admin?
# store: false ensures we'll need a token for every api request
sign_in user, store: false # this is the line the spec complains about
else
raise ApplicationController::AccessDenied
end
end

def access_denied
render :file => "public/401", :status => :unauthorized
end


end

用户 Controller .rb
class UsersController < ApplicationController

[snip]

# We use this 'verify' method to provide an endpoint
# for clients to poll for token verification
# If the before filter rejects the user/token
# they recieve a 401, else we respond with a 200
# and the user params for verification on the remote app
def verify
user = User.find_by_authentication_token params[:token]
render json: user
end
end

我不知道错误提到的“用户”方法在哪里被调用,也不知道它被调用的对象是什么。

最佳答案

我找到了 Authy 的 devise module基于 token 的身份验证非常易于使用/修改,而​​不是从头开始。

关于ruby-on-rails - 在设计 [Rails 4] 之上滚动 token 认证机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19465137/

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