· 2 min read

Screencast: Authentifizierung mit sorcery

Downloads in verschiedenen Formaten:

mp4 mp4 webm ogg

Resourcen:

bash

[bash] bundle rake sorcery:bootstrap rails g sorcery_migration core remember_me rails g model user —skip-migration rake db:migrate rails g controller users new rails g controller sessions new [/bash]

Gemfile

[ruby] gem ‘sorcery’ [/ruby]

config/initializers/sorcery.rb

[ruby] Rails.application.config.sorcery.submodules = [:remember_me]

# …

user.username_attribute_name = :email [/ruby]

models/user.rb

[ruby] class User < ActiveRecord::Base authenticates_with_sorcery! attr_accessible :email, :password, :password_confirmation

validates_confirmation_of :password validates_presence_of :password, :on => :create validates_presence_of :email validates_uniqueness_of :email end [/ruby]

users_controller.rb

[ruby] 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 [/ruby]

views/users/new.html.erb

[html] <%= form_for @user do |f| %> <% if @user.errors.any? %>

Form is invalid

    <% for message in @user.errors.full_messages %>
  • <%= message %>
  • <% end %>
<% end %>
<%= f.label :email %> <%= f.text_field :email %>
<%= f.label :password %> <%= f.password_field :password %>
<%= f.label :password_confirmation %> <%= f.password_field :password_confirmation %>
<%= f.submit %>
<% end %> [/html]

sessions_controller.rb

[ruby] def create user = login(params[:email], params[:password], params[:remember_me]) if user redirect_back_or_to root_url, :notice => “Logged in!” else flash.now.alert = “Email or password was invalid” render :new end end

def destroy logout redirect_to root_url, :notice => “Logged out!” end [/ruby]

views/sessions/new.html.erb

[html] <%= form_tag sessions_path do %>

<%= label_tag :email %> <%= text_field_tag :email, params[:email] %>
<%= label_tag :password %> <%= password_field_tag :password %>
<%= check_box_tag :remember_me, 1, params[:remember_me] %> <%= label_tag :remember_me %>
<%= submit_tag “Log in” %>
<% end %> [/html]

config/routes.rb

[ruby] get “logout” => “sessions#destroy”, :as => “logout” get “login” => “sessions#new”, :as => “login” get “signup” => “users#new”, :as => “signup” resources :users resources :sessions [/ruby]

home_controller.rb

[ruby] before_filter :require_login, :only => :secret [/ruby]

application_controller.rb

[ruby] def not_authenticated redirect_to login_url, :alert => “First login to access this page.” end [/ruby]

application.html.erb

[html] <% if current_user %> Logged in as <%= current_user.email %>. <%= link_to “Log out”, logout_path %> <% else %> <%= link_to “Sign up”, signup_path %> or <%= link_to “log in”, login_path %>. <% end %> [/html]

Back to Blog