· 2 min read
Screencast: Authentifizierung mit sorcery
Downloads in verschiedenen Formaten:
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? %>
<% end %>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 %>
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]