To Examples

BlogPostSite2 Example

  1. Create a Rails scaffold-based project named BlogPostSite2. If you are adding login authentication to a project with more than one controller in your project, repeat steps 2 to 6 for each controller that contains pages needing password authentication.
  2. Generate a Rails scaffold-based project with model name Blog defined by
    Field Datetype
    screen_name string
    message text
  3. Create a model named User that contains the usernames and their passwords. (Don't forget rake db:migrate.)
     
    Field Datetype
    username string
    password string
  4. Populate the users table with user names and encrypted passwords by inserting statements similar to the Ruby seed file statements in db/seeds.rb. Run the seed file with rake db:seed.
  5. Add this line at the very top of the controller:
    require 'digest/md5'
    
  6. Suppose that the new and edit views need password authentication. Add this line to the top of the controller immediately before the index method:
    before_filter :authenticate, except: [:index, :show]
    
  7. Add this code to the end of the controller immediately before the final end statement:
    private
      def authenticate
        authenticate_or_request_with_http_digest("localhost") do |username|
          if user = User.find_by_username(username)
            user.password
          else
            nil
          end
        end
      end
    
    localhost is the realm, which is usually the name of the server.
  8. When the user tries to view the new or edit views that require password authentication, a password dialog will appear, asking for the username and password. The user will stay logged in until all browser windows on your machine are closed.