<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Vision Master Designs &#187; Login System</title>
	<atom:link href="http://visionmasterdesigns.com/tag/login-system/feed/" rel="self" type="application/rss+xml" />
	<link>http://visionmasterdesigns.com</link>
	<description>Just another WordPress weblog</description>
	<lastBuildDate>Mon, 02 Aug 2010 12:09:29 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Tutorial : Create a login system in Ruby on Rails</title>
		<link>http://visionmasterdesigns.com/tutorial-create-a-login-system-in-ruby-on-rails/</link>
		<comments>http://visionmasterdesigns.com/tutorial-create-a-login-system-in-ruby-on-rails/#comments</comments>
		<pubDate>Thu, 11 Sep 2008 11:10:57 +0000</pubDate>
		<dc:creator>Michael</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[Web Programming]]></category>
		<category><![CDATA[blog]]></category>
		<category><![CDATA[Login System]]></category>

		<guid isPermaLink="false">http://www.visionmasterdesigns.com/?p=597</guid>
		<description><![CDATA[Hello everyone, In today&#8217;s tutorial I`ll teach you how to create a very basic Login System in Ruby on Rails. Welcome to Tutorial : Create a login system in Ruby on Rails. Before proceeding I would suggest you guys to read Tutorial : Create a blog using Ruby on Rails 2. (Part 1 &#8211; Relationships) [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin: 0 0 0.6em 0.6em;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fvisionmasterdesigns.com%2Ftutorial-create-a-login-system-in-ruby-on-rails%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fvisionmasterdesigns.com%2Ftutorial-create-a-login-system-in-ruby-on-rails%2F&amp;source=rowoot&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>Hello everyone,<br />
In today&#8217;s tutorial I`ll teach you how to create a very basic Login System in <strong>Ruby on Rails</strong>. Welcome to <strong>Tutorial : Create a login system in Ruby on Rails</strong>. Before proceeding I would suggest you guys to read <a href="http://www.visionmasterdesigns.com/2008/08/tutorial-create-blog-using-ruby-on-rails-2-relationship/">Tutorial : Create a blog using Ruby on Rails 2. (Part 1 &#8211; Relationships)</a> since we will be using this sytem in our application.</p>
<h2>Introduction</h2>
<p>We will create a very simple standalone login system first, It will check the database for valid users. Then I`ll let you know how to integrate a similar login system in our blog application. First of course the basics.</p>
<p>We would need to design
<ul>
<li>Login page</li>
<li>A page which would have to be protected by the login system</li>
<li>Function to Check session, if not valid, then redirect to login page.</li>
</ul>
<p>Demo of the Login System in RoR : <a href="http://visionmasterdesigns.com:12001/user/login">Click Here</a> (user:admin,pass:admin)</p>
<p><span id="more-597"></span></p>
<h4>Step 1 : Create &#8216;logintest&#8217; Rails app</h4>
<p>Ok, Fire up the command prompt window, Lets create our Rails application called &#8216;<strong>logintest</strong>&#8216;.</p>
<pre lang="cmd">C:\railsappz>rails logintest -d mysql</pre>
<p>After creating the Rails application, you`ll notice a new directory called logintest being created. Navigate inside.</p>
<h4>Step 2 : Modify the &#8216;database.yml&#8217; &#038; Create Tables</h4>
<p>Since, our authentication system is going to check the backend for valid users, we need to tell it which database to refer, for the same you need to modify the <strong>database.yml</strong> file. By now, you must have known this procedure, but for those guys who don`t know how to, here is a lowdown. Navigate to <span class="code">C:\railsappz\login\config</span>, inside it you`ll find <strong>database.yml</strong></p>
<p>Open it, then modify the code inside. Please put a valid database name, a valid username and password (mysql). If you want to know how to create databases using phpMyAdmin, read here <a href="http://www.visionmasterdesigns.com/2008/07/tutorial-using-phpmyadmin-to-manage-mysql/">Tutorial : Using phpMyAdmin to manage mySQL</a></p>
<p>Secondly, we need to create the &#8216;User&#8217; Table. This table already has some user information.</p>
<pre class="brush: sql">
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL auto_increment,
  `user_name` varchar(255) default NULL,
  `password` varchar(255) default NULL,
  `role` int(11) default NULL,
  `created_at` datetime default NULL,
  `updated_at` datetime default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

INSERT INTO `users` (`id`, `user_name`, `password`, `role`, `created_at`, `updated_at`) VALUES
(1, &#039;admin&#039;, &#039;admin&#039;, 0, NULL, NULL),
(2, &#039;test&#039;, &#039;test&#039;, 1, NULL, NULL);
</pre>
<p>These are the 2 entries we have entered in our User Table.</p>
<ol>
<li>
Username : admin<br />
Password : admin
</li>
<li>
Username : test<br />
password : test
</li>
</ol>
<p>The following is how MY database.yml looks.</p>
<pre class="brush: ruby">
development:
  adapter: mysql
  encoding: utf8
  database: login
  username: root
  password: root
  host: localhost

test:
  adapter: mysql
  encoding: utf8
  database: login
  username: root
  password: root
  host: localhost

production:
  adapter: mysql
  encoding: utf8
  database: login
  username: root
  password: root
  host: localhost
</pre>
<h4>Step 3 : Generate the &#8216;User&#8217; Model</h4>
<p>Creating a model is very important, because for any querying to the database, we need to use a object of this model, similarly to import the form values (login form), we will be using the object of User model.</p>
<p>So we need to tell our app about this mode. Since we are not using database, we`ll skip the database files that normally get created, while creating a model. We`ll use the <strong>&#8211;skip-migrations</strong> option.</p>
<pre lang="cmd">C:\railsappz\login>ruby script/generate model user --skip-migrations</pre>
<p>Lets move on to creating the User Controller.</p>
<h4>Step 4 : Generate the &#8216;User&#8217; Controller</h4>
<p>Now lets create our User Controller. Before creating, Lets do a check on what all we would require, cuz accordingly we have to create our controller.</p>
<ol>
<li>Login Page</li>
<li>Private Page</li>
</ol>
<p>So Our controller file will have the <strong>login page</strong>, <strong>private page</strong>.</p>
<pre lang="cmd">C:\railsappz\login>ruby script/generate controller user login private</pre>
<pre lang="cmd">
      exists  app/controllers/
      exists  app/helpers/
      create  app/views/user
      exists  test/functional/
      create  app/controllers/user_controller.rb
      create  test/functional/user_controller_test.rb
      create  app/helpers/user_helper.rb
      create  app/views/user/login.html.erb
      create  app/views/user/private.html.erb
</pre>
<p>If you noticed, you`ll see that whatever parameters we specified, view files with the same name are created, i.e login.html.erb, private.html.erb. Basically</p>
<p>Lets decipher the above code,</p>
<p><strong>User &#8211; Controller Name</strong><br />
Parameters :</p>
<ul>
<li><span class="code">login</span> &#8211; Creates a empty function inside <span class="code">user_controller.rb</span> and also creates a view file called <span class="code">login.html.erb</span> which will contain our Login Form.
</li>
<li>
<span class="code">private</span> &#8211; Creates a empty function inside <span class="code">user_controller.rb</span> and also creates a view file called <span class="code">private.html.erb</span> which will contain the content to be protected using our login system.
</li>
</ul>
<h4>Step 5 : Edit the Views, viz: login.html.erb, private.html.erb</h4>
<p>Navigate to C:\railsappz\login\app\views\user, open up <strong>login.html.erb</strong>. Time to create our form. We will be using the ruby helpers.</p>
<pre class="brush: ruby">
&lt;% if flash[:notice] %&gt;
&lt;div style=&quot;font-family:&#039;Trebuchet MS&#039;; color:#FF0000; font-size:14px;&quot;&gt;
&lt;%= flash[:notice] %&gt;
&lt;/div&gt;
&lt;% end %&gt;

&lt;!--creates form, exectues the authenticate method when the submit button is clicked--&gt;
&lt;%= form_tag :action=&gt;&#039;authenticate&#039; %&gt;
User name:
&lt;%= text_field(&quot;userform&quot;, &quot;user_name&quot;,:size=&gt;&quot;20&quot; ) %&gt;
Password:
&lt;%= password_field(&quot;userform&quot;, &quot;password&quot;,:size=&gt;&quot;20&quot; )
%&gt;
&lt;input type=&quot;submit&quot; value=&quot; LOGIN &quot; /&gt;
</pre>
<p>Save the file, now open up <strong>private.html.erb</strong>. This will be our protected page. If someone tries to view this page directly he should be redirected to the login page. Only valid users should be able to see this page.</p>
<pre class="brush: ruby">
&lt;!--#displays hello (username)--&gt;
hello &lt;strong&gt;&lt;%=session[:user_id]%&gt;&lt;/strong&gt;.

&lt;!--#creates logout link, when the link is clicked, the controller is User and the method executed will be logout.--&gt;
&lt;%= link_to &quot;logout&quot;,:controller =&gt; &quot;user&quot;, :action =&gt; &quot;logout&quot; %&gt;
</pre>
<p>Ok, Now we have defined our view files and used some methods inside them, now its time to define these methods. All methods go inside the controller.</p>
<h4>Step 6 : Edit the user_controller.rb</h4>
<p>Navigate <span class="code">C:\railsappz\login\app\controllers</span> and open <strong>user_controller.rb</strong>. You will notice 2 empty methods viz login, private. Let them be the way they are for now, We will be creating 2 methods, first lets create a method to handle our authentication viz <strong>authenticate</strong>.</p>
<pre class="brush: ruby">
def authenticate
		#User.new(params[:userform]) will create a new object of User, retrieve values from the form and store it variable @user.
		@user = User.new(params[:userform])
        #find records with username,password
		valid_user = User.find(:first,:conditions =&gt; [&quot;user_name = ? and password = ?&quot;,@user.user_name, @user.password])

        #if statement checks whether valid_user exists or not
		if valid_user
        #creates a session with username
			session[:user_id]=valid_user.user_name
        #redirects the user to our private page.
			redirect_to :action =&gt; &#039;private&#039;
		else
			flash[:notice] = &quot;Invalid User/Password&quot;
			redirect_to :action=&gt; &#039;login&#039;
		end
end
</pre>
<p>Second method is for to handle the logout. When the logout link will be clicked, this method will be called. As you can see, we will reset the session created during authenticate method and redirect the user to the login page again.</p>
<pre class="brush: ruby">
  def logout
	  if session[:user_id]
		  reset_session
		  redirect_to :action=&gt; &#039;login&#039;
	  end
  end
</pre>
<p>Now to test the server. Run <span class="code">ruby script/server</span>. You will see the usual Riding on Rails Page.<br />
Point your browser to <a href="http://myserver.dev:3000/user/login">http://myserver.dev:3000/user/login</a> to see the login page. </p>
<p>If you have followed all the steps properly, you`ll see that the login system is working fine, except for a lil important modifications.</p>
<p>First logout, then Try pointing your browser to <a href="http://myserver.dev:3000/user/private">http://myserver.dev:3000/user/private</a>, you`ll notice that you are able to view the private page !!!<br />
Lets rectify this problem</p>
<h4>Step 7 : Modify the private method in user_controller.rb</h4>
<p>Since we just have to protect one page, we can simply use an if statement to check the session and respectively allow or disallow them to view the private page. Remember we had created a private method in user_controller.rb (Our User Controller). So your new private method will look like the following</p>
<pre class="brush: ruby">
  def private
 	 if !session[:user_id]
    	redirect_to :action=&gt; &#039;login&#039;
	end
  end
</pre>
<p>Voila ! We have secured our private page. Finally</p>
<p>This is how your final <strong>User_controller.rb</strong> should look</p>
<pre class="brush: ruby">
class UserController &lt; ApplicationController
def authenticate
		#User.new(params[:userform]) will create a new object of User, retrieve values from the form and store it variable @user.
		@user = User.new(params[:userform])
        #find records with username,password
		valid_user = User.find(:first,:conditions =&gt; [&quot;user_name = ? and password = ?&quot;,@user.user_name, @user.password])

        #if statement checks whether valid_user exists or not
		if valid_user
        #creates a session with username
			session[:user_id]=valid_user.user_name
        #redirects the user to our private page.
			redirect_to :action =&gt; &#039;private&#039;
		else
			flash[:notice] = &quot;Invalid User/Password&quot;
			redirect_to :action=&gt; &#039;login&#039;
		end
end

  def login
  end

  def private
  if !session[:user_id]
	redirect_to :action=&gt; &#039;login&#039;
	end
  end

  def logout
	  if session[:user_id]
		  reset_session
		  redirect_to :action=&gt; &#039;login&#039;
	  end
  end

end
</pre>
<p>Now to test the server again, Re-Run <span class="code">ruby script/server</span>.<br />
Try pointing your browser to <a href="http://myserver.dev:3000/user/private">http://myserver.dev:3000/user/private</a>, you will see that you will be redirected to the login page (if you previously logged out, else if the session is still valid, you`ll see the private page).</p>
<p>Phew&#8230;  Well thats about how to design the Login System in Ruby on Rails. If you guys have any problems, as usual you can always post a comment here. I`ll be posting another post on how to integrate this login system in our blog application.</p>
<p>Demo of the Login System in RoR : <a href="http://visionmasterdesigns.com:12001/user/login">Click Here</a> (user:admin,pass:admin)</p>
<h2>Related Links</h2>
<p><a href="http://www.visionmasterdesigns.com/2008/08/tutorial-create-blog-using-ruby-on-rails-2-relationship/">Tutorial : Create a blog using Ruby on Rails 2. (Part 1 &#8211; Relationships)</a><br />
<a href="http://www.visionmasterdesigns.com/2008/08/tutorial-basics-ruby-on-rails-2-model-controller-view-routing/">Tutorial : Basics on Ruby on Rails 2 Model, Controller and Views and Routing</a><br />
<a href="http://www.visionmasterdesigns.com/2008/07/tutorial-developing-your-first-ruby-on-rails-2-application/">Tutorial : Developing your First Ruby on Rails 2 Application</a><br />
<a href="http://www.visionmasterdesigns.com/2008/07/tutorial-installing-ruby-on-rails-2-in-windows-vista-xp/">Tutorial : Installing Ruby on Rails 2 in Windows Vista/XP</a></p>
<div class="donate"><strong>Buy me a beer.</strong></p>
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_donations">
<input type="hidden" name="business" value="rowoot@gmail.com">
<input type="hidden" name="item_name" value="MICHEAL BENEDICT ARUL">
<input type="hidden" name="no_shipping" value="0">
<input type="hidden" name="no_note" value="1">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="tax" value="0">
<input type="hidden" name="lc" value="IN">
<input type="hidden" name="bn" value="PP-DonationsBF">
<input type="image" src="https://www.paypal.com/en_US/i/btn/btn_donate_SM.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1"><br />
</form>
</div>
]]></content:encoded>
			<wfw:commentRss>http://visionmasterdesigns.com/tutorial-create-a-login-system-in-ruby-on-rails/feed/</wfw:commentRss>
		<slash:comments>33</slash:comments>
		</item>
	</channel>
</rss>
