How to hash the security questions in rails?

Viewed 72

In my data schema for user, I have

  create_table "users", force: :cascade do |t|
    t.string "name"
    t.string "email"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.string "password_digest"
  end

To hash the password we have ' t.string "password_digest"', but what if I want to add security question to users? Is there any default function for hash the answer for security question?

1 Answers

If your code is working now, then you presumably have has_secure_password in your model.

This, by default, adds a password accessor to your model, and hashes the value into a column called password_digest.

You can change the column/attribute name by passing the name as the first argument to has_secure_password:

class User < ApplicationRecord

  has_secure_password
  has_secure_password(:security_question_1)
  has_secure_password(:security_question_2)

  ...

This will automatically hash user.security_question_1 = "..." to a column called security_question_1_digest.

Keep in mind:

  • this method is tailored for storing short user-generated passwords, using BCrypt, which means it has a maximum length of 72 characters.
  • this method also adds a validates_confirmation_of validator to your model. You can suppress this by passing validations: false.
Related