GREAT explanation on how to use Rails Devise: https://launchschool.com/blog/how-to-use-devise-in-rails-for-authentication... Copied as a back up
How to Use Devise in Rails for Authentication
Devise and Warden
The Devise gem is built on top of Warden. Warden is a Rack application, which means that it runs as a separate and standalone module, and is (nearly always) executed before the chief Rails application is invoked.Warden provides the cookie handling that verifies the identity of a logged in user via a (secure) session string, in which the
id
(primary key) of a particular user is somehow stored and disguised.
Warden also provides a hook so your app can deal with users who aren’t
currently logged in. These users will either have restricted access, or
none at all, except, of course, to sign-in/sign-up pages.Warden knows nothing about the existence of your Rails app. As a result, Warden does not provide helper methods, controller classes, views, configuration options and log in failure handling. These things are what Devise supplies.
Devise often interacts with Warden using Strategies. (a strategy is a design pattern in which an algorithm is encapsulated within a dedicated class, which implements a method with a commonly shared name. You change the class to vary the algorithm). The Strategies that Devise employs are for encrypting passwords, email confirmations, and for HTTP Authentication. If you need to extend or augment Devise, you can implement a customized Strategy class. But this is an advanced subject, for which there is usually little call.
Understanding How Devise Works
Devise’s README contains all the information you need to get started, and it also touches on its more advanced features. It recommends that you understand the basic authentication techniques (i.e. registrations and logins) before you proceed to integrate it in your app.A Kick-Start Devise Installation
To have Devise completely installed in an existing Rails app, (where a user’s model class is named,User
), the following six shell commands are required:1 2 3 4 5 6 |
|
User
.Devise makes no assumption about the class name of the user model. Though it’s usually, ‘User’, or less commonly, ‘Admin’. These two class names can sit side-by-side in any app, as can any other names of user classes you may care to conjure up.
The
rails generate devise:views users
command creates the directory /app/views/users
with all the devise views, such as login form, registration form, etc.
If you want customize these files and have Devise use them you must set config.scoped_views
to true
in the configuration file, located at /app/config/initializers/devise.rb
.Devise Configuration
Once you have installed Devise, as per the above commands, the next step is configuration. This is specified in two main files:- Firstly in a global config file,
config/initializers/devise.rb
. If you change the settings in this, they won’t become effective until you restart the Rails server. And the settings apply to the whole site. - Secondly, in a model class representing a (registered) user, which can be tailored to suit a particular role, for example if your app has an end-user, as well as having a site administrator (more on this later).
Devise Utility Methods
Devise contains dozens of classes, including, models, controllers, mailers, helpers, hooks, routes, and views, but since Devise exposes it’s functionality in a small number of simple helper methods, It’s unlikely that you will even need to know of the existence of all of them. The most important helper methods Devise gives you to use in your own app are:- authenticate_user!
- current_user
- user_signed_in?
- sign_in(@user)
- sign_out(@user)
- user_session
authenticate_user!
Theauthenticate_user!
class method (controller only),
ensures a logged in user is available to all, or a specified set of
controller actions. This method is invoked via a before_filter
, for example:1 2 3 4 5 |
|
1
|
|
authenticate_user!
method’s use is for applications
that require a logged in user to access (a set of) their pages. In this
case, it is very common to use the current_user
method (see
just below) as the first receiver in a method chain that accesses a
database, for cases where a record’s owner is to be stored. For example:1 2 3 4 5 6 7 |
|
before_filter :authenticate_user!
line ensures that current_user
is never nil
, thus avoiding the fatal error: method called on nil
object.current_user
Thecurrent_user
method , whose purpose is self-explanatory, simply returns the model class relating to the signed in user. It returns nil
if a user has not, as yet, signed in.user_signed_in?
Theuser_signed_in?
query method, which really just checks if the current_user
method returns a value that’s not nil
.sign_in(@user) and sign_out(@user)
Thesign_in(@user)
and the sign_out(@user)
methods. These are useful to login (or logout) a (newly created) user.user_session
Theuser_session
method, which returns meta data on a logged in user.An application programmer will normally only need to use the
current_user
and user_signed_in?
methods regularly. These, of course, are present as helper methods. So
you can, for example, have a message in the header of your app stating
the name of the signed in user.Note that if you refer to an admin (who has a dedicated
Admin
class), the access method becomes current_admin
, not current_user
.The prefix, or sometime suffix, is the corresponding underscored class name of a user class. For example, a user class name of ‘EndUser’, when underscored, becomes ‘end_user’, so the logged in user would in this situation be
current_end_user
.Devise also defines a whole host of routes, which are defined in
config/routes.rb
with a line like:1
|
|
Devise Modules
When you invoke the Devise generator, a model class (in `app/models*) is created for you to modify for your specific requirements.This user model class is where many of the most important configuration options are specified. Perhaps the most important of these are the Devise modules to use. These modules provide enhanced security functionality. There are ten modules in all.
The modules are included thusly:
1 2 3 4 5 |
|
A number of these modules have associated HTML forms and links. In the forms, an end-user typically fills in their email address, and in exchange they are sent back an email which contains confirmation links back to Devise controllers in your app, and include an authentication to token for security. These forms are mostly to (re-)enable a particular account.
Although the Devise README lists these options, we’ll explain them a little here as well.
- database_authenticatable – ensures that a user enters a correct password, and it encrypts the said password, before saving it.
- confirmable – ensures newly registered users confirm their accounts by clicking a link on a (Devise sent) mail they receive. This is a defence against bots creating fake, but valid, users.
- recoverable – for handling forgotten passwords safely.
- registerable – allows users to register themselves, and subsequently change their login credentials.
- rememberable – for transparently logging on a user, based on a cookie. This is the functionality associated with the
Remember me?
checkbox you often see on login forms. Since the Devise config file specifies a timeout period, this is often of limited use. And is a security risk if the user steps away from their browser, with others about. - trackable – stores login information i.e. the user’s IP address, login time, last login time, and the total number of logins. These values are generally for site admins to look at, when trying to trace unusual activity.
- validatable – ensures that the given email/name and passwords conform to a particular format.
- lockable – limits the number of login attempts allowed before further access to a particular account is prohibited. Access restrictions are lifted after a time span, or if a (legitimate) user requests that an email be sent that contains a link to unblock his/her account.
Devise’s Global Configuration File
Devise has a very well commented configuration file,config/initializers/devise.rb
. This is where its site-wide settings are specified.These are things like the minimum password length, the password encryption algorithm, a flag to have a case sensitive username lookup, a timeout period, the ‘pepper’ string, and lots more as well. There is no substitute to actually taking a look at this file. If the options seem a bit bewildering at first, their exact purposes will become clearer on re-readings.
Protecting the Mass-Assignment of User Attributes
Naturally, all of the fields associated with a Devise user contain sensitive data, whose alteration could seriously compromise security. For this reason, it is probably a good idea never to allow your app to have pages (which are accessible to untrusted users) that update (or create) a user model. Only allow these attributes to be updated by Devise, where you know it’ll be done securely.If an app’s requirements ordain that auxiliary user information be kept, such as an address or a phone number, these details are best kept on an entirely separate table which has a foreign key back to the (Devise generated) user table. This auxiliary table would have a one-to-one relationship with the Devise user table.
If you really must add fields to the (Devise generated) user model you must absolutely make sure that Devise’s fields cannot be changed. The means by which you achieve this is different for Rails 4 apps than it is for Rails 3 apps. In the former case, it’s with
strong_parameters
in the controller. In the latter case, it’s with the attr_accessible
or attr_protected
class methods in the model.The Devise README explains this in adequate detail.
Adding Further Authentication
Having said all that in the preceding section, there is, arguably, an exception to this “no added user model fields” principle. This is where a user model has a flag likeadmin?
, which is used to distinguish an app’s administator (super-user) from a regular end-user.This is not a Devise added field, but one an app developer would add in a database migration. This field should not set up in a module or page of an actual app. Instead it should be set manually in a direct database command.
For example:
1 2 3 4 |
|
In some other kinds of apps, the site administrators may need perform a completely different set of tasks to regular users. In this case it is cleaner to have separate classes for a site administrator and for a regular user.
Handling Different Types of Users in Devise
In this section, we’ll take a look at some ways in which some common use-cases, relating to access restrictions, can be handled with Devise’s controller class methods (macros). (This is an area where the distinction betweenauthentication
and authorization
becomes blurred.)These class methods are invoked as
before filters
, and take effect for a number of the controller’s available actions.In this first case, suppose we want to ensure that every controller action requires a logged in user, except for the
login
and register
actions:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
1 2 3 4 5 6 7 8 9 |
|
User
class, and an admin has an Admin
class. For example:1 2 3 4 5 6 7 8 9 |
|
admin
flag set to a true value on the model record. Whereas regular users have this flag switched off. For example:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
CrudController
will ensure that black-listed users are prohibited from further editing, but can still look at the site.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
Devise Invitable Gem
If you want users to be registered through an invitation carried out by a site administrator, or by a group leader. (As an alternative to end-users explicitly registering themselves on provided web forms), there is a another gem to use,devise_invitable
.The Invitable gem generates a form in which a number of email addresses are filled in. Emails are sent out to the respective addresses inviting the users to confirm their registrations, which are actually performed by the site administrator.
As its name suggests, this gem must be used in conjunction with Devise. And it automatically links the invited users with the user who initially invited them.
Testing
It would be counter-productive to test Devise itself. It already has a comprehensive suite of tests that you are able run yourself, should you doubt its efficacy. However, you ought to test the parts of your app which interface with Devise, to ensure that Devise is presented with correct data, and to ensure that Devise remains in general working order.Also, your own app’s tests are very likely to depend on your having a logged-in user, on whose behalf, the various operations of controller, acceptance, integration and view tests, are performed.
You can programmatically create a devise user as follows:
1
|
|
db/seeds.rb
, and you run it with the shell command:1
|
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
Though some might argue that the testing of such functionality would be better placed in integration tests. That, in general, controller testing is often superfluous, and has poorer code coverage, than integration testing does.
An RSpec example of an integration test could be as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
Wrapping up
If you have not done so already, your next step is to peruse the Devise README. which is probably the best single document on the practical use of Devise that’s readily available. If you want to do something out of the ordinary with Devise there’s a comprehensive list of howtos.These two documents will, most likely, be the only ones you need to read in order to use Devise effectively.
Also if you would like more background information, take a look at the Devise wiki.
No comments:
Post a Comment