devroom.io/drafts/2007-08-24-super-simple-authentication-plugin-and-generator.md

42 lines
2.6 KiB
Markdown
Raw Normal View History

2013-03-22 22:53:57 +00:00
---
title: "Super Simple Authentication Plugin and Generator"
kind: article
slug: super-simple-authentication-plugin-and-generator
created_at: 2007-08-24
tags:
- General
- RubyOnRails
- Features
---
I hereby proudly announce my <em>Super Simple Authentication</em> plugin and generator.
All right, what does it do? Sometimes you need to protect your actions and controllers, but you don't want to go about installing restful_authentication or anything like that. Adding a simple password for certain actions would suffice. So, I wrote a little plugin that can generate some code for you that allows you to easily protect your app with a simple password.
To get started, you must first install the plugin in your rails application:
<pre lang="bash">script/plugin install http://svn.ariejan.net/plugins/super_simple_authentication</pre>
When the plugin is installed, you may generate your SSA controller. This controller verifies your password and makes sure you stay authenticated for the duration of your visit.
<pre lang="bash">script/generate super_simple_authentication sessions</pre>
Your password is located in config/super_simple_authentication.yml. Change it.
In the SessionsController, you'll find an include statement. Move this include to your application controller:
<pre lang="ruby">include SuperSimpleAuthenticationSystem</pre>
The generator automatically added routes to your config/routes.rb file. If you want easy access to login and logout functionality, add these two lines to your config/routes.rb file as well:
<pre lang="ruby">map.login '/login', :controller => 'sessions', :action => 'new'
map.logout '/logout', :controller => 'sessions', :action => 'destroy', :method => :delete</pre>
You can now protect you actions and controllers with a before_filter:
<pre lang="ruby"># Protect all actions in the controller
before_filter :authorization_required
# Protect all actions, except :index and :recent
before_filter :authorization_required, :except => [:index, :recent]
# Protect only :destroy
before_filter :authorization_required, :only => :destroy</pre>
In your views, you can check if you are authorized or not with authorized? E.g.
<pre lang="html"><% if authorized? %>
# ... do secret admin stuff
<% end %></pre>
Please visit <a href="http://trac.ariejan.net">http://trac.ariejan.net</a> to report bugs. Ariejan.net will keep you updated on new major version. <a href="http://feeds.feedburner.com/Ariejan">Please subscribe to the RSS Feed</a>.
I hope you enjoy this plugin. Please post a comment if you use it in your project, or if you just like it. Bugs, feature requests and support requests should go into <a href="http://trac.ariejan.net/newticket">Trac</a>