Forum: Ruby on Rails super simple authentication fail.

D974b374bd09edcef9285ff7c4f59ea5?d=identicon&s=25 Bigmac Turdsplash (i8igmac)
on 2016-11-10 16:35
http://railscasts.com/episodes/21-super-simple-aut...

im trying to create a login page, i would like all traffic to be
directed to this login...

sessions/new.html.erb  <---login form
sessions/home.html.erb
sessions/index.html.erb
sessions/console.html.erb

i hope to restrict access to these 3 documents... currently the simple
hello world example for these 3 documents will work just fine...



[code]
rails g controllers sessions home index console new create destroy

[controller/sessions/application_controller.rb]
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
#  session :session_key => '_railscasts_session_id'

  helper_method :admin?
  protected

  def authorize
    unless admin?
      flash[:notice] = "Unauthorized access"
      redirect_to home_path
      false
    end
  end

  def admin?
    session[:password] == "secret"
  end


end




[controller/sessions/sessions_controller.rb]
class SessionsController < ApplicationController
  def new
  end

  def home
  end

  def index
  end

  def console
  end

  def create
    session[:password] = params[:password]
    flash[:notice] = "Successfully logged in"
    redirect_to home_path
  end

  def destroy
    reset_session
    flash[:notice] = "Successfully logged out"
    redirect_to login_path
  end
end







[view/sessions/new.html.erb]
<h1>new.html.erb</h1>
<div class="content">
<p>
<%= form_tag sessions_path do %>
  Password: <%= password_field_tag :password %>
  <%= submit_tag "Login" %>
<% end %>
</p>
</div>






[config/routes.rb]
Rails.application.routes.draw do
  get 'sessions/new'
  get 'sessions/index'
  get 'sessions/home'
  get 'sessions/console'
  get 'sessions/create'
  get 'sessions/destroy'

  resources :controller, :sessions
  resources '', :controller => 'sessions', :action => 'new'
  root '', :controller => 'sessions', :action => 'new'
  get 'login', :controller => 'sessions', :action => 'create'
  get 'logout', :controller => 'sessions', :action => 'destroy'
  # For details on the DSL available within this file, see
http://guides.rubyonrails.org/routing.html
end
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.