· 2 min read
Screencast: Authentifizierung
Download:
Download(22.6 MB, 15:26) Alternativer Download für iPod & Apple TV(22.3 MB, 15:26)
Resourcen:
Quellcode:
[bash] rails g controller users new rails g model user email:string password_hash:string password_salt:string rake db:migrate rails dbconsole rails g controller sessions new [/bash]
[ruby] # Gemfile gem “bcrypt-ruby”, :require => “bcrypt”
# models/user.rb class User < ActiveRecord::Base attr_accessible :email, :password, :password_confirmation attr_accessor :password before_save :encrypt_password validates_confirmation_of :password validates_presence_of :password, :on => :create validates_presence_of :email validates_uniqueness_of :email def self.authenticate(email, password) user = find_by_email(email) if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt) user else nil end end def encrypt_password if password.present? self.password_salt = BCrypt::Engine.generate_salt self.password_hash = BCrypt::Engine.hash_secret(password, password_salt) end end end
# users_controller.rb def new @user = User.new end
def create @user = User.new(params[:user]) if @user.save redirect_to root_url, :notice => “Signed up!” else render “new” end end
# sessions_controller.rb def new end
def create user = User.authenticate(params[:email], params[:password]) if user session[:user_id] = user.id redirect_to root_url, :notice => “Logged in!” else flash.now.alert = “Invalid email or password” render “new” end end
def destroy session[:user_id] = nil redirect_to root_url, :notice => “Logged out!” end
# application_controller.rb helper_method :current_user
private
def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end
# routes.rb get “log_out” => “sessions#destroy”, :as => “log_out” get “log_in” => “sessions#new”, :as => “log_in” get “sign_up” => “users#new”, :as => “sign_up” root :to => “users#new” resources :users resources :sessions [/ruby]
[html]
Sign Up
<%= form_for @user do |f| %> <% if @user.errors.any? %>
<% end %><%= f.label :email %>
<%= f.text_field :email %>
<%= f.label :password %>
<%= f.password_field :password %>
<%= f.label :password_confirmation %>
<%= f.password_field :password_confirmation %>
Log in
<%= form_tag sessions_path do %>
<%= label_tag :email %>
<%= text_field_tag :email, params[:email] %>
<%= label_tag :password %>
<%= password_field_tag :password %>
<% flash.each do |name, msg| %> <%= content_tag :div, msg, :id => “flash_#{name}” %> <% end %> [/html]