Moved users into new admin-namespace and made the controller restful. Also moved some logic from the controller into the user-model (dry it up..).

This commit is contained in:
Benjamin Meichsner 2009-01-12 18:26:09 +01:00
parent 47398c6a70
commit 461dfa8531
19 changed files with 242 additions and 94 deletions

View File

@ -0,0 +1,70 @@
class Admin::UsersController < ApplicationController
before_filter :authenticate_admin
def index
if (params[:per_page] && params[:per_page].to_i > 0 && params[:per_page].to_i <= 100)
@per_page = params[:per_page].to_i
else
@per_page = 20
end
# if the search field is used
conditions = "first_name LIKE '%#{params[:query]}%' OR last_name LIKE '%#{params[:query]}%'" unless params[:query].nil?
@total = User.count(:conditions => conditions)
@users = User.paginate :page => params[:page], :conditions => conditions, :per_page => @per_page, :order => 'nick'
respond_to do |format|
format.html # listUsers.haml
format.js do
render :update do |page|
page.replace_html 'table', :partial => "users"
end
end
end
end
def show
@user = User.find(params[:id])
end
def new
@user = User.new
end
def create
@user = User.new(params[:user])
if @user.save
flash[:notice] = 'Benutzerin wurde erfolgreich angelegt.'
redirect_to admin_users_path
else
render :action => 'new'
end
end
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
if @user.update_attributes(params[:user])
flash[:notice] = 'Änderungen wurden gespeichert.'
redirect_to [:admin, @user]
else
render :action => 'edit'
end
end
def destroy
user = User.find(params[:id])
if user.nick == @current_user.nick
# deny destroying logged-in-user
flash[:error] = 'Du darfst Dich nicht selbst löschen.'
else
user.destroy
flash[:notice] = 'Benutzer_in wurde gelöscht.'
end
redirect_to admin_users_path
end
end

View File

@ -5,10 +5,6 @@ class AdminController < ApplicationController
verify :method => :post, :only => [ :destroyUser, :createUser, :updateUser, :destroyGroup, :createGroup, :updateGroup], :redirect_to => { :action => :index } verify :method => :post, :only => [ :destroyUser, :createUser, :updateUser, :destroyGroup, :createGroup, :updateGroup], :redirect_to => { :action => :index }
# Messages # Messages
MSG_USER_CREATED = 'Benutzer_in wurde erfolgreich angelegt.'
MSG_USER_UPDATED = 'Änderungen wurden gespeichert'
MSG_USER_DELETED = 'Benutzer_in wurde gelöscht'
ERR_NO_SELF_DELETE = 'Du darfst Dich nicht selbst löschen'
MESG_NO_ADMIN_ANYMORE = "Du bist nun kein Admin mehr" MESG_NO_ADMIN_ANYMORE = "Du bist nun kein Admin mehr"
def index def index

View File

@ -0,0 +1,2 @@
module Admin::UsersHelper
end

View File

@ -2,15 +2,15 @@
module ApplicationHelper module ApplicationHelper
def format_time(time = Time.now) def format_time(time = Time.now)
I18n.l time, :format => "%d.%m.%Y %H:%M" I18n.l(time, :format => "%d.%m.%Y %H:%M") unless time.nil?
end end
def format_date(time = Time.now) def format_date(time = Time.now)
I18n.l time.to_date I18n.l(time.to_date) unless time.nil?
end end
def format_datetime(time = Time.now) def format_datetime(time = Time.now)
I18n.l time I18n.l(time) unless time.nil?
end end
# Creates ajax-controlled-links for pagination # Creates ajax-controlled-links for pagination
@ -29,9 +29,12 @@ module ApplicationHelper
links = [] links = []
per_page_options.each do |per_page| per_page_options.each do |per_page|
unless per_page == current unless per_page == current
links << link_to_remote(per_page, {:url => {:action => action, :params => {:per_page => per_page}}, links << link_to_remote(
:before => "Element.show('loader')", per_page,
:success => "Element.hide('loader')"}) { :url => { :action => action, :params => {:per_page => per_page}},
:before => "Element.show('loader')",
:success => "Element.hide('loader')",
:method => :get } )
else else
links << per_page links << per_page
end end
@ -51,7 +54,8 @@ module ApplicationHelper
options = { options = {
:url => {:action => 'list', :params => params.merge({:sort => key, :page => nil, :per_page => per_page})}, :url => {:action => 'list', :params => params.merge({:sort => key, :page => nil, :per_page => per_page})},
:before => "Element.show('loader')", :before => "Element.show('loader')",
:success => "Element.hide('loader')" :success => "Element.hide('loader')",
:method => :get
} }
html_options = { html_options = {
:title => _('Sort by this field'), :title => _('Sort by this field'),
@ -86,6 +90,6 @@ module ApplicationHelper
end end
def tab_is_active?(tab) def tab_is_active?(tab)
tab[:active].detect {|c| c == controller.controller_name } tab[:active].detect {|c| c == controller.controller_path }
end end
end end

View File

@ -27,13 +27,20 @@ class User < ActiveRecord::Base
has_many :assignments, :dependent => :destroy has_many :assignments, :dependent => :destroy
has_many :tasks, :through => :assignments has_many :tasks, :through => :assignments
attr_accessible :nick, :first_name, :last_name, :email, :phone, :address attr_accessor :password, :setting_attributes
validates_presence_of :nick, :email
validates_presence_of :password_hash, :message => "Password is required."
validates_length_of :nick, :in => 2..25 validates_length_of :nick, :in => 2..25
validates_uniqueness_of :nick validates_uniqueness_of :nick
validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
validates_uniqueness_of :email validates_uniqueness_of :email
validates_length_of :first_name, :in => 2..50 validates_length_of :first_name, :in => 2..50
validates_confirmation_of :password
validates_length_of :password, :in => 5..25, :allow_blank => true
before_validation :set_password
after_save :update_settings
# Adds support for configuration settings (through "settings" attribute). # Adds support for configuration settings (through "settings" attribute).
acts_as_configurable acts_as_configurable
@ -44,15 +51,14 @@ class User < ActiveRecord::Base
# User settings keys # User settings keys
# returns the User-settings and the translated description # returns the User-settings and the translated description
def self.setting_keys def self.setting_keys
settings_hash = { {
"notify.orderFinished" => _('Get message with order result'), "notify.orderFinished" => 'Get message with order result',
"notify.negativeBalance" => _('Get message if negative account balance'), "notify.negativeBalance" => 'Get message if negative account balance',
"messages.sendAsEmail" => _('Get messages as emails'), "messages.sendAsEmail" => 'Get messages as emails',
"profile.phoneIsPublic" => _('Phone is visible for foodcoop members'), "profile.phoneIsPublic" => 'Phone is visible for foodcoop members',
"profile.emailIsPublic" => _('Email is visible for foodcoop members'), "profile.emailIsPublic" => 'Email is visible for foodcoop members',
"profile.nameIsPublic" => _('Name is visible for foodcoop members') "profile.nameIsPublic" => 'Name is visible for foodcoop members'
} }
return settings_hash
end end
# retuns the default setting for a NEW user # retuns the default setting for a NEW user
# for old records nil will returned # for old records nil will returned
@ -65,11 +71,19 @@ class User < ActiveRecord::Base
return true if self.new_record? && defaults[setting] return true if self.new_record? && defaults[setting]
end end
def update_settings
for setting in User::setting_keys.keys
self.settings[setting] = setting_attributes[setting] && setting_attributes[setting] == '1' ? '1' : nil
end
end
# Sets the user's password. It will be stored encrypted along with a random salt. # Sets the user's password. It will be stored encrypted along with a random salt.
def password=(password) def set_password
salt = [Array.new(6){rand(256).chr}.join].pack("m").chomp unless password.blank?
self.password_hash, self.password_salt = Digest::SHA1.hexdigest(password + salt), salt salt = [Array.new(6){rand(256).chr}.join].pack("m").chomp
self.password_hash, self.password_salt = Digest::SHA1.hexdigest(password + salt), salt
end
end end
# Returns true if the password argument matches the user's password. # Returns true if the password argument matches the user's password.
@ -77,21 +91,21 @@ class User < ActiveRecord::Base
Digest::SHA1.hexdigest(password + self.password_salt) == self.password_hash Digest::SHA1.hexdigest(password + self.password_salt) == self.password_hash
end end
#Sets the passwort, and if fails it returns error-messages (see above) # # Sets the passwort, and if fails it returns error-messages (see above)
def set_password(options = {:required => false}, password = nil, confirmation = nil) # def set_password(options = {:required => false}, password = nil, confirmation = nil)
required = options[:required] # required = options[:required]
if required && (password.nil? || password.empty?) # if required && (password.nil? || password.empty?)
self.errors.add_to_base _('Password is required') # self.errors.add_to_base 'Password is required'
elsif !password.nil? && !password.empty? # elsif !password.nil? && !password.empty?
if password != confirmation # if password != confirmation
self.errors.add_to_base _("Passwords doesn't match") # self.errors.add_to_base "Passwords doesn't match"
elsif password.length < 5 || password.length > 25 # elsif password.length < 5 || password.length > 25
self.errors.add_to_base _('Password-length has to be between 5 and 25 characters') # self.errors.add_to_base 'Password-length has to be between 5 and 25 characters'
else # else
self.password = password # self.password = password
end # end
end # end
end # end
# Returns a random password. # Returns a random password.
def new_random_password(size = 3) def new_random_password(size = 3)

View File

@ -1,5 +0,0 @@
<% form_tag(:action => 'createUser') do %>
<%= render :partial => 'users/form' %>
<p style="clear:both;">
<%= submit_tag "Speichern" %> | <%= link_to_function('Abbrechen', 'Element.hide("newUser")')%></p>
<% end %>

View File

@ -1,12 +0,0 @@
<h1>Benutzer bearbeiten</h1>
<div id="newUser" style="width:65em">
<div class="box_title"><h2>Benutzer_in bearbeiten</h2></div>
<div class="column_content" id="userForm">
<% form_tag(:action => 'updateUser', :id => @user) do %>
<%= render :partial => 'users/form' %>
<br style="clear:both" />
<p>
<%= submit_tag 'Speichern' %> | <%= link_to 'Abbrechen', :action => 'listUsers' %></p>
<% end %>
</div>
</div>

View File

@ -1,13 +0,0 @@
<h1>Neuer Benutzer</h1>
<div id="newUser">
<div class="box_title"><h2>Neue_r Benutzer_in</h2></div>
<div class="column_content" id="userForm">
<% form_tag(:action => 'createUser') do %>
<%= render :partial => 'users/form' %>
<p style="clear:both;">
<%= submit_tag "Speichern" %> | <%= link_to('Abbrechen', :action => 'listUsers')%></p>
<% end %>
</div>
</div>
<p><%= link_to 'Benutzer_innenübersicht', :action => 'listUsers' %></p>

View File

@ -25,15 +25,14 @@
- roles << 'Artikel' if user.role_article_meta? - roles << 'Artikel' if user.role_article_meta?
- roles << 'Bestellung' if user.role_orders? - roles << 'Bestellung' if user.role_orders?
%tr{:class => cycle('even','odd', :name => 'users')} %tr{:class => cycle('even','odd', :name => 'users')}
%td= link_to user.nick, :action => 'showUser', :id => user %td= link_to user.nick, [:admin, user]
%td=h user.first_name %td=h user.first_name
%td=h user.last_name %td=h user.last_name
%td=h user.email %td=h user.email
%td=h roles.join(', ') %td=h roles.join(', ')
%td=h format_date_time(user.last_login) %td=h format_time(user.last_login)
%td %td
= link_to(image_tag('b_edit.png', :size => "16x16", :border => "0", :alt => 'Benutzer_in bearbeiten', :title => 'Benutzer_in bearbeiten'), :action => 'editUser', :id => user) = link_to(image_tag('b_edit.png', :size => "16x16", :border => "0", :alt => 'Benutzer_in bearbeiten', :title => 'Benutzer_in bearbeiten'), edit_admin_user_path(user))
= link_to(image_tag('b_drop.png', :size => "16x16", :border => "0", :alt => 'Benutzer_in löschen', :title => 'Benutzer_in löschen'), | = link_to(image_tag('b_drop.png', :size => "16x16", :border => "0", :alt => 'Benutzer_in löschen', :title => 'Benutzer_in löschen'), |
{:action => 'destroyUser', :id => user}, | [:admin, user], |
:confirm => 'Willst du ' + user.first_name + ' wirklich löschen?', | :confirm => 'Willst du ' + user.first_name + ' wirklich löschen?', :method => :delete) |
:method => "post") |

View File

@ -0,0 +1,12 @@
<h1>Benutzerin bearbeiten</h1>
<div id="newUser" style="width:65em">
<div class="box_title"><h2>Benutzerin bearbeiten</h2></div>
<div class="column_content" id="userForm">
<% form_for([:admin, @user]) do |@form| %>
<%= render :partial => 'shared/user_form' %>
<br style="clear:both" />
<p>
<%= submit_tag 'Speichern' %> | <%= link_to 'Abbrechen', admin_users_path %></p>
<% end %>
</div>
</div>

View File

@ -2,7 +2,7 @@
%p %p
%i %i
Hier kannst du Benutzer_innen Hier kannst du Benutzer_innen
= link_to_remote 'neu Anlegen', :url => {:action => 'newUser'} = link_to 'neu Anlegen', new_admin_user_path
, bearbeiten und natürlich auch löschen. , bearbeiten und natürlich auch löschen.
#newUser{:style => "display:none;"} #newUser{:style => "display:none;"}
.box_title .box_title
@ -20,9 +20,9 @@
= observe_field 'query', :frequency => 2, | = observe_field 'query', :frequency => 2, |
:before => "Element.show('loader')", | :before => "Element.show('loader')", |
:success => "Element.hide('loader')", | :success => "Element.hide('loader')", |
:url => {:action => 'listUsers'}, | :url => admin_users_path, |
:with => 'query' | :with => 'query', |
:method => :get |
#table #table
= render :partial => "listUsers" = render :partial => "users"
- if @current_user.role_admin? %p= link_to 'Neue Benutzerin', new_admin_user_path
%p= link_to 'Neue Benutzer_in', :action => 'newUser'

View File

@ -0,0 +1,13 @@
- title "Neue Benutzerin"
#newUser
.box_title
%h2 Neue Benutzerin
.column_content#userForm
- form_for([:admin, @user]) do |@form|
= render :partial => 'shared/user_form'
%p{:style => "clear:both" }
= submit_tag "Speichern"
|
= link_to('Abbrechen', admin_users_path )
%p= link_to 'Benutzerinnenübersicht', admin_users_path

View File

@ -1,12 +1,14 @@
<h1><%=h @user.nick %></h1> <h1><%=h @user.nick %></h1>
<div class="left_column" style="width:100%"> <div class="left_column" style="width:100%">
<div class="box_title"><h2>Übersicht</h2></div> <div class="box_title">
<h2>Übersicht</h2>
</div>
<div class="column_content"> <div class="column_content">
<%= render :partial => 'users/show'%> <%= render :partial => 'users/show'%>
<p style="clear:both"> <p style="clear:both">
<%= link_to 'Bearbeiten', :action => 'editUser', :id => @user %> <%= link_to 'Bearbeiten', edit_admin_user_path(@user) %>
| <%= link_to 'Löschen', { :action => 'destroyUser', :id => @user }, :confirm => 'Willst du ' + @user.first_name + ' wirklich rausschmeißen?', :method => "post" %> | <%= link_to 'Löschen', [:admin, @user], :confirm => "Willst du #{@user.first_name} wirklich rausschmeißen?", :method => :delete %>
| <%= link_to 'Nachricht senden', :controller => 'messages', :action => 'user', :id => @user %> | <%= link_to 'Nachricht senden', :controller => 'messages', :action => 'user', :id => @user %>
</p> </p>
</div> </div>
<div class="box_title"><h2>Gruppenabos</h2></div> <div class="box_title"><h2>Gruppenabos</h2></div>

View File

@ -26,7 +26,8 @@
{ :name => "Suppliers", :url => suppliers_path, :access? => (u.role_suppliers?) } { :name => "Suppliers", :url => suppliers_path, :access? => (u.role_suppliers?) }
] ]
}, },
{ :name => "Finance", :url => "/finance", :active => ["finance", "invoices", "transactions", "balancing"], { :name => "Finance", :url => "/finance",
:active => ["finance", "finance/invoices", "finance/transactions", "finance/balancing"],
:access? => (u.role_finance?), :access? => (u.role_finance?),
:subnav => [ :subnav => [
{ :name => "Manage accounts", :url => "/finance/transactions" }, { :name => "Manage accounts", :url => "/finance/transactions" },
@ -34,10 +35,11 @@
{ :name => "Invoices", :url => finance_invoices_path } { :name => "Invoices", :url => finance_invoices_path }
] ]
}, },
{ :name => "Administration", :url => "/admin", :active => ["admin"], { :name => "Administration", :url => "/admin",
:active => ["admin", "admin/users"],
:access? => (u.role_admin?), :access? => (u.role_admin?),
:subnav => [ :subnav => [
{ :name => "Users", :url => "/admin/listUsers" }, { :name => "Users", :url => "/admin/users" },
{ :name => "Groups", :url => "/admin/listGroups" } { :name => "Groups", :url => "/admin/listGroups" }
] ]
} }

View File

@ -0,0 +1,50 @@
<%= @form.error_messages %>
<table style="float:left;width:52%;">
<tr>
<td><%= @form.label :nick %></td>
<td><%= @form.text_field :nick %></td>
</tr>
<tr>
<td><%= @form.label :first_name %></td>
<td><%= @form.text_field :first_name %></td>
</tr>
<tr>
<td><%= @form.label :last_name %></td>
<td><%= @form.text_field :last_name %></td>
</tr>
<tr>
<td><%= @form.label :email %></td>
<td><%= @form.text_field :email %></td>
</tr>
<tr>
<td><%= @form.label :phone %></td>
<td><%= @form.text_field :phone %></td>
</tr>
<tr>
<td><%= @form.label :address %></td>
<td><%= @form.text_field :address %></td>
</tr>
<tr>
<td/>
</tr>
<tr>
<td><%= @form.label :password, "Password" %></td>
<td><%= @form.password_field :password %></td>
</tr>
<tr>
<td><%= @form.label :password_confirmation, "Password confirmation" %></td>
<td><%= @form.password_field :password_confirmation %></td>
</tr>
</table>
<table style="float:right;width:45%;">
<tr>
<td colspan="2"><b>Einstellungen:</b></td>
</tr>
<% for setting in User::setting_keys.keys -%>
<tr>
<td><label for="user[setting_attributes][<%= setting %>]"><%=h User::setting_keys[setting]%></label></td>
<td><%= check_box_tag "user[setting_attributes][#{setting}]", '1', @user.settings[setting] == '1' || @user.settings_default(setting) %></td>
</tr>
<% end -%>
</table>

View File

@ -29,12 +29,12 @@
<td/> <td/>
</tr> </tr>
<tr> <tr>
<td><label for="user[password]">Neues Passwort</label></td> <td><label for="user_password_entry">Neues Passwort</label></td>
<td><%= password_field_tag "user[password]" %></td> <td><%= password_field_tag "user", "password_entry" %></td>
</tr> </tr>
<tr> <tr>
<td><label for="user[password_confirmation]">Passwort wiederholen</label></td> <td><label for="user_password_entry_confirmation">Passwort wiederholen</label></td>
<td><%= password_field_tag "user[password_confirmation]" %></td> <td><%= password_field_tag "user", "password_entry_confirmation" %></td>
</tr> </tr>
</table> </table>
<table style="float:right;width:45%;"> <table style="float:right;width:45%;">

View File

@ -1,5 +1,9 @@
ActionController::Routing::Routes.draw do |map| ActionController::Routing::Routes.draw do |map|
map.namespace :admin do |admin|
admin.resources :users
end
map.namespace :finance do |finance| map.namespace :finance do |finance|
finance.resources :invoices finance.resources :invoices
finance.connect 'transactions/:action/:id', :controller => 'transactions' finance.connect 'transactions/:action/:id', :controller => 'transactions'

View File

@ -0,0 +1,8 @@
require 'test_helper'
class Admin::UsersControllerTest < ActionController::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
end

View File

@ -301,7 +301,9 @@ module WillPaginate
def page_link(page, text, attributes = {}) def page_link(page, text, attributes = {})
# bennis hack to support ajax-support # bennis hack to support ajax-support
if @options[:remote] == true if @options[:remote] == true
@template.link_to_remote text, :url => url_for(page), :html => attributes, :before => "Element.show('loader')", :success => "Element.hide('loader')" @template.link_to_remote text, :url => url_for(page), :html => attributes,
:before => "Element.show('loader')", :success => "Element.hide('loader')",
:method => :get
else else
@template.link_to text, url_for(page), attributes @template.link_to text, url_for(page), attributes
end end