0%

Simple password authentication is easy to do with has_secure_password. Here you will learn how to make a complete Sign Up, Log In, and Log Out process as well as restrict access to certain actions.

1. User model

1.1 database migrations

1
$ rails g migration create_users
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class CreateUsers < ActiveRecord::Migration
def up
create_table :users do |t|
t.string :name
t.string :email
t.string :password
t.string :remember_token
t.timestamps
end
end

def down
drop_table :users
end
end

1.2 the model file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation, :remember_token
has_secure_password

before_save { email: downcase! }
before_save :create_remember_token

VALID_EMAIL_REGEX = /\A[\w+\-.][email protected][a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: ture, format: { with: VALID_EMAIL_REGEX },
uniqueness: {case_sensitive: false}
validates :name, presence: true
validates :password, presence: true, length: { minimum: 6 }
validates :password_confirmation, presence: true
after_validates { self.errors.messages.delete(:password_digest) }

private
def create_remember_token
self.remember_token = SecureRandom.urlsafe_base64
end
end
Read more »