Login Form Not Showing Devise Errors, but Registration Is Updated FREE
Login Form Not Showing Devise Errors, but Registration Is
In the previous episode [watch, read] nosotros showed how to fix up devise for user authentication in a Rail awarding. This time we'll continue from where we left off and show you how to customize devise.
We'll be working with the same application we used last time so nosotros already accept some authentication in identify, with pages for signing up, logging in and logging out of the application.
Restricting Admission
The next step we desire to take is to restrict certain actions to users who have logged in. Only those users should be able to create, edit or destroy projects. To do this we need to modify the ProjectsController
, adding a before_filter
that calls a method provided by devise called authenticate_user!
. This method ensures that the user is logged in and if not redirects them to the login page. All users should exist able to encounter the index
and show
actions so we'll add together an :except
parameter to exclude those deportment from the filter.
form ProjectsController < ApplicationController before_filter :authenticate_user!, :except => [:show, :index] def index #rest of class
If we click the "New Project" link now when we're not logged in we'll exist taken to the login page.
This technique works well if your say-so is simple and you simply need to ensure that a user is logged in. For more than complex potency needs an additional potency solution such every bit CanCan, which was covered in episode 192 [sentry, read] can exist used with devise.
Customizing Devise'due south Views
Next we'll show you how to customize the way that devise's views await. If you lot've gone to a lot of endeavour on the look of your site then y'all'll want the forms that devise provides to lucifer the rest of your pages. Every bit devise is a Rails Engine it provides its own views but these can be easily overridden by adding them into your own application and devise provides a generator to arrive easy to copy these views over. From our application'southward directory we tin run rails generate devise_views
and the view files will be created for u.s..
$ rails generate devise_views create app/views/devise create app/views/devise/confirmations/new.html.erb create app/views/devise/mailer/confirmation_instructions.html.erb create app/views/devise/mailer/reset_password_instructions.html.erb create app/views/devise/mailer/unlock_instructions.html.erb create app/views/devise/passwords/edit.html.erb create app/views/devise/passwords/new.html.erb create app/views/devise/registrations/edit.html.erb create app/views/devise/registrations/new.html.erb create app/views/devise/sessions/new.html.erb create app/views/devise/shared/_links.erb create app/views/devise/unlocks/new.html.erb
This command copies all of the views over from the devise Rail Engine so nosotros can now edit them to fit our needs. For example below is the view code for the sign in page we saw earlier.
/app/views/devise/sessions/new.html.erb
<h2>Sign in< / h2> <%= form_for(resource_name, resource, :url => session_path(resource_name)) do |f| %> <p><%= f.label :e-mail %>< / p> <p>< %= f.text_field :email %></p> <p><% = f.label :password %>< / p> <p><%= f.password_field :password %>< / p> < % if devise_mapping.rememberable? - %> <p > < %= f.check_box :remember_me %> <% = f.label :remember_me %>< / p> <% end -%> <p><%= f.submit "Sign in" %>< / p> < % end %> < %= render :partial = > " devise/shared/links " %>
We'll change the page to this:
<% title " Sign In " %> <%= form_for(resource_name, resource, :url => session_path(resource_name)) do |f| %> <ol class= " formList " > <li> <%= f.label :email %> <%= f.text_field :e-mail %> </li> <li> <%= f.label :password %> <%= f.password_field :password %> </li> <% if devise_mapping.rememberable? -%> <li> <%= f.check_box :remember_me %> <%= f.label :remember_me %> </li> <% cease %> <li> <%= f.submit " Sign in " %> </li> </ol> <% terminate %> <%= return :partial => " devise/shared/links " %>
In the code above we've replaced the header with a call to the title
method that'southward provided past Ryan Bates' nifty generators. This means that the text volition also appear in the page'southward title. (This play tricks was covered back in episode thirty [watch, read].) Nosotros've also changed the layout of the page and so that the form elements are rendered as office of a list. With some CSS styling this tin can be used to move each text field'south characterization so that it appears next to the field itself.
All of the other views can exist customized in a like way so that they fit in with the balance of your awarding.
Customizing Error Letters
Devise has a number of mistake messages that are shown when something goes awry. For instance if y'all enter an incorrect email address or countersign you'll see the message "Invalid email or password". All of these messages are stored in a locale file, making it piece of cake to change them or to translate them into other languages. In the locale file beneath we've changed the devise.failure.invalid
bulletin.
en: errors: letters: not_found: " not institute " already_confirmed: " was already confirmed " not_locked: " was non locked " devise: failure: unauthenticated: 'You demand to sign in or sign upward before continuing.' unconfirmed: 'You lot have to confirm your account before standing.' locked: 'Your account is locked.' invalid: 'OH NOES! Error IN TEH E-mail!' invalid_token: 'Invalid authentication token.' timeout: 'Your session expired, please sign in once again to keep.' inactive: 'Your business relationship was non activated yet.' sessions: signed_in: 'Signed in successfully.' signed_out: 'Signed out successfully.' #rest of file omitted.
When nosotros try to log in with an invalid email address the updated message is shown.
That covers the error letters, but what about the validations that devise shows, for instance when someone enters incorrect details when signing up?
Within the awarding'due south /config/initializers
directory is a file chosen devise.rb
and this file contains a large number of options that we can employ to configure devise. These options are well documented so its easy to determine which ones demand to be contradistinct if y'all want to make changes. So, if we want to reduce the minimum password length to four characters from vi then we tin can merely uncomment out the bottom line from this part of the file and make the necessary change. Notation that you'll need to restart the server after making any changes so that they're picked upward by the application.
# ==> Configuration for :validatable # Range for password length # config.password_length = 6..20
If we want to accept this further we can remove the default ready of validations and supersede it with our own. If nosotros wait in our User
model we'll encounter a list of the devise modules that our application is using, one of which is :validatable
.
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :lockable, :timeoutable and :activatable # :confirmable, devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable # Setup accessible (or protected) attributes for your model attr_accessible :email, :password, :password_confirmation end
The :validatable
module handles the validations on the email and password when nosotros sign upwardly. If we desire to change that behaviour nosotros can remove that module and handle the validations ourself. The defaults in the validatable module are expert enough for most purposes though so we'll leave them equally they are for now.
Routing
Next we'll wait at customizing the routes. By default the sign-up folio is at /users/sign_up
just we want to change that to /register
. When ran the devise generator in the last episode it created a road called devise_for :users
. We tin can change this route with a number of different parameters to alter the routes to conform our needs.
ProjectManage::Awarding.routes.depict exercise |map| devise_for :users resource :projects root :to => ' projects#index ' end
One of the parameters we tin can add is called :path_names
and we can use information technology to alter the road for our signup page.
ProjectManage::Application.routes.draw do |map| devise_for :users, :path_names => { :sign_up => " register " } resources :projects root :to => ' projects#alphabetize ' cease
In one case we've made this alter we'll see a routing error when nosotros visit /users/sign_up and instead we'll accept to visit /users/annals
. There are a number of other options that tin exist passed to the devise_for route and these are listed in the documentation.
Customizing The Login Requirements
Our application currently uses an email address and password to log users in, but if we desire to alter it so that it asks for a username instead of an email accost so we can do so fairly easily.
The get-go matter nosotros need to do is create a username
column in the User
table, which nosotros can exercise past generating a migration.
$ rails generate migration add_username_to_users username:string
That done we'll run the migration.
As nosotros only have one user in the database we can quickly log in to the Rails console and set a value for the username attribute for that user.
$ rails c Loading evolution environs (Rails 3.0.0.beta2) reddish-1.8.7-p249 > User.start.update_attribute(:username, "eifion") => true
Now that we've modified the database we need to modify devise's configuration file, uncommenting the config.authentication_keys
line and changing its value from :email
to :username
.
config.authentication_keys = [ :username ]
With this value set devise will use the username field equally the authentication key. We'll also have to modify the sign in form and so that it has a username field instead of the email field.
<% title " Sign In " %> <%= form_for(resource_name, resources, :url => session_path(resource_name)) practise |f| %> <ol class= " formList " > <li> <%= f.label :username %> <%= f.text_field :username %> </li> <li> <%= f.characterization :password %> <%= f.password_field :password %> </li> <% if devise_mapping.rememberable? -%> <li> <%= f.check_box :remember_me %> <%= f.label :remember_me %> </li> <% end %> <li> <%= f.submit " Sign in " %> </li> </ol> <% end %> <%= render :fractional => " devise/shared/links " %>
The signup form volition likewise demand to be modified and we'll have to add validation to the User
model attribute but we won't show that hither.
Once we've restarted the server so that the configuration changes are picked up we can visit the signin page and login with a username instead of and electronic mail address.
That's information technology for this episode on customizing devise. Devise is a great solution for hallmark in Rail applications with a skilful set of default options simply with the flexibility to exist customized almost however you want it.
Login Form Not Showing Devise Errors, but Registration Is
DOWNLOAD HERE
Source: http://railscasts.com/episodes/210-customizing-devise?view=asciicast
Posted by: lopezligive.blogspot.com
0 Response to "Login Form Not Showing Devise Errors, but Registration Is Updated FREE"
Post a Comment