Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ====================================
- model: user.rb
- ====================================
- require 'digest/sha1'
- class User < ActiveRecord::Base
- validates_presence_of :name
- validates_uniqueness_of :name
- attr_accessor :password_confirmation
- validates_confirmation_of :password
- def validate
- errors.add_to_base("Missing password") if hashed_password.blank?
- end
- def password
- @password
- end
- def password=(pwd)
- @password = pwd
- create_new_salt
- self.hashed_password = User.encrypted_password(self.password, self.salt)
- end
- def self.authenticate(name, password)
- user = self.find_by_name(name)
- if user
- expected_password = encrypted_password(password, user.salt)
- if user.hashed_password != expected_password
- user = nil
- end
- end
- user
- end
- private
- def self.encrypted_password(password, salt)
- string_to_hash = password + "wibble" + salt
- Digest::SHA1.hexdigest(string_to_hash)
- end
- def create_new_salt
- self.salt = self.object_id.to_s + rand.to_s
- end
- end
- ====================================
- controller: login_controller.rb
- ====================================
- class LoginController < ApplicationController
- def add_user
- @user = User.new(params[:user])
- if request.post? and @user.save
- flash.now[:notice] = 'User #{@user.name} created'
- @user = User.new
- end
- end
- def login
- session[:user_id] = nil
- if request.post?
- user = User.authenticate(params[:name], params[:password])
- if user
- session[:user_id] = user.id
- flash[:notice] = 'You have been logged in.'
- redirect_to :action => 'index'
- else
- flash[:notice] = 'Invalid user/password combination.'
- end
- end
- end
- def logout
- end
- def index
- end
- def delete_user
- end
- def list_users
- end
- end
- ====================================
- view: login.rhtml (note: this is the template for the action, not the layout for the controller, :D)
- ====================================
- <fieldset>
- <form>
- <label for="name">Name:</label><br/>
- <%= text_field_tag :name, params[:name] %><br/>
- <label for="password">Password:</label><br/>
- <%= password_field_tag :password, params[:password] %><br/>
- <%= submit_tag 'Login', :action => 'login', :method => 'post'%>
- </form>
- </fieldset>
- >>>>I loaded this one down, I added the the method first, and the action last... I'm not sure if I should have added either of them :D Anyway, I just got returned to the page each time... so yeah.
- ====================================
- Simple little index: index.rhtml
- ====================================
- <% if session[:user_id] %>
- <h3>You are logged in.</h3></br>
- <% user_name = User.find_by_id(session[:user_id]) %>
- In fact, you're logged in as <%= user_name.name %> .
- <% else %>
- <h3> You are not logged in. </h3>
- <h4> Either that or there's an error. :D</h4>
- <% end %>
Add Comment
Please, Sign In to add comment