Rails 5 auth_token设计

时间:2018-12-11 19:06:33

标签: ruby-on-rails authentication devise

我在Rails 5项目中遇到一些问题。 我必须管理用户的注册,登录和注销。在进行注册时,将正确创建用户,并提供身份验证令牌。 注销后,身份验证令牌将被删除,但是再次登录时,不会生成身份验证令牌,它仍然为null。我该怎么办?

这是registrations_controller:

class RegistrationsController < Devise::RegistrationsController
skip_before_action :verify_authenticity_token,
                 :if => Proc.new { |c| c.request.format == 'application/json' }

respond_to :json

def create
build_resource
resource = User.new(user_params)
#resource.skip_confirmation!
if resource.save
  sign_in resource
  render :status => 200,
       :json => { :success => true,
                  :info => "Registered",
                  :data => { :user => resource,
                             :auth_token => current_user.authentication_token } }
else
  render :status => :unprocessable_entity,
         :json => { :success => false,
                    :info => resource.errors,
                    :data => resource }
end
end

private

def user_params
params.require(:user).permit(:name, :email, :password, :password_confirmation, :city, :street)
end

end

负责登录和注销的是sessionscontroller:

class SessionsController < Devise::SessionsController
skip_before_action :verify_authenticity_token,
                 :if => Proc.new { |c| c.request.format == 'application/json' }
skip_before_action :verify_signed_out_user
respond_to :json

def create
warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#failure")
render :status => 200,
       :json => { :success => true,
                  :info => "Logged in",
                  :auth_token => current_user.authentication_token,
                  :data => current_user}
end

def destroy
warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#failure")
current_user.update_column(:authentication_token, nil)
render :status => 200,
       :json => { :success => true,
                  :info => "Logged out",
                  :data => {} }
end

def failure
render :status => 401,
       :json => { :success => false,
                  :info => "Login Failed",
                  :data => {} }
end
end

这是用户模型:

 class User < ApplicationRecord
# Include default devise modules. Others available are:
 # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
 devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :validatable, :token_authenticatable

 before_save :ensure_authentication_token

#attr_accessor :name, :email, :password, :password_confirmation, :remember_me
has_many :videogames, dependent: :destroy
end

0 个答案:

没有答案