har*_*nsa 36 ruby-on-rails deprecated devise
我之前一直token_authenticatable
用来保护我的API,但是,我发现它已被弃用了?我应该使用什么,为什么他们弃用它?
Nea*_*eal 41
我想保持向后兼容性,所以我只是将所有内容都转移到关注点以避免警告.这是我的代码和相关规范:
/app/models/concerns/token_authenticatable.rb
module TokenAuthenticatable
extend ActiveSupport::Concern
module ClassMethods
def find_by_authentication_token(authentication_token = nil)
if authentication_token
where(authentication_token: authentication_token).first
end
end
end
def ensure_authentication_token
if authentication_token.blank?
self.authentication_token = generate_authentication_token
end
end
def reset_authentication_token!
self.authentication_token = generate_authentication_token
save
end
private
def generate_authentication_token
loop do
token = Devise.friendly_token
break token unless self.class.unscoped.where(authentication_token: token).first
end
end
end
Run Code Online (Sandbox Code Playgroud)
/app/models/user.rb
class User < ActiveRecord::Base
include TokenAuthenticatable
end
Run Code Online (Sandbox Code Playgroud)
/app/models/employee.rb
class Employee < ActiveRecord::Base
include TokenAuthenticatable
end
Run Code Online (Sandbox Code Playgroud)
/spec/models/user_spec.rb
describe User do
it_behaves_like 'token_authenticatable'
end
Run Code Online (Sandbox Code Playgroud)
/spec/models/employee_spec.rb
describe Employee do
it_behaves_like 'token_authenticatable'
end
Run Code Online (Sandbox Code Playgroud)
规格/ shared_examples/token_authenticatable.rb
shared_examples 'token_authenticatable' do
describe '.find_by_authentication_token' do
context 'valid token' do
it 'finds correct user' do
class_symbol = described_class.name.underscore
item = create(class_symbol, :authentication_token)
create(class_symbol, :authentication_token)
item_found = described_class.find_by_authentication_token(
item.authentication_token
)
expect(item_found).to eq item
end
end
context 'nil token' do
it 'returns nil' do
class_symbol = described_class.name.underscore
create(class_symbol)
item_found = described_class.find_by_authentication_token(nil)
expect(item_found).to be_nil
end
end
end
describe '#ensure_authentication_token' do
it 'creates auth token' do
class_symbol = described_class.name.underscore
item = create(class_symbol, authentication_token: '')
item.ensure_authentication_token
expect(item.authentication_token).not_to be_blank
end
end
describe '#reset_authentication_token!' do
it 'resets auth token' do
end
end
end
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
19729 次 |
最近记录: |