Refactored login module. Implemented standard sessions controller.

This commit is contained in:
benni 2011-05-11 13:38:46 +02:00
parent b1a700ab5d
commit e40f865c45
13 changed files with 89 additions and 332 deletions

View file

@ -1,12 +1,10 @@
class ApplicationController < ActionController::Base
filter_parameter_logging :password, :password_confirmation # do not log passwort parameters
protect_from_forgery
before_filter :select_foodcoop, :authenticate, :store_controller
after_filter :remove_controller
# sends a mail, when an error occurs
# see plugins/exception_notification
include ExceptionNotifiable
helper_method :current_user
# Returns the controller handling the current request.
def self.current
@ -25,46 +23,27 @@ class ApplicationController < ActionController::Base
protected
def current_user
begin
# check if there is a valid session and return the logged-in user (its object)
if session[:user] and session[:foodcoop]
if session[:user_id] and params[:foodcoop]
# for shared-host installations. check if the cookie-subdomain fits to request.
return User.current_user = User.find(session[:user]) if session[:foodcoop] == Foodsoft.env
@current_user ||= User.find(session[:user_id]) if params[:foodcoop] == Foodsoft.env
end
rescue
reset_session
flash[:error]= _("An error has occurred. Please login again.")
redirect_to :controller => 'login'
end
end
def current_user=(user)
session[:user], session[:foodcoop] = user.id, Foodsoft.env
end
def return_to
session['return_to']
end
def return_to=(uri)
session['return_to'] = uri
end
def deny_access
self.return_to = request.request_uri
redirect_to :controller => '/login', :action => 'denied'
return false
redirect_to login_url, :alert => 'Access denied!'
end
private
def authenticate(role = 'any')
# Attempt to retrieve authenticated user from controller instance or session...
if !(user = current_user)
if !current_user
# No user at all: redirect to login page.
self.return_to = request.request_uri
redirect_to :controller => '/login'
return false
session[:user_id] = nil
session['return_to'] = request.fullpath
redirect_to login_url, :alert => 'Authentication required!'
else
# We have an authenticated user, now check role...
# Roles gets the user through his memberships.
@ -78,7 +57,7 @@ class ApplicationController < ActionController::Base
else false # any unknown role will always fail
end
if hasRole
@current_user = user
current_user
else
deny_access
end

View file

@ -2,46 +2,7 @@ class LoginController < ApplicationController
skip_before_filter :authenticate # no authentication since this is the login page
before_filter :validate_token, :only => [:password, :update_password]
verify :method => :post, :only => [:login, :reset_password, :new], :redirect_to => { :action => :index }
# Redirects to the login action.
def index
render :action => 'login'
end
# Logout the current user and deletes the session
def logout
self.return_to = nil
current_user = nil
reset_session
flash[:notice] = "Abgemeldet"
render :action => 'login'
end
# Displays a "denied due to insufficient privileges" message and provides the login form.
def denied
flash[:error] = "Du bist nicht berechtigt diese Seite zu besuchen. Bitte als berechtige Benutzerin anmelden oder zurück gehen."
render :action => 'login'
end
# Login to the foodsoft.
def login
user = User.find_by_nick(params[:login][:user])
if user && user.has_password(params[:login][:password])
# Set last_login to Now()
user.update_attribute(:last_login, Time.now)
self.current_user = user
if (redirect = return_to)
self.return_to = nil
redirect_to redirect
else
redirect_to root_path
end
else
current_user = nil
flash[:error] = "Tschuldige, die Anmeldung war nicht erfolgreich. Bitte erneut versuchen."
end
end
verify :method => :post, :only => [:reset_password], :redirect_to => { :action => 'forgot_password' }
# Display the form to enter an email address requesting a token to set a new password.
def forgot_password
@ -57,8 +18,7 @@ class LoginController < ApplicationController
logger.debug("Sent password reset email to #{user.email}.")
end
end
flash[:notice] = "Wenn Deine E-Mail hier registiert ist bekommst Du jetzt eine Nachricht mit einem Passwort-Zurücksetzen-Link."
render :action => 'login'
redirect_to login_url, :notice => "Wenn Deine E-Mail hier registiert ist bekommst Du jetzt eine Nachricht mit einem Passwort-Zurücksetzen-Link."
end
# Set a new password with a token from the password reminder email.
@ -74,8 +34,7 @@ class LoginController < ApplicationController
@user.reset_password_token = nil
@user.reset_password_expires = nil
@user.save
flash[:notice] = "Dein Passwort wurde aktualisiert. Du kannst Dich jetzt anmelden."
render :action => 'login'
redirect_to login_url, :notice => "Dein Passwort wurde aktualisiert. Du kannst Dich jetzt anmelden."
else
render :action => 'password'
end

View file

@ -0,0 +1,24 @@
class SessionsController < ApplicationController
skip_before_filter :authenticate
layout 'login'
def new
end
def create
user = User.authenticate(params[:nick], params[:password])
if user
session[:user_id] = user.id
redirect_to session['return_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 login_url, :notice => "Logged out!"
end
end

View file

@ -108,7 +108,7 @@ module ApplicationHelper
# to set a title for both the h1-tag and the title in the header
def title(page_title, show_title = true)
@content_for_title = page_title.to_s
content_for(:title) { page_title.to_s }
@show_title = show_title
end

View file

@ -0,0 +1,2 @@
module SessionsHelper
end

View file

@ -176,6 +176,15 @@ class User < ActiveRecord::Base
self.groups.find(:all, :conditions => {:type => ""})
end
def self.authenticate(nick, password)
user = find_by_nick(nick)
if user && user.has_password(password)
user
else
nil
end
end
end
# == Schema Information

View file

@ -10,6 +10,8 @@
#login
- if yield(:title)
%h1= yield(:title)
- flash.each do |name, msg|
= content_tag :div, msg, :class => "flash #{name}"
= yield
#meta
Foodcoop

View file

@ -1,6 +1,4 @@
- title "Passwort vergessen?"
- if flash[:error]
%p{:style => "color: red"}= flash[:error]
%p
Kein Problem, Du kannst dir einfach ein neues Passwort zulegen.
%p

View file

@ -15,19 +15,15 @@
bitte abschalten.
#login-form.edit_form(style="width:25em;display:none")
- form_tag :action => 'login' do
- if flash[:notice]
%div.notice= flash[:notice]
- if flash[:error]
%div.error= flash[:error]
= form_tag sessions_path do
%p
%label{:for => 'user'} Benutzerin
%br/
= text_field 'login', 'user'
= text_field_tag 'nick'
%p
%label{:for => 'password'} Passwort
%br/
= password_field 'login', 'password'
= password_field_tag 'password'
= submit_tag "Anmelden"
|
= link_to "Passwort vergessen?", :action => 'forgot_password'
= link_to "Passwort vergessen?", :controller => 'login', :action => 'forgot_password'

View file

@ -1,20 +1,29 @@
Foodsoft::Application.routes.draw do
get "sessions/new"
# Use routing filter to select foodcoop config and datbase
# filter :foodcoop
root :to => redirect("/#{Foodsoft.env}")
scope '/:foodcoop', :defaults => { :foodcoop => Foodsoft.env } do
# Root path
root :to => 'home#index'
########### Sessions
match '/login' => 'sessions#new', :as => 'login'
match '/logout' => 'sessions#destroy', :as => 'logout'
resources :sessions, :only => [:new, :create, :destroy]
########### User specific
match '/login' => 'login#index', :as => 'login'
match '/logout' => 'login#logout', :as => 'logout'
match '/home/profile' => 'home#profile', :as => 'my_profile'
match '/home/ordergroup' => 'home#ordergroup', :as => 'my_ordergroup'
############ Wiki
resources :pages do
@ -141,5 +150,10 @@ Foodsoft::Application.routes.draw do
end
end
end
end
############## The rest
match '/:controller(/:action(/:id))'
end # End of /:foodcoop scope
end

View file

@ -1,239 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>Ruby on Rails: Welcome aboard</title>
<style type="text/css" media="screen">
body {
margin: 0;
margin-bottom: 25px;
padding: 0;
background-color: #f0f0f0;
font-family: "Lucida Grande", "Bitstream Vera Sans", "Verdana";
font-size: 13px;
color: #333;
}
h1 {
font-size: 28px;
color: #000;
}
a {color: #03c}
a:hover {
background-color: #03c;
color: white;
text-decoration: none;
}
#page {
background-color: #f0f0f0;
width: 750px;
margin: 0;
margin-left: auto;
margin-right: auto;
}
#content {
float: left;
background-color: white;
border: 3px solid #aaa;
border-top: none;
padding: 25px;
width: 500px;
}
#sidebar {
float: right;
width: 175px;
}
#footer {
clear: both;
}
#header, #about, #getting-started {
padding-left: 75px;
padding-right: 30px;
}
#header {
background-image: url("images/rails.png");
background-repeat: no-repeat;
background-position: top left;
height: 64px;
}
#header h1, #header h2 {margin: 0}
#header h2 {
color: #888;
font-weight: normal;
font-size: 16px;
}
#about h3 {
margin: 0;
margin-bottom: 10px;
font-size: 14px;
}
#about-content {
background-color: #ffd;
border: 1px solid #fc0;
margin-left: -55px;
margin-right: -10px;
}
#about-content table {
margin-top: 10px;
margin-bottom: 10px;
font-size: 11px;
border-collapse: collapse;
}
#about-content td {
padding: 10px;
padding-top: 3px;
padding-bottom: 3px;
}
#about-content td.name {color: #555}
#about-content td.value {color: #000}
#about-content ul {
padding: 0;
list-style-type: none;
}
#about-content.failure {
background-color: #fcc;
border: 1px solid #f00;
}
#about-content.failure p {
margin: 0;
padding: 10px;
}
#getting-started {
border-top: 1px solid #ccc;
margin-top: 25px;
padding-top: 15px;
}
#getting-started h1 {
margin: 0;
font-size: 20px;
}
#getting-started h2 {
margin: 0;
font-size: 14px;
font-weight: normal;
color: #333;
margin-bottom: 25px;
}
#getting-started ol {
margin-left: 0;
padding-left: 0;
}
#getting-started li {
font-size: 18px;
color: #888;
margin-bottom: 25px;
}
#getting-started li h2 {
margin: 0;
font-weight: normal;
font-size: 18px;
color: #333;
}
#getting-started li p {
color: #555;
font-size: 13px;
}
#sidebar ul {
margin-left: 0;
padding-left: 0;
}
#sidebar ul h3 {
margin-top: 25px;
font-size: 16px;
padding-bottom: 10px;
border-bottom: 1px solid #ccc;
}
#sidebar li {
list-style-type: none;
}
#sidebar ul.links li {
margin-bottom: 5px;
}
</style>
<script type="text/javascript">
function about() {
info = document.getElementById('about-content');
if (window.XMLHttpRequest)
{ xhr = new XMLHttpRequest(); }
else
{ xhr = new ActiveXObject("Microsoft.XMLHTTP"); }
xhr.open("GET","rails/info/properties",false);
xhr.send("");
info.innerHTML = xhr.responseText;
info.style.display = 'block'
}
</script>
</head>
<body>
<div id="page">
<div id="sidebar">
<ul id="sidebar-items">
<li>
<h3>Browse the documentation</h3>
<ul class="links">
<li><a href="http://api.rubyonrails.org/">Rails API</a></li>
<li><a href="http://stdlib.rubyonrails.org/">Ruby standard library</a></li>
<li><a href="http://corelib.rubyonrails.org/">Ruby core</a></li>
<li><a href="http://guides.rubyonrails.org/">Rails Guides</a></li>
</ul>
</li>
</ul>
</div>
<div id="content">
<div id="header">
<h1>Welcome aboard</h1>
<h2>You&rsquo;re riding Ruby on Rails!</h2>
</div>
<div id="about">
<h3><a href="rails/info/properties" onclick="about(); return false">About your application&rsquo;s environment</a></h3>
<div id="about-content" style="display: none"></div>
</div>
<div id="getting-started">
<h1>Getting started</h1>
<h2>Here&rsquo;s how to get rolling:</h2>
<ol>
<li>
<h2>Use <code>rails generate</code> to create your models and controllers</h2>
<p>To see all available options, run it without parameters.</p>
</li>
<li>
<h2>Set up a default route and remove or rename this file</h2>
<p>Routes are set up in config/routes.rb.</p>
</li>
<li>
<h2>Create your database</h2>
<p>Run <code>rake db:migrate</code> to create your database. If you're not using SQLite (the default), edit <code>config/database.yml</code> with your username and password.</p>
</li>
</ol>
</div>
</div>
<div id="footer">&nbsp;</div>
</div>
</body>
</html>

View file

@ -0,0 +1,9 @@
require 'test_helper'
class SessionsControllerTest < ActionController::TestCase
test "should get new" do
get :new
assert_response :success
end
end

View file

@ -0,0 +1,4 @@
require 'test_helper'
class SessionsHelperTest < ActionView::TestCase
end