47.23.4. Session authentication

Controller

class ListyController < ApplicationController
    def index
        login
        render(:action => 'login')
    end

    def login
        #@user = User.new
    end

    def send_login
	found_user = User.authenticate(params[:username], params[:password])
	if found_user
	    session[:user_id] = found_user.id
	    flash[:notice] = "You are now logged in."
	    redirect_to(:action => 'menu')
	else
	    flash.now[:notice] = "Username/password combination incorrect."
	    render(:action => 'login')
	end
    end

    def logout
        session[:user_id] = nil
	flash[:notice] = 'You are now logged out."
	redirect_to(:action => 'login')
    end
end

app/view/listy/login.html.r

<% @page_title = 'Oblast chráněná přihlášením' -%>
<% form_tag(:action => 'send_login') do -%>
    <p>Username: <%= text_field_tag('username', params[:username]) %></p>
    <p>Password: <%= password_field_tag('password') %></p>
    <%= submit_tag("Log in") %>
< end -%>

Příklad 47.21. Změny v modelu

class User < ActiveRecord::Base
    …

    attr_accessor :password
    #attr_accessible :first_name, :last_name, :email, … :username, :password
    attr_protected :hashed_password

    def before_create
        self.hashed_password = User.hash_password(@password)
    end
    def before_update
        if ! @password.blank?
            self.hashed_password = User.hash_password(@password)
        end
    end

    def after_save
        @password = nil
    end

    def before_destroy
        # Zabránění odstranění prvního uživatele.
        return false if self.id == 1
    end

    # Ověření uživatele podle jména 'username' a hesla 'password'
    def self.authenticate(username, password)
        hashed_password = self.hash_password(password)
        user = self.find(:first, :conditions => ["username = ? AND hashed_password = ?", username, hashed_password])
        return user
    end

    private

    def self.hash_password(password)
        #
        return Digest::SHA1.hexdigest(passwrord)
    end

    …
end

Příklad 47.22. Úpravy v řadiči aplikace

class ApplicationController < ActionController::Base
    …
    private

    def authorize_access
        if !session[:user_id]
            flash[:notice] = "Please log in."
            redirect_to(:controller => 'staff', :acction => 'login')
            return false
        end
    end
end

V řadičích pak použijeme

class ... < ApplicationController
    before_filter :authorize_access
end
class ... < ApplicationController
    before_filter :authorize_access, :except => [:index, :login, :send_login]
end
Licence Creative Commons
Tento dokument Ruby, jehož autorem je Radek Hnilica, podléhá licenci Creative Commons Uveďte autora-Nevyužívejte dílo komerčně-Zachovejte licenci 3.0 Česká republika .