Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3.1. Create one user in console with secure password

I want to create one user (admin) and I want to use console (without user registration model). I use solution from RailsCasts (http://railscasts.com/episodes/270-authentication-in-rails-3-1). But I have one problem: when I do User.create(..., :password => "pass") in console my password stored in database without encription (like "pass"). And I can't login with my data.

How can I create user from console? :)

like image 809
Oleg Pasko Avatar asked Oct 27 '11 17:10

Oleg Pasko


People also ask

What is Password_digest?

The has_secure_password method encrypts passwords by hashing and salting the passwords and generate 'password_digest'. Please read Wikepedia on how bcrypt works. The has_secure_password method in turn gives you, #authenticate method, which you can use to authenticate passwords.

How does Rails authentication work?

The Authentication Concern provides an interface for logging the user in and out. We load it into the ApplicationController so that it will be used across the whole application. The login method first resets the session to account for session fixation.


1 Answers

Straight from the Rails API

# Schema: User(name:string, password_digest:string)
class User < ActiveRecord::Base
  has_secure_password
end

user = User.new(:name => "david", :password => "", :password_confirmation => "nomatch")
user.save                                                      # => false, password required
user.password = "mUc3m00RsqyRe"
user.save                                                      # => false, confirmation doesn't match
user.password_confirmation = "mUc3m00RsqyRe"
user.save                                                      # => true
user.authenticate("notright")                                  # => false
user.authenticate("mUc3m00RsqyRe")                             # => user

You need to include :password_confirmation => "pass in your hash!

Right, so taking a look at has_secure_password you want to perform BCrypt::Password.create(unencrypted_password) to obtain it. You'll need the bcrypt-ruby gem to do the above.

like image 129
Michael De Silva Avatar answered Oct 10 '22 10:10

Michael De Silva