has_secure_password with Rails 4.1

I just started a new project with Rails 4.1 and explored the has_secure_password feature. Really awesome stuff!

I hope you are not storing passwords in clear text to your database! You should always store some kind of hashed values instead of clear text passwords. In case somebody steals your database he/she still doesn’t has the passwords.

There are a couple good tutorials how to hash and store passwords in a secure way. I implemented it a couples times by myself with Ruby.

A more sophisticated solution is devise, a very robust gem for security and authentication.

However. Since Rails 3.1 you can take advantage of has_secure_password. This mechanism in Rails takes care of password validation and encryption. It requires a field ‘password_digest’ in your model, where it will store the encrypted password. Let’s generate a simple model.

rails g model user username:string password_digest:string

Let’s add this line to the user model.

has_secure_password

This will add an attribute `password` and `password_confirmation` to your model. This 2 fields are now part of your model but not part of the database schema! Because we don’t want to store cleartext passwords.

Let’s add some tests.

require 'spec_helper'

describe User do

  it "fails because no passwrod" do
    User.new({:username => "hans"}).save.should be_false
  end

  it "fails because passwrod to short" do
    User.new({:username => "hans", 
      :password => 'han'}).save.should be_false
  end

  it "succeeds because password is long enough" do
    User.new({:username => "hans",
      :password => 'hansohanso'}).save.should be_true
  end

end

3 very simple tests. Persisting a new user without password should fail. Persisting a new user with too short password should fail as well. And creating a new user with a long password should succeed. If you run this tests with RSpec the 2nd test will fail. By default Rails doesn’t has a validation for the length of the password. So let’s add it to our user model.

class User < ActiveRecord::Base

  has_secure_password

  validates :password,
    :length => { :minimum => 5 }

end

If you run the tests again, they will be green. If you take a look into your database you will see that the user table/collection has a column `password_digest` with a very cryptical value. But there are no columns for password! That’s exactly what we wanted.

Now lets do the authentication. Assume a new user signed up at your portal and now he wants to login. This is how you authenticate him.

user = User.find_by_username("USERNAME").authenticate("CLEAR_TEXT_PASSWORD") 

If the username and the clear text password from the HTTP Request is correct it will return a valid user from the database. Otherwise it will return nil!

`has_secure_password` validates the password on creation time, the very first time you persist it. It doesn’t check the password field after that, for updates for example. And that’s OK. Because that means you can load a user later from db, change it and persist it without knowing the password.

Another feature of this mechanism is password confirmation. `has_secure_password` also adds an attribute `password_confirmation` to your model. This attribute gets only validated if it’s not nil. If it’s not nil it must be equal to the password attribute. Let’s add 2 more tests for that one.

  it "fails because password confirmation doesnt match" do
    User.new({:username => "hans",
      :password => 'hansohanso',
      :password_confirmation => 'aa'}).save.should be_false
  end

  it "succeeds because password & confirmation match" do
    User.new({:username => "hans",
      :password => 'hansohanso',
      :password_confirmation => 'hansohanso'}).save.should be_true
  end

To make this tests pass you have to add one more line to the model.

class User < ActiveRecord::Base

  has_secure_password

  validates :password,
    :length => { :minimum => 5 }

  validates_confirmation_of :password

end

The line “validates_confirmation_of :password” will check the password confirmation.

Rails doesn’t force you to have a password confirmation for your model, but if you want it you can turn it on.

I really like this feature because it saves me a lot of code and development time. And for most applications this is really enough.

Let me know what you think about this, either in the comments or on Twitter.

Geek2Geek NoSQL

Join the next Geek2Geek in Berlin this Friday night. We will talk about NoSQL databases and have talks to Neo4J, CouchDB and ArangoDB.

Geek2Geek

The MeetUp will happen at CO.UP in Kreuzberg. Which is a pretty cool coworking space.

Locafox, a young StartUp from Berlin, will sponsor pizza & beer. They are currently hiring in all areas. Check out their job listings here: http://locafox.de/jobs. And many thanks for the pizza. We really appreciate that.

Comparison of Application Level Package Managers

I have to work with a lot (9) of different package managers at my daily work at VersionEye. Part of our mission is it to make manual updating of dependencies extinct, because it’s a manual and time consuming task which nobody enjoys. That’s why we are building a notification system for open source software libraries to make Continuous Updating easy and fun. And since we support several programming languages – 8 at this point! – I get to write crawlers and parsers for all of them. To give you a better overview over the strengths and weaknesses of these package managers, I picked the most popular one for each language and will compare them. The contenders are:

  • RubyGems / Bundler (Ruby)
  • PIP / PyPI (Python)
  • Packagist / Composer (PHP)
  • NPM (Node.JS)
  • Bower (JS, CSS, HTML)
  • CocoaPods (Objective-C)
  • Maven (Java)
  • Lein (Clojure)

Comparison Matrix

Here are the results of my comparison.

Comparison of Package Managers

You can read the complete article on the VersionEye Blog and follow the discussion on hacker news and Reddit.

Semantic Versioning

Do you know semantic versioning? You should! It describes how to name version numbers. Check it out here: semver.org.

This is the pattern it describes:

MAJOR.MINOR.PATCH

MAJOR version when you make incompatible API changes 
MINOR version when you add functionality in a backwards-compatible manner
PATCH version when you make backwards-compatible bug fixes

The cool thing here is that on the version number itself you can already see how big the changes are in the new release. A typical semantic version number is this:

3.2.1 

Let’s say I am using version “3.2.0″ in my project. Now I can immediately see that the new version of the package “only” contains a patch. That means for me that I can update without worrying. On the other side if this version comes out:

4.0.0 

And I am using version “3.2.1″ of the package in my project, I can now immediately see that this update will very likely break my build! In this case I have to look into the change logs and follow the migration paths.

Semantic versioning even addresses alpha and beta versions. If you are working on version “4.0.0″ but it’s not quiet ready but you wanna release anyway something, you can name it like this:

4.0.0-a

That means that is version “4.0.0″ alpha. And this here would be the beta version:

4.0.0-b 

Another convention is “RC”, that means “Release Candidate”. You can use it like this:

4.0.0-RC1 
4.0.0-RC2

The complete order over all of them is like this, the highest and newest version is on the top.

4.0.0
4.0.0-RC2 
4.0.0-RC1
4.0.0-b
4.0.0-a

That basically means 4.0.0 > 4.0.0-RC2 > 4.0.0-RC1 > 4.0.0-b > 4.0.0-a.

I’m the author of naturalsorter. That is an open source library to sort semantic version numbers in the correct way.

VersionEye now supports CocoaPods

This week we finished the CocoaPods integration for VersionEye. VersionEye tracks now 2857 Objective-C packages on a daily basis. This here is the VersionEye page JSONKit.

Screen Shot 2013-11-15 at 15.29.28

You can follow the Objective-C packages you are using in your projects for your iPhone dev work and as soon the next version is released you will get notified via email.

If you are using CocoaPods as package manager you can directly upload your Podfile to VersionEye and you will see the out-dated dependencies. This here is a simple Podfile.

platform :ios
pod 'SSToolkit'
pod 'AFNetworking', '>= 0.5.1'
pod 'CocoaLumberjack'
pod 'Objection', :head # 'bleeding edge'
generate_bridge_support!

It defines 4 packages for the project. If your project is on GitHub, VersionEye can directly monitor your Podfile in your GitHub repository and notify you as soon there are updates available for your project.

Screen Shot 2013-11-15 at 15.36.00

The CocoaPods integration is a very new feature. We rely on your feedback. Please let me know if you find something odd or your have further feature requests.