yerassyl
yerassyl

Reputation: 3048

Password encryption in Rails

I have User model and use Devise gem on it. In my application i have an admin user who can register other users (for example:clients). Then these users can log in by themselves with randomly generated password. (But no one can register by themselves, only admin can register users.)

When I am creating user from other user logged in, i.e admin user creates another user , i want to generate some random password, encrypt it, and save to database.

How to encrypt passwords, so that it will work with Devise authorization. I guess I have to use the same method as Devise?

I want something like that: EDIT:

def create
  @user = User.new(user_params)
  # set @user.password to some random encrypted password  

  @user.save
end
So every created user will get some random password.

The reason i am asking this, is that i think that if my encryption/decription will not match what devise uses users will not be able to log in with their passwords, since when they log in their input is encrypted via devise's encryption.

Upvotes: 1

Views: 3073

Answers (2)

Francesco Belladonna
Francesco Belladonna

Reputation: 11689

If you are using Devise and you have :database_authenticable enabled, you don't need what you describe at all.

Devise encrypts automatically when it saves to the database and doesn't decrypt when it reads it back, however when you store it in the password field, it can be plain text, Devise will take care of it for you only when writing (so it will stay plain text until you save).

So in your controller to create new users you can just do the following:

def create
  # I assume your form will pass a `params[:password]` in plain text too
  @user = User.new(user_params)
  @user.password_confirmation = params[:password]
  @user.save
end

This should be enough for your purpose, don't need to match devise encryption

Update 1:

To generate a random password in addition, you can do something like:

require 'securerandom'

def create
  # I assume your form will pass a `params[:password]` in plain text too
  @password = SecureRandom.hex(16)
  @user = User.new(user_params.to_h.merge(password: @password, password_confirmation: @password))
  @user.save
  # Remember to display `@password` in some way to the user
end

Upvotes: 2

Pavan
Pavan

Reputation: 33542

You should be having :database_authenticatable as one of the devise modules in your User model.

From Devise, it says

Database Authenticatable: encrypts and stores a password in the database to validate the authenticity of a user while signing in. The authentication can be done both through POST requests or HTTP Basic Authentication.

Upvotes: 0

Related Questions