Posts tagged as:

authentication

I’ve been working on several applications where I’ve needed not only to verify that someone was logged in, but actually make sure that someone had permission to modify a particular object. There are several authentication solutions out there. I’ve actually listed 9 of them in this post.

I’m going to add one that I’ve picked up lately. It’s called Devise. I’m actually really enjoying it and liking a lot of the options that it offers. I still haven’t figured it all out, but it extends your rails application and manages your sign up, sign in, and sign off functionality. I’ll probably put up a screencast on it soon. So, stay posted.

The part that I’m really excited about, though, is CanCan. I’ve built complicated permissions systems before. Some were role based, others permissions based (possibly containing roles). I would place the role and permission checks into the controllers and manage the rights the user exercised that way. The problem was that I found myself repeating a LOT of code.

That’s what I like about CanCan. It provides a before filter for your controllers that saves you all of that code. The best thing about that is that your permissions are all defined in one place (/app/models/ability.rb) so if you need to give someone access to a particular resource in your application, you just set it up there and it’s propagated to the rest of your application. Trust Ryan Bates to come up with something simple and awesome like that.

{ 0 comments }

Twitter just turned off Basic Auth and is forcing application developer to use OAuth. Here is a demonstration of how to add Twitter OAuth to your Ruby on Rails Application.

Download 90.9 MB
Download (iPod & iPhone) 45.6 MB

{ 24 comments }

Joe is one of the talented developers at Thoughtbot in Boston, MA.

Joe is a maintainer for the shoulda gem. Here’s a video on how to use shoulda.

Some of the gems we talked about are:

Thoughtbot is responsible for HopToad.

Joe also mentioned that Thoughtbot uses Pivotal Tracker and most developers use VIM. His VIM config files are here.

Here’s the article on Team Rotation.

Download this Episode

{ 1 comment }

I just read the article by Pratik Naik from the Rails Core Team regarding Rails Templates.

Have you ever wished you could start out your Rails application with all of your gems installed and all of your standard setup items completed? Well, wait no longer. You can now do it with Rails Templates. Pratik covered it pretty well, so I’m not going to repeat what he’s done. Rather, I’m going to share a template of my own and explain why I included what I did.

[click to continue…]

{ 1 comment }

One problem that seems to face people when they’re attempting to move their applications into production is the best way to manage deployment of their application. This is where tools like capistrano comes in.

Capistrano was written by Jamis Buck of 37signals. In a lot of ways it has become the defacto way to deploy Ruby on Rails applications. It has also had tools like webistrano build on top of it to provide a graphical interface to the command line tool.

To get started, you need to install the capistrano gem:

gem install capistrano

[click to continue…]

{ 6 comments }


In this screencast, I show you how to use the Twitter gem to connect to Twitter, and we clarify some of the difficulties that comes with learning OAuth.
Download 67 MB
Download (iphone & ipod) 23.6 MB

{ 20 comments }


In this series, I attempt to recreate a twitter style application called ‘Flitter’. In this installment, I show you how to create an authenticated system easily using existing tools. I also show how to generate test data to simulate an active application. Finally, you will learn how to set up self-referencial associations.
Download 280 MB
Download (iphone & ipod) 86 MB

{ 19 comments }

While looking at articles and resources about authentication in Ruby on Rails I ran across a set of generators written by Ryan Bates of Railscasts. You can find the nifty generators at http://github.com/ryanb/nifty-generators/tree/master

I ran the generators and have posted the resulting code at http://github.com/charlesmaxwood/nifty/tree/master.

[click to continue…]

{ 5 comments }

Last week, I wrote a post listing 9 ways to use rails metal. This is an explanation of the first way to use Rails Metal: Check Authentication.

We’re setting up this Rails Metal to handle two scenarios: requiring authentication, and logging the user in. First, it verifies that requests to any path beginning with /admin have a user logged in by checking that a valid user id is stored in the session. Second, accepts an HTTP POST to /authenticate with a username, password, and target path for redirect upon

Before we get too deep into things, let me share the code. You can check out a working version of the application on GitHub.

Here’s the Metal.

require(File.dirname(__FILE__) + "/../../config/environment") unless defined?(Rails)

class Authentication
  def self.call(env)
    session = env["rack.session"]
    request = Rack::Request.new(env)
    params = req.params
    if env["PATH_INFO"] =~ /^/admin.*/ && (session["user_id"].nil? || (session["user_id"] && User.connection.select_all("SELECT * FROM users WHERE id = #{session["user_id"]}").empty?))
      [302, {"Content-Type" => "text/html", "Location" => "/login?target_path=#{env["REQUEST_URI"]}"}, ["You must be logged in to view this page. You are being redirected."]]
    elsif env["REQUEST_METHOD"] == "POST" && env["PATH_INFO"] =~ /^/authenticate/
      users = User.connection.select_all("SELECT * FROM users WHERE username='#{params["user"]["username"]}' AND password='#{params["user"]["password"]}'")
      unless users.empty?
        session["user_id"] = users.first["id"]
        [302, {"Content-Type" => "text/html", "Location" => "#{params["target_path"] || "/"}"}, ["You have been logged in. You are being redirected."]]
      else
        [302, {"Content-Type" => "text/html", "Location" => "/login"}, ["Authentication failed. You are being redirected."]]
      end
    else
      [404, {"Content-Type" => "text/html"}, ["Not Found"]]
    end
  end
end

Bases for Understanding the Code

There are a few methods and structures here that are important to note in how this all works.

First, the self.call(env) is the entry point for the Rails Metal application. env refers to the Rack environment.

Next, Rack::Request is a class that provides a convenient interface to the Rack environment. In this case, we’re using it to extract the GET and POST parameters from the request. You can see the full Rack::Request API here.

env[‘rack.session’] returns the session as a hash. In this case, keys are accessed as strings, not symbols. So, in our case, session[:user_id] won’t work, but session[“user_id”] will work.

Finally, we do direct SQL calls through the ActiveRecord object rather than using the find method because it’s faster and we only need a few fields like the id of the user that’s found.

Overview of the Code

Checking Authentication

Our authentication code creates a session variable called user_id and places the current user’s id into it. So, to make sure someone is logged in, we need to make sure that a valid user id is in the session.

To do this we check if the path begins with /admin. env[“PATH_INFO”] contains the path without any GET parameters. So, we do a regular expression match and them move on to checking if there’s a valid user id in the session.

There are two scenarios that we need to check. There is no user id stored in the session and the user id stored is not the id of a valid user.

If both conditions are met, we redirect the user to /login and pass along the path the user was trying to access as a GET parameter called “target_path.”

Logging the user in

If a valid username and password are passed to the path /authenticate, we need to store the user’s id in the session and redirect them to where they were trying to go. To check the username and password, we query the database. If no matches are found in the database, then we send them to the login page.

Overall the code is pretty simple. Feel free to use it in any of your applications. I’ll post the benchmarks when I get a chance, but several people were looking for this content, so I’m putting it out now.

{ 7 comments }

I wrote a quick overview of Rails Metal earlier and started thinking that it would be nice to provide some examples of how you could use it in your Rails application. Here are 9 ways I thought of off the top of my head.

I’ll provide a quick explanation of each one and then post the code as I get each one done.

1. Authentication checking

Many sites have two parts to them. The administrative side—which is protected by an authentication system—and the public side—which anyone can access. If a user must be logged in to access the admin/authenticated part of the site, then why not take advantage of the performance boost Rails Metal gives you and redirect before the Rails even gets loaded.

UPDATE: I just posted the an explanation of how to do Rails Metal Authentication.

2. OpenID checking

Similar to the Authentication checking, you can do a quick check of the user’s authentication status with their OpenID and let them through if they are already authenticated. It’s kind of like a convenient before_filter call on that section of your website.

3. Simple API’s

API’s are extremely simple to implement with Rails Metal. If you have a convenient method on the Model to convert a given instance into the format the API user expects—to_json for example—then you could simply provide a success response with the converted object as the response text.

UPDATE: I just posted the code and explanation on how to do API’s in Rails Metal.

4. Redirecting Affiliate Links

Have you ever built a site that made money from advertising and wished you could send people to http://mydomain.com/hosting for your hosting affiliate? This would be one of the simplest uses of Rails Metal. Check the path and redirect.

UPDATE: I just posted the an explanation of how to do Rails Metal Redirects.

5. Serving Static Content

If you have pages or some other type of content that doesn’t change from one page load to the next and you don’t need the nice templating magic that the Ruby on Rails layouts give you, then this solution is for you. It allows you to make these pages database driven.

UPDATE: I just posted the an explanation of how to serve Static Content and Pages using Rails Metal.

6. Serving Downloads

Regardless of whether the file you’re serving is a file in the filesystem, or has its data stored in the database, all you really need is the file’s mime-type and its content. Then you give a success response with the content type set in the header and the file content in the response text.

7. Tracking Analytics

Rails Metal was designed to be a possible endpoint for your application, meaning that it returns a response and stops execution. However, you can perform some function and then pass the execution on to the remainder of your application. So storing visits to certain paths is a cinch with Rails Metal.

8. Serving Cached Content

Are you caching your content to memcached or the filesystem? For memcached, loading cached content is as easy as loading the memcached client gem and accessing memcached with they key. The rest is caching on the part of your rails application.

9. Triggering Server Side Events (Jobs and Rake Tasks)

Have you ever thought it would be convenient to hit a particular URL and have it kick off a process on your server? Obviously you’d have to secure it, but we can do that with another Rails Metal that checks authentication. (See #1 and #2.)

If you have any other uses that you’re putting Rails Metal to, let us all know in the comments below.

{ 7 comments }