2014-01-26 33 views
2

我使用attr_encrypted来支持我的rails应用程序中的客户数据的加密。当密钥是静态的时候,gem正在工作,但是当我尝试使用proc从params[:key](因此我不需要存储密钥)在控制器中获取密钥时,密钥使用不正确。我当前的代码是:使用attr_encrypted和客户提供的密钥(未存储在数据库中)

客户模式:

class Customer < ActiveRecord::Base 
    belongs_to :store 
    attr_encrypted :phone, key: proc { |key| "#{key}" } , :attribute => 'phone_number' 

客户控制器:

class CustomersController < ApplicationController 
    def create 
    if params[:customer][:phone_number].present? 
     @customer = Customer.new(customer_params) 
     @customer.store_id = @store.id 
     key = params[:key] 
     @customer.phone = params[:customer][:phone_number] 
     @customer.phone_number 
     if @customer.save 
     return_response['new_customer']=1 
     else 
     render json: @customer.errors, status: :unprocessable_entity 
    end 

宝石说,我也可以通过一类方法的关键。有人对我如何使用它来实现不将密钥存储在数据库中的目的有任何想法吗?任何帮助将不胜感激。

回答

1

根据文档,您可以指定自定义方法或proc以动态获取密钥。两者都假设key在当前用户的范围内可用。

一种可能的方法是定义在客户一个新的实例变量的关键

class Customer < ActiveRecord::Base 
    attr_accessor :encryption_key 

,并指示宝石用它作为重点。

class Customer < ActiveRecord::Base 
    attr_accessor :encryption_key 
    attr_encrypted :phone, key: :encryption_key, :attribute => 'phone_number' 

现在你只需要确保在执行加密之前设置实例变量。您可以在创建客户后立即设置密钥

@customer.encryption_key = params[:key] 

或将呼叫中的属性传递给new

相关问题