0

I am using devise for authentication, register. Now i want to save emailId in MySQL in encrypted format. So i use gem 'aescrypt'.

My controller:

 def create
    @dashboard_user = DashboardUser.new(dashboard_user_params)
    @dashboard_user.created_by=current_dashboard_user.username
    @dashboard_user.company_id=current_dashboard_user.company_id
    active_ind = ""
    email = @dashboard_user.email

    if params["active"] == nil then
      active_ind = "0"
    else
      active_ind = "1"
    end

    @dashboard_user.active = active_ind
    @dashboard_user.email= AESCrypt.encrypt(email, "password")

    respond_to do |format|
      if @dashboard_user.save
        format.html { flash[:notice] = 'User successfully Created.' and redirect_to action: "index"}
      else
        @dashboard_user.email = email
        format.html { render :new }
      end
    end
  end

When i try to save user, it throws Email invalid. I removed validation for email in model. Even though same error exists. What problem it is? If there any way to encrypt data after validation?

Thanks in advance.

2
  • Can you post a snippet of your DashboardUser class? What's the auth key in config/initializers/devise.rb ? Commented Nov 13, 2014 at 11:57
  • config.authentication_keys = [ :username ]@Novae Commented Nov 13, 2014 at 13:18

3 Answers 3

1

How do you validate email? You could use a custom method to decrypt it before validate against (for e.g.) a regex. Alternatively, you can use ActiveRecord Callbacks. In your case, after_validation can be useful :)

after_validation(on: :create) do
  self.email= AESCrypt.encrypt(email, "password")
end
Sign up to request clarification or add additional context in comments.

7 Comments

undefined method `after_validation' for DashboardUsersController:Class
Where i want to define?
Oh no, is an Active::Record method! You should put it in your model, not in the controller :)! Put it in DashboardUser
How to decrypt in view?
You're welcome :). Keep in mind that next time you'll get the record from the database, the password will be already encrypted. So the validation could fail. You should validate it only during creation, just add on: :create as a parameter to the validates :email (that you can now re-enable
|
0

You can encrypt the data using using a method triggered by the after_validation callback. It is described here: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

Comments

0

On its model you can just declare like the example scenario below: E.g.:

after_validation :encrypt_cc_number, on: :create

It will validate then encrypt the credit car number on a create action.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.