0

我的会话控制器方法(对于API)使用模型方法来生成令牌。接下来它应该使用json将令牌发送到前端。但是,在render json一行中,api_token不再可用,并且是nil。应该怎么处理呢?如何使模型方法中的属性集在控制器中可用? attr_accessor不工作?

module Api 
    module V1 
    class ApiSessionsController < Api::BaseController 
     def create 
     user = User.friendly.find_by(email: create_params[:email].downcase) 
     if user && user.authenticate(create_params[:password]) 
      user.create_api_token 
      render json: { api_token: api_token }, status: :ok 
     else 
      render json: {errors: "wrong credentials" }, status: :unauthorized 
     end 
     end 
    end 
    end 
end 

class User < ActiveRecord::Base 
    attr_accessor :api_token 
    has_secure_password 

    def create_api_token 
     begin 
     self.api_token = User.new_token 
     api_digest = User.digest(api_token) 
     end while self.class.exists?(api_digest: api_digest) 
     update_attributes(api_digest: api_digest, api_sent_at: Time.zone.now) 
    end 

    def User.digest(string) 
     cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost 
     BCrypt::Password.create(string, cost: cost) 
    end 
end 

回答

1

我相信行应该是未被定义的,因此你收到nil

+0

也许我这样做是错误的,但我

render json: { api_token: user.api_token }, status: :ok 

控制器代码引用api_token变量m仅将令牌的加密摘要保存到数据库。所以'user.api_token'不存在('user.api_digest'确实存在)。为了授权,将令牌与摘要进行比较。我会将摘要方法添加到OP中。 – Marty

+0

@Marty你的问题是什么? – Alik

+0

基本上如何解决这个问题。我需要控制器中'api_token'的值。我明白,在目前的设置中,它的价值在控制器中是不可用的。我能想出的唯一选择是将'create_api_token'的完整代码放在控制器中。但这似乎不正确/有效。你会同意这是唯一/最好的解决方案,还是你看到更好的解决方案? – Marty

相关问题