Project

General

Profile

366.patch

Ohad Levy, 11/05/2010 06:17 PM

View differences:

app/controllers/application_controller.rb
3 3

  
4 4
class ApplicationController < ActionController::Base
5 5
  protect_from_forgery # See ActionController::RequestForgeryProtection for details
6
  rescue_from ActionController::RoutingError, :with => :no_puppetclass_documentation_handler
6 7

  
7 8
  # standard layout to all controllers
8 9
  layout 'standard'
......
11 12
  before_filter :require_ssl, :require_login
12 13
  before_filter :load_tabs, :manage_tabs, :unless => :request_json?
13 14
  before_filter :welcome, :detect_notices, :only => :index, :unless => :request_json?
15
  before_filter :authorize, :except => :login
16

  
17
  # Authorize the user for the requested action
18
  def authorize(ctrl = params[:controller], action = params[:action])
19
    return true if request.xhr?
20
    allowed = User.current.allowed_to?({:controller => ctrl, :action => action})
21
    allowed ? true : deny_access
22
  end
23

  
24
  def deny_access
25
    User.current.logged? ? render_403 : require_login
26
  end
14 27

  
15 28
  protected
16 29

  
......
25 38

  
26 39

  
27 40
  # Force a user to login if authentication is enabled
28
  # Sets @user to the logged in user, or to admin if logins are not used
41
  # Sets User.current to the logged in user, or to admin if logins are not used
29 42
  def require_login
30
    unless session[:user] and @user = User.find(session[:user])
43
    unless session[:user] and User.current = User.find(session[:user])
31 44
      # User is not found or first login
32 45
      if SETTINGS[:login] and SETTINGS[:login] == true
33 46
        # authentication is enabled
34 47
        if request_json?
35 48
          # JSON requests (REST API calls) use basic http authenitcation and should not use/store cookies
36
          @user = authenticate_or_request_with_http_basic { |u, p| User.try_to_login(u, p) }
37
          return !@user.nil?
49
          User.current = authenticate_or_request_with_http_basic { |u, p| User.try_to_login(u, p) }
50
          return !User.current.nil?
38 51
        end
39 52
        session[:original_uri] = request.request_uri # keep the old request uri that we can redirect later on
40 53
        redirect_to login_users_path and return
41 54
      else
42 55
        # We assume we always have a user logged in, if authentication is disabled, the user is the build-in admin account.
43
        unless @user = User.find_by_login("admin")
56
        unless User.current = User.find_by_login("admin")
44 57
          flash[:foreman_error] = "Unable to find internal system admin account - Recreating . . ."
45
          @user = User.create_admin
58
          User.current = User.current = User.create_admin
46 59
        end
47
        session[:user] = @user.id unless request_json?
60
        session[:user] = User.current.id unless request_json?
48 61
      end
49 62
    end
50 63
  end
51 64

  
52 65
  def current_user
53
    @user
66
    User.current
54 67
  end
55 68

  
56 69
  def invalid_request
......
103 116
    session[:last_controller] = controller_name
104 117
    self.active_tab           = "" if @controller_changed
105 118

  
106
    return if params[:tab_name].empty? or params[:action] != "index"
119
    return true if params[:tab_name].empty? or params[:action] != "index"
107 120

  
108
    if    params[:tab_name] == "Reset"
121
    if params[:tab_name] == "Reset"
109 122
      self.active_tab    = ""
110 123
    elsif params[:remove_me] and @tabs.has_key? params[:tab_name]
111 124
      @tabs.delete params[:tab_name]
......
122 135
    end
123 136
  end
124 137

  
138
  def require_admin
139
    unless User.current.admin?
140
      render_403
141
      return false
142
    end
143
    true
144
  end
145

  
146
  def render_403
147
    respond_to do |format|
148
      format.html { render :template => "common/403", :layout => (request.xhr? ? false : 'standard'), :status => 403 }
149
      format.atom { head 403 }
150
      format.yaml { head 403 }
151
      format.yml  { head 403 }
152
      format.xml  { head 403 }
153
      format.json { head 403 }
154
    end
155
    return false
156
  end
157

  
158
  # this has to be in the application controller, as the new request (for puppetdoc) url is not controller specific.
159
  def no_puppetclass_documentation_handler(exception)
160
    if exception.message =~ /No route matches "\/puppet\/rdoc\/([^\/]+)\/classes\/(.+?)\.html/
161
      render :template => "puppetclasses/no_route", :locals => {:environment => $1, :name => $2.gsub("/","::")}, :layout => false
162
    else
163
      local_request? ? rescue_action_locally(exception) : rescue_action_in_public(exception)
164
    end
165
  end
166

  
125 167
end
app/controllers/environments_controller.rb
1 1
class EnvironmentsController < ApplicationController
2 2
  include Foreman::Controller::Environments
3
  rescue_from ActionController::RoutingError, :with => :no_puppetclass_documentation_handler
4 3

  
5 4
  before_filter :find_environment, :only => %w{show edit update destroy}
6 5

  
app/controllers/fact_values_controller.rb
1 1
class FactValuesController < ApplicationController
2
  skip_before_filter :require_ssl, :only => :create
3
  skip_before_filter :require_login, :only => :create
2
  skip_before_filter :require_ssl,               :only => :create
3
  skip_before_filter :require_login,             :only => :create
4
  skip_before_filter :authorize,                 :only => :create
4 5
  skip_before_filter :verify_authenticity_token, :only => :create
5 6

  
6 7
  # avoids storing the facts data in the log files
app/controllers/hosts_controller.rb
8 8
    :multiple_enable, :multiple_disable, :submit_multiple_disable, :submit_multiple_enable]
9 9
  before_filter :find_host, :only => %w[show edit update destroy puppetrun setBuild cancelBuild report
10 10
    reports facts storeconfig_klasses clone externalNodes pxe_config]
11
  before_filter :authorize
11 12

  
12 13
  filter_parameter_logging :root_pass
13 14
  helper :hosts, :reports
14 15

  
15 16
  def index
17

  
18
    # restrict allowed hosts list based on the user permissions
19
    @search = User.current.admin? ? Host.search(params[:search]) : Host.my_hosts.search(params[:search])
20

  
16 21
    respond_to do |format|
17
      @search = Host.search(params[:search])
18 22
      format.html do
19
        @hosts = @search.paginate :page => params[:page], :include => [:hostgroup, :domain, :operatingsystem, :environment, :model]
23
        # You can see a host if you can CRUD it
24
        @hosts = @search.paginate :page => params[:page], :include => [:hostgroup, :domain, :operatingsystem, :environment, :model, :fact_values]
20 25
        @via    = "fact_values_"
21 26
        @last_reports = Report.maximum(:id, :group => :host_id, :conditions => {:host_id => @hosts})
22 27
      end
......
343 348
    hosts.delete_if {|host| host.destroy}
344 349

  
345 350
    session[:selected] = []
346
    flash[:foreman_notice] = hosts.empty? ? "Destroyed selected hosts" : "The following hosts were not deleted: #{hosts.map(&:name).join('<br/>')}"
351
    missed_hosts       = hosts.map(&:name).join('<br/>')
352
    flash[:foreman_notice] = hosts.empty? ? "Destroyed selected hosts" : "The following hosts were not deleted: #{missed_hosts}"
347 353
    redirect_to(hosts_path)
348 354
  end
349 355

  
......
487 493
    action = mode ? "enabled" : "disabled"
488 494

  
489 495
    session[:selected] = []
490
    flash[:foreman_notice] = @hosts.empty? ? "#{action.capitalize} selected hosts" : "The following hosts were not #{action}: #{hosts.map(&:name).join('<br/>')}"
496
    missed_hosts       = hosts.map(&:name).join('<br/>')
497
    flash[:foreman_notice] = @hosts.empty? ? "#{action.capitalize} selected hosts" : "The following hosts were not #{action}: #{missed_hosts}"
491 498
    redirect_to(hosts_path) and return
492 499
  end
493 500

  
......
503 510
    @search = list.search(params[:search])
504 511
    respond_to do |format|
505 512
      format.html do
506
        @hosts = @search.paginate :page => params[:page], :include => [:hostgroup, :domain, :operatingsystem, :environment, :model]
513
        @hosts = @search.paginate :page => params[:page], :include => [:hostgroup, :domain, :operatingsystem, :environment, :model, :fact_values]
507 514
        @via    = "fact_values_"
508 515
        @last_reports = Report.maximum(:id, :group => :host_id, :conditions => {:host_id => @hosts})
509 516
        @title = title
app/controllers/models_controller.rb
34 34

  
35 35
  def destroy
36 36
    @model = Model.find(params[:id])
37
    if  @model.destroy
37
    if @model.destroy
38 38
      flash[:foreman_notice] = "Successfully destroyed model."
39 39
    else
40 40
      flash[:foreman_error] = @model.errors.full_messages.join("<br/>")
app/controllers/notices_controller.rb
1 1
class NoticesController < ApplicationController
2
  skip_before_filter :authorize, :only => :destroy
3

  
2 4
  def destroy
3 5
    @notice = Notice.find(params[:id])
4
    if @notice.global
5
      @notice.destroy
6
    else
7
      @notice.users.delete(current_user)
8
      @notice.destroy unless @notice.users.any?
9
    end
6
    @notice.destroy_notice
10 7
    redirect_to :back
11 8
  end
12 9
end
app/controllers/puppetclasses_controller.rb
1 1
class PuppetclassesController < ApplicationController
2 2
  include Foreman::Controller::Environments
3
  rescue_from ActionController::RoutingError, :with => :no_puppetclass_documentation_handler
4 3

  
5 4
  def index
6 5
    respond_to do |format|
app/controllers/reports_controller.rb
1 1
class ReportsController < ApplicationController
2
  skip_before_filter :require_login, :only => :create
3
  skip_before_filter :require_ssl, :only => :create
2
  skip_before_filter :require_login,             :only => :create
3
  skip_before_filter :require_ssl,               :only => :create
4
  skip_before_filter :authorize,                 :only => :create
4 5
  skip_before_filter :verify_authenticity_token, :only => :create
5 6
  helper :reports
6 7

  
app/controllers/roles_controller.rb
1
# redMine - project management software
2
# Copyright (C) 2006  Jean-Philippe Lang
3
#
4
# This program is free software; you can redistribute it and/or
5
# modify it under the terms of the GNU General Public License
6
# as published by the Free Software Foundation; either version 2
7
# of the License, or (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13
#
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17

  
18
class RolesController < ApplicationController
19
  before_filter :require_admin
20

  
21
  def index
22
    @search = Role.search(params[:search])
23
    @roles = @search.paginate(:page => params[:page], :order => "builtin ASC, name ASC")
24
  end
25

  
26
  def new
27
    # Prefills the form with 'default user' role permissions
28
    @role        = Role.new({:permissions => Role.default_user.permissions})
29
    @permissions = @role.setable_permissions
30
  end
31

  
32
  def create
33
    @role = Role.new(params[:role])
34
    @permissions = @role.setable_permissions
35
    if @role.save
36
      flash[:foreman_notice] = "#{@role.name} succcessfully created"
37
      redirect_to roles_url
38
    else
39
      render :action => 'new'
40
    end
41
  end
42

  
43
  def edit
44
    @role = Role.find(params[:id])
45
    @permissions = @role.setable_permissions
46
  end
47

  
48
  def update
49
    @role = Role.find(params[:id])
50
    if @role.update_attributes(params[:role])
51
      flash[:foreman_notice] = "#{@role.name} successfully updated"
52
      redirect_to roles_url
53
    else
54
      render :action => 'edit'
55
    end
56
  end
57

  
58
  def destroy
59
    @role = Role.find(params[:id])
60
    if @role.destroy
61
      flash[:foreman_notice] = "Successfully destroyed role."
62
    else
63
      flash[:foreman_error] = @role.errors.full_messages.join("<br/>")
64
    end
65
    redirect_to roles_url
66
  end
67

  
68
  def report
69
    @roles = Role.all(:order => 'builtin, name')
70
    @permissions = Foreman::AccessControl.permissions.select { |p| !p.public? }
71
    if request.post?
72
      @roles.each do |role|
73
        role.permissions = params[:permissions][role.id.to_s]
74
        role.save
75
      end
76
      flash[:foreman_notice] = "All non public permissions successfuly updated"
77
      redirect_to roles_url
78
    end
79
  end
80
end
app/controllers/usergroups_controller.rb
1 1
class UsergroupsController < ApplicationController
2 2
  def index
3
    @usergroups = Usergroup.all
3
    @usergroups = Usergroup.all(:order => "name")
4 4
  end
5 5

  
6 6
  def new
app/controllers/users_controller.rb
2 2

  
3 3
  filter_parameter_logging :password, :password_confirmation
4 4
  skip_before_filter :require_login, :only => [:login, :logout]
5
  skip_before_filter :authorize, :only => [:login, :logout]
5 6

  
6 7
  def index
7 8
    # set defaults search order - cant use default scope due to bug in AR
......
21 22
    @user = User.new(params[:user])
22 23
    @user.admin = params[:admin]
23 24
    if @user.save
25
      @user.roles = Role.name_is("Anonymous")
24 26
      flash[:foreman_notice] = "Successfully created user."
25 27
      redirect_to users_url
26 28
    else
......
30 32

  
31 33
  def edit
32 34
    @user = User.find(params[:id])
35
    if @user.user_facts.count == 0
36
      user_fact = @user.user_facts.build :operator => "==", :andor => "or"
37
      user_fact.fact_name_id = Puppet::Rails::FactName.first.id if Puppet::Rails::FactName.first
38
      true
39
    end
33 40
  end
34 41

  
35 42
  def update
36 43
    @user = User.find(params[:id])
37 44
    admin = params[:user].delete :admin
45
    # Remove keys for resticted variables when the user is granted minimal access only to their own account
46
    if @minimal_edit
47
      for key in params[:user].keys
48
        params[:user].delete key unless %w{password_confirmation password mail firstname lastname}.include? key
49
      end
50
    end
38 51
    if @user.update_attributes(params[:user])
39
      @user.update_attribute :admin, admin
52
      # Only an admin can update admin attribute of another use
53
      # this is required, as the admin field is blacklisted above
54
      @user.update_attribute(:admin, admin) if User.current.admin
40 55
      flash[:foreman_notice] = "Successfully updated user."
41 56
      redirect_to users_url
42 57
    else
......
46 61

  
47 62
  def destroy
48 63
    user = User.find(params[:id])
49
    if user == current_user
64
    if user == User.current
50 65
      flash[:foreman_notice] = "You are currently logged in, suicidal?"
51 66
      redirect_to :back and return
52 67
    end
......
80 95
  # Called from the logout link
81 96
  # Clears the rails session and redirects to the login action
82 97
  def logout
83
    session[:user] = @user = nil
98
    session[:user] = @user = User.current = nil
84 99
    if flash[:foreman_notice] or flash[:foreman_error]
85 100
      flash.keep
86 101
    else
102
      session.clear
87 103
      flash[:foreman_notice] = "Logged out - See you soon"
88 104
    end
89 105
    redirect_to login_users_path
......
99 115
    end
100 116
  end
101 117

  
118
  private
119

  
120
  def authorize(ctrl = params[:controller], action = params[:action])
121
    # Minimal edit is true when the user is granted access to just their
122
    # own account details
123
    @minimal_edit = false
124
    return true if User.current.allowed_to?({:controller => ctrl, :action => action})
125
    if action =~ /edit|update/ and params[:id] == User.current.id.to_s
126
      return @minimal_edit=true
127
    else
128
      deny_access and return
129
    end
130
  end
131

  
102 132
end
app/helpers/application_helper.rb
1
# Methods added to this helper will be available to all templates in the application.
1
# Methods added to this helper will be available to all templates in the application
2 2
module ApplicationHelper
3 3

  
4
  def contract model
5
    model.to_s
6
  end
4 7
  def graph(type,opts = {})
5 8
    Gchart.send(type, {:size => '400x150', :bg => "E6DFCF", :format => "image_tag"}.merge(opts))
6 9
  end
......
10 13
  end
11 14

  
12 15
  def edit_habtm klass, association
13
    render :partial => 'common/edit_habtm', :locals =>{ :klass => klass, :associations => association.all.delete_if{|e| e == klass}}
16
    render :partial => 'common/edit_habtm', :locals =>{ :klass => klass, :associations => association.all.sort.delete_if{|e| e == klass}}
14 17
  end
15 18

  
16 19
  def link_to_remove_fields(name, f)
17 20
    f.hidden_field(:_destroy) + link_to_function(image_tag("false.png", :title => "remove"), "remove_fields(this)")
18 21
  end
19 22

  
23
  # Creates a link to a javascript function that creates field entries for the association on the web page
24
  # +name+       : String containing links's text
25
  # +f+          : FormBuiler object
26
  # +association : The field are created to allow entry into this association
27
  # +partial+    : String containing an optional partial into which we render
20 28
  def link_to_add_fields(name, f, association, partial = nil)
21 29
    new_object = f.object.class.reflect_on_association(association).klass.new
22 30
    fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
......
52 60
      :position => {:after => {:success => "selected_classes" }}
53 61
  end
54 62

  
63
  def check_all_links(form_name)
64
    link_to_function("Check all", "checkAll('#{form_name}', true)") +
65
    " | " +
66
    link_to_function("Uncheck all", "checkAll('#{form_name}', false)")
67
  end
68

  
55 69
  def searchtab title, search, options
56 70
    opts = {:action => params[:action], :tab_name => title, :search => search}
57 71
    selected_class = options[:selected] ? "selectedtab" : ""
......
81 95
    return param.to_i unless param.empty?
82 96
    return @fact_name_id if @fact_name_id
83 97
  end
98

  
99
  # Return true if user is authorized for controller/action, otherwise false
100
  # +controller+ : String or symbol for the controller
101
  # +action+     : String or symbol for the action
102
  def authorized_for(controller, action)
103
    User.current.allowed_to?({:controller => controller, :action => action}) rescue false
104
  end
105

  
106
  # Display a link if user is authorized, otherwise a string
107
  # +name+    : String to be displayed
108
  # +options+ : Hash containing
109
  #             :enable_link  : Boolean indicating whether the link is to be displayed
110
  #             :controlller  : String or Symbol representing the controller
111
  #             :auth_action  : String or Symbol representing the action to be used for authorization checks
112
  # +html_options+ : Hash containing html options for the link or span
113
  def link_to_if_authorized(name, options = {}, html_options = {})
114
    enable_link = options.has_key?(:enable_link) ? options.delete(:enable_link) : true
115
    auth_action = options.delete :auth_action
116
    if enable_link
117
      link_to_if authorized_for(options[:controller] || params[:controller], auth_action || options[:action]), name, options, html_options
118
    else
119
      content_tag(:span, name, {:class => "entry"}.merge(html_options))
120
    end
121
  end
122

  
123
  # Display a link if user is authorized, otherwise nothing
124
  # +name+    : String to be displayed
125
  # +options+ : Hash containing
126
  #             :controlller  : String or Symbol representing the controller
127
  #             :auth_action  : String or Symbol representing the action to be used for authorization checks
128
  # +html_options+ : Hash containing html options for the link or span
129
  def display_link_if_authorized(name, options = {}, html_options = nil)
130
    auth_action = options.delete :auth_action
131
    link_to(name, options, html_options) if authorized_for(options[:controller] || params[:controller], auth_action || options[:action])
132
  end
133

  
134
  def authorized_edit_habtm klass, association
135
    return edit_habtm(klass, association) if authorized_for params[:controller], params[:action]
136
    show_habtm klass.send(association.name.pluralize.downcase)
137
  end
138

  
84 139
end
app/helpers/common_parameters_helper.rb
1 1
module CommonParametersHelper
2
  # Return true if user is authorized for controller/action OR controller/action@type, otherwise false
3
  def authorized_via_my_scope(controller, action)
4
    return true if authorized_for(controller, action)
5

  
6
    operation = "#{action}_my_#{controller.singularize}".to_sym
7
    User.current.allowed_to?(operation) and User.current.send(controller).include?(eval("@#{controller.singularize}"))
8
  end
2 9
end
app/helpers/domains_helper.rb
1 1
module DomainsHelper
2
  include CommonParametersHelper
2 3
end
app/helpers/host_groups_helper.rb
1 1
module HostGroupsHelper
2
  include CommonParametersHelper
2 3
end
app/helpers/hostgroups_helper.rb
1 1
module HostgroupsHelper
2
  include CommonParametersHelper
2 3
end
app/helpers/hosts_helper.rb
1 1
module HostsHelper
2
  include CommonParametersHelper
2 3
  def last_report_column(record)
3 4
    return nil if record.last_report.nil?
4 5
    time = time_ago_in_words(record.last_report.getlocal)
5 6
    image_tag("#{not (record.error_count > 0 or record.no_report)}.png", :size => "18x18") +
6
      link_to_if(@last_reports[record.id], time, report_path(@last_reports[record.id].to_i))
7
      link_to_if_authorized(time,  hash_for_report_path(:id => @last_reports[record.id], :enable_link => @last_reports[record.id])
8
    )
7 9
  end
8 10

  
9 11
# method that reformats the hostname column by adding the status icons
app/models/architecture.rb
1 1
class Architecture < ActiveRecord::Base
2
  include Authorization
2 3
  has_many :hosts
3 4
  has_and_belongs_to_many :operatingsystems
4 5
  validates_uniqueness_of :name
app/models/auth_source.rb
16 16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17 17

  
18 18
class AuthSource < ActiveRecord::Base
19
  include Authorization
19 20
  has_many :users
20 21

  
21 22
  validates_presence_of :name
......
49 50
  end
50 51

  
51 52
  # Try to authenticate a user not yet registered against available sources
53
  # Returns : user's attributes OR nil
52 54
  def self.authenticate(login, password)
53 55
    AuthSource.find(:all).each do |source|
54 56
      begin
app/models/auth_source_ldap.rb
31 31
    self.port = 389 if self.port == 0
32 32
  end
33 33

  
34
  # Loads the LDAP info for a user and authenticates the user with their password
35
  # Returns : Array of Strings.
36
  #           Either the users's DN or the user's full details OR nil
34 37
  def authenticate(login, password)
35 38
    return nil if login.blank? || password.blank?
36 39
    attrs = []
app/models/authorization.rb
1
module Authorization
2
  def self.included(base)
3
    base.class_eval do
4
      before_save    :enforce_edit_permissions
5
      before_destroy :enforce_destroy_permissions
6
      before_create  :enforce_create_permissions
7
    end
8
  end
9

  
10
  # We must enforce the security model
11
  def enforce_edit_permissions
12
    enforce_permissions("edit") if enforce?
13
  end
14

  
15
  def enforce_destroy_permissions
16
    enforce_permissions("destroy") if enforce?
17
  end
18

  
19
  def enforce_create_permissions
20
    enforce_permissions("create") if enforce?
21
  end
22

  
23
  def enforce_permissions operation
24
    # We get called again with the operation being set to create
25
    return true if operation == "edit" and new_record?
26

  
27
    klass   = self.class.name.downcase
28
    klass.gsub!(/authsource.*/, "authenticator")
29
    klass.gsub!(/commonparameter.*/, "global_variable")
30
    klasses = klass.pluralize
31
    return true if User.current.allowed_to?("#{operation}_#{klasses}".to_sym)
32

  
33
    errors.add_to_base "You do not have permission to #{operation} this #{klass}"
34
    false
35
  end
36

  
37
  private
38
  def enforce?
39
    not (defined?(Rake) or User.current.admin?)
40
  end
41
end
app/models/domain.rb
1 1
# This models a DNS domain and so represents a site.
2 2
class Domain < ActiveRecord::Base
3
  include Authorization
3 4
  has_many :hosts
4 5
  has_many :subnets
5 6
  has_many :domain_parameters, :dependent => :destroy, :foreign_key => :reference_id
7
  has_and_belongs_to_many :users, :join_table => "user_domains"
8

  
6 9
  accepts_nested_attributes_for :domain_parameters, :reject_if => lambda { |a| a[:value].blank? }, :allow_destroy => true
7 10
  validates_uniqueness_of :name
8 11
  validates_uniqueness_of :fullname, :allow_blank => true, :allow_nil => true
......
24 27
    super({:only => [:name, :id]}.merge(options))
25 28
  end
26 29

  
30
  def enforce_permissions operation
31
    # We get called again with the operation being set to create
32
    return true if operation == "edit" and new_record?
33

  
34
    current = User.current
35

  
36
    if current.allowed_to?("#{operation}_domains".to_sym)
37
      # If you can create domains then you can create them anywhere
38
      return true if operation == "create"
39
      # However if you are editing or destroying and you have a domain list then you are contrained
40
      if current.domains.empty? or current.domains.map(&:id).include? self.id
41
        return true
42
      end
43
    end
44

  
45
    errors.add_to_base "You do not have permission to #{operation} this domain"
46
    false
47
  end
48

  
27 49
end
28 50

  
app/models/domain_parameter.rb
1 1
class DomainParameter < Parameter
2 2
  belongs_to :domain, :foreign_key => :reference_id
3 3
  validates_uniqueness_of :name, :scope => :reference_id
4

  
5
  private
6
  def enforce_permissions operation
7
    # We get called again with the operation being set to create
8
    return true if operation == "edit" and new_record?
9

  
10
    current = User.current
11

  
12
    if current.allowed_to?("#{operation}_domains".to_sym)
13
      if current.domains.empty? or current.domains.include? domain
14
        return true
15
      end
16
    end
17

  
18
    errors.add_to_base "You do not have permission to #{operation} this domain parameter"
19
    false
20
  end
4 21
end
app/models/group_parameter.rb
1 1
class GroupParameter < Parameter
2 2
  belongs_to :hostgroup, :foreign_key => :reference_id
3 3
  validates_uniqueness_of :name, :scope => :reference_id
4

  
5
  private
6
  def enforce_permissions operation
7
    # We get called again with the operation being set to create
8
    return true if operation == "edit" and new_record?
9

  
10
    current = User.current
11

  
12
    if current.allowed_to?("#{operation}_hostgroups".to_sym)
13
      if current.hostgroups.empty? or current.hostgroups.include? hostgroup
14
        return true
15
      end
16
    end
17

  
18
    errors.add_to_base "You do not have permission to #{operation} this group parameter"
19
    false
20
  end
4 21
end
app/models/host.rb
1 1
class Host < Puppet::Rails::Host
2
  include Authorization
2 3
  belongs_to :architecture
3 4
  belongs_to :media
4 5
  belongs_to :model
......
52 53
  named_scope :successful, {:conditions => "puppet_status = 0"}
53 54
  named_scope :alerts_disabled, {:conditions => ["enabled = ?", false] }
54 55

  
56
  named_scope :my_hosts, lambda {
57
    user                 = User.current
58
    owner_conditions     = sanitize_sql_for_conditions(["((hosts.owner_id in (?) AND hosts.owner_type = 'Usergroup') OR (hosts.owner_id = ? AND hosts.owner_type = 'User'))", user.my_usergroups.map(&:id), user.id])
59
    domain_conditions    = sanitize_sql_for_conditions([" (hosts.domain_id in (?))",dms = (user.domains).map(&:id)])
60
    hostgroup_conditions = sanitize_sql_for_conditions([" (hosts.hostgroup_id in (?))",(hgs = user.hostgroups).map(&:id)])
61

  
62
    fact_conditions = ""
63
    for user_fact in (ufs = user.user_facts)
64
      fact_conditions += sanitize_sql_for_conditions ["(hosts.id = fact_values.host_id and fact_values.fact_name_id = ? and fact_values.value #{user_fact.operator} ?)", user_fact.fact_name_id, user_fact.criteria]
65
      fact_conditions = user_fact.andor == "and" ? "(#{fact_conditions}) and " : "#{fact_conditions} or  "
66
    end
67
    if match = fact_conditions.match(/^(.*).....$/)
68
      fact_conditions = "(#{match[1]})"
69
    end
70

  
71
    conditions = ""
72
    if user.filtering?
73
      conditions  = "#{owner_conditions}"                                                                                                            if     user.filter_on_owner
74
      (conditions = (user.domains_andor    == "and") ? "(#{conditions}) and #{domain_conditions} "    : "#{conditions} or #{domain_conditions} ")    unless dms.empty?
75
      (conditions = (user.hostgroups_andor == "and") ? "(#{conditions}) and #{hostgroup_conditions} " : "#{conditions} or #{hostgroup_conditions} ") unless hgs.empty?
76
      (conditions = (user.facts_andor      == "and") ? "(#{conditions}) and #{fact_conditions} "      : "#{conditions} or #{fact_conditions} ")      unless ufs.empty?
77
      conditions.sub!(/\s*\(\)\s*/, "")
78
      conditions.sub!(/^(?:\(\))?\s?(?:and|or)\s*/, "")
79
      conditions.sub!(/\(\s*(?:or|and)\s*\(/, "((")
80
    end
81
    {:conditions => conditions}
82
  }
83

  
55 84
  # audit the changes to this model
56 85
  acts_as_audited :except => [:last_report, :puppet_status, :last_compile]
57 86

  
......
70 99
    validates_format_of      :sp_name, :with => /.*-sp/, :allow_nil => true, :allow_blank => true
71 100
    validates_presence_of    :architecture_id, :domain_id, :mac, :operatingsystem_id
72 101
    validates_length_of      :root_pass, :minimum => 8,:too_short => 'should be 8 characters or more'
73
    validates_format_of      :mac,       :with => /([a-f0-9]{1,2}:){5}[a-f0-9]{1,2}/
74
    validates_format_of      :ip,        :with => /(\d{1,3}\.){3}\d{1,3}/
102
    validates_format_of      :mac,       :with => (/([a-f0-9]{1,2}:){5}[a-f0-9]{1,2}/)
103
    validates_format_of      :ip,        :with => (/(\d{1,3}\.){3}\d{1,3}/)
75 104
    validates_presence_of    :ptable, :message => "cant be blank unless a custom partition has been defined",
76
                             :if => Proc.new { |host| host.disk.empty? and not defined?(Rake) }
105
      :if => Proc.new { |host| host.disk.empty? and not defined?(Rake) }
77 106
    validates_format_of      :sp_mac,    :with => /([a-f0-9]{1,2}:){5}[a-f0-9]{1,2}/, :allow_nil => true, :allow_blank => true
78 107
    validates_format_of      :sp_ip,     :with => /(\d{1,3}\.){3}\d{1,3}/, :allow_nil => true, :allow_blank => true
79 108
    validates_format_of      :serial,    :with => /[01],\d{3,}n\d/, :message => "should follow this format: 0,9600n8", :allow_blank => true, :allow_nil => true
......
103 132
  # supports a simple user, or a usergroup
104 133
  # selection parameter is expected to be an ActiveRecord id_and_type method (see Foreman's AR extentions).
105 134
  def is_owned_by=(selection)
106
    oid = User.find(selection.to_i) if selection =~ /-Users$/
107
    oid = Usergroup.find(selection.to_i) if selection =~ /-Usergroups$/
135
    oid = User.find(selection.to_i) if selection =~ (/-Users$/)
136
    oid = Usergroup.find(selection.to_i) if selection =~ (/-Usergroups$/)
108 137
    self.owner = oid
109 138
  end
110 139

  
......
193 222

  
194 223
  # returns the list of puppetclasses a host is in.
195 224
  def puppetclasses_names
196
      return all_puppetclasses.collect {|c| c.name}
225
    return all_puppetclasses.collect {|c| c.name}
197 226
  end
198 227

  
199 228
  def all_puppetclasses
200
     return hostgroup.nil? ? puppetclasses : (hostgroup.puppetclasses + puppetclasses).uniq
229
    return hostgroup.nil? ? puppetclasses : (hostgroup.puppetclasses + puppetclasses).uniq
201 230
  end
202 231

  
203 232
  # provide information about each node, mainly used for puppet external nodes
......
278 307

  
279 308
  def fv name
280 309
    v=fact_values.first(:select => "fact_values.value", :joins => :fact_name,
281
                       :conditions => "fact_names.name = '#{name}'")
310
                        :conditions => "fact_names.name = '#{name}'")
282 311
    v.value unless v.nil?
283 312
  end
284 313

  
......
404 433
  end
405 434

  
406 435
  def classes_from_storeconfigs
407
   klasses = resources.find(:all, :conditions => {:restype => "Class"}, :select => :title, :order => :title)
408
   klasses.map!(&:title).delete(:main)
409
   return klasses
436
    klasses = resources.find(:all, :conditions => {:restype => "Class"}, :select => :title, :order => :title)
437
    klasses.map!(&:title).delete(:main)
438
    return klasses
410 439
  end
411 440

  
412 441
  def can_be_build?
......
422 451
    return hash
423 452
  end
424 453

  
454
  def enforce_permissions operation
455
    if operation == "edit" and new_record?
456
      return true # We get called again with the operation being set to create
457
    end
458
    current = User.current
459
    if (operation == "edit") or operation == "destroy"
460
      if current.allowed_to?("#{operation}_hosts".to_sym)
461
        return true if Host.my_hosts(current).include? self
462
      end
463
    else # create
464
      if current.allowed_to?(:create_hosts)
465
        # We are unconstrained
466
        return true if current.domains.empty? and current.hostgroups.empty?
467
        # We are contrained and the constraint is matched
468
        return true if (!current.domains.empty?    and current.domains.include?(domain)) or
469
        (!current.hostgroups.empty? and current.hostgroups.include?(hostgroup))
470
      end
471
    end
472
    errors.add_to_base "You do not have permission to #{operation} this host"
473
    false
474
  end
475

  
425 476
  private
426 477
  # align common mac and ip address input
427 478
  def normalize_addresses
......
459 510
    return if name.empty? or domain.nil?
460 511
    self.name += ".#{domain}" unless name =~ /.#{domain}$/
461 512
  end
462

  
463 513
end
app/models/host_parameter.rb
3 3
  validates_uniqueness_of :name, :scope => :reference_id
4 4

  
5 5
  def to_s
6
    "#{host_id ? host.name : "unassociated"}: #{name} = #{value}"
6
    "#{host.id ? host.name : "unassociated"}: #{name} = #{value}"
7 7
  end
8 8

  
9
  private
10
  def enforce_permissions operation
11
  # We get called again with the operation being set to create
12
  return true if operation == "edit" and new_record?
13

  
14
  self.host.enforce_permissions operation
15
  end
9 16
end
app/models/hostgroup.rb
1 1
class Hostgroup < ActiveRecord::Base
2
  include Authorization
2 3
  has_and_belongs_to_many :puppetclasses
4
  has_and_belongs_to_many :users, :join_table => "user_hostgroups"
3 5
  validates_uniqueness_of :name
4 6
  validates_format_of :name, :with => /\A(\S+\s?)+\Z/, :message => "can't be blank or contain trailing white spaces."
5 7
  has_many :group_parameters, :dependent => :destroy, :foreign_key => :reference_id
......
10 12

  
11 13
  acts_as_audited
12 14

  
13
#TODO: add a method that returns the valid os for a hostgroup
15
  #TODO: add a method that returns the valid os for a hostgroup
14 16

  
15
 def all_puppetclasses
16
   puppetclasses
17
 end
18

  
19
 def hostgroup
20
   self
21
 end
17
  def all_puppetclasses
18
    puppetclasses
19
  end
22 20

  
23 21
  def as_json(options={})
24 22
    super({:only => [:name, :id]}.merge(options))
25 23
  end
26 24

  
25
  def hostgroup
26
    self
27
  end
27 28
end
app/models/media.rb
1 1
class Media < ActiveRecord::Base
2
  include Authorization
2 3
  has_and_belongs_to_many :operatingsystems
3 4
  has_many :hosts
4 5
  validates_uniqueness_of :name
app/models/model.rb
1 1
class Model < ActiveRecord::Base
2
  include Authorization
2 3
  has_many :hosts
3 4
  before_destroy Ensure_not_used_by.new(:hosts)
4 5
  validates_uniqueness_of :name
app/models/notice.rb
12 12
    "#{global? ? "global" : "individual"} #{content}"
13 13
  end
14 14

  
15
  def destroy_notice
16
    if global
17
      destroy
18
    else
19
      users.delete(User.current)
20
      destroy unless users.any?
21
    end
22
  end
15 23
  private
16 24

  
17 25
  def add_to_all_users
app/models/operatingsystem.rb
2 2
require 'uri'
3 3

  
4 4
class Operatingsystem < ActiveRecord::Base
5
  include Authorization
5 6
  has_many :hosts
6 7
  has_and_belongs_to_many :medias
7 8
  has_and_belongs_to_many :ptables
app/models/parameter.rb
1 1
class Parameter < ActiveRecord::Base
2
  include Authorization
2 3
  acts_as_audited
3 4
  validates_presence_of   :name, :value
4 5
  validates_format_of     :name, :value, :with => /^.*\S$/, :message => "can't be blank or contain trailing white space"
app/models/ptable.rb
3 3
# A host object may contain a reference to one of these ptables or, alternatively, it may contain a
4 4
# modified version of one of these in textual form
5 5
class Ptable < ActiveRecord::Base
6
  include Authorization
6 7
  has_many :hosts
7 8
  has_and_belongs_to_many :operatingsystems
8 9
  before_destroy Ensure_not_used_by.new(:hosts)
app/models/puppetclass.rb
1 1
class Puppetclass < ActiveRecord::Base
2
  include Authorization
2 3
  has_and_belongs_to_many :environments
3 4
  has_and_belongs_to_many :operatingsystems
4 5
  has_and_belongs_to_many :hosts
app/models/report.rb
1 1
class Report < ActiveRecord::Base
2
  include Authorization
2 3
  belongs_to :host
3 4
  has_many :messages, :through => :logs, :dependent => :destroy
4 5
  has_many :sources, :through => :logs, :dependent => :destroy
......
244 245
    nil
245 246
  end
246 247

  
247

  
248 248
  # The metrics layout has changed in Puppet 2.6.x release,
249 249
  # this method attempts to align the bit value metrics and the new name scheme in 2.6.x
250 250
  # returns a hash of { :type => "metric type", :name => "metric_name"}
251 251
  def self.translate_metrics_to26 metric
252
   case metric
252
    case metric
253 253
    when "applied"
254 254
      { :type => "changes", :name => :total}
255 255
    else
......
257 257
    end
258 258
  end
259 259

  
260
  def enforce_permissions operation
261
    # No one can edit a report
262
    return false if operation == "edit"
263

  
264
    # Anyone can create a report
265
    return true if operation == "create"
266
    return true if operation == "destroy" and User.current.allowed_to?(:destroy_reports)
267

  
268
    errors.add_to_base "You do not have permission to #{operation} this report"
269
    false
270
  end
260 271
end
app/models/role.rb
1
# redMine - project management software
2
# Copyright (C) 2006  Jean-Philippe Lang
3
#
4
# This program is free software; you can redistribute it and/or
5
# modify it under the terms of the GNU General Public License
6
# as published by the Free Software Foundation; either version 2
7
# of the License, or (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13
#
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17

  
18
class Role < ActiveRecord::Base
19
  # Built-in roles
20
  BUILTIN_DEFAULT_USER  = 1
21
  BUILTIN_ANONYMOUS     = 2
22

  
23
  named_scope :givable, { :conditions => "builtin = 0", :order => 'name' }
24
  named_scope :builtin, lambda { |*args|
25
    compare = 'not' if args.first == true
26
    { :conditions => "#{compare} builtin = 0" }
27
  }
28

  
29
  before_destroy :check_deletable
30

  
31
  has_many :user_roles, :dependent => :destroy
32
  has_many :users, :through => :user_roles
33

  
34
  serialize :permissions, Array
35
  attr_protected :builtin
36

  
37
  validates_presence_of :name
38
  validates_uniqueness_of :name
39
  validates_length_of :name, :maximum => 30
40
  validates_format_of :name, :with => /^\w[\w\s\'\-]*\w$/i
41
  validates_inclusion_of :builtin, :in => 0..2
42

  
43
  def initialize *args
44
    super *args
45
    self.builtin = 0
46
  end
47

  
48
  def permissions
49
    read_attribute(:permissions) || []
50
  end
51

  
52
  def permissions=(perms)
53
    perms = perms.collect {|p| p.to_sym unless p.blank? }.compact.uniq if perms
54
    write_attribute(:permissions, perms)
55
  end
56

  
57
  def add_permission!(*perms)
58
    self.permissions = [] unless permissions.is_a?(Array)
59

  
60
    permissions_will_change!
61
    perms.each do |p|
62
      p = p.to_sym
63
      permissions << p unless permissions.include?(p)
64
    end
65
    save!
66
  end
67

  
68
  def remove_permission!(*perms)
69
    return unless permissions.is_a?(Array)
70
    permissions_will_change!
71
    perms.each { |p| permissions.delete(p.to_sym) }
72
    save!
73
  end
74

  
75
  # Returns true if the role has the given permission
76
  def has_permission?(perm)
77
    !permissions.nil? && permissions.include?(perm.to_sym)
78
  end
79

  
80
  # Return true if the role is a builtin role
81
  def builtin?
82
    self.builtin != 0
83
  end
84

  
85
  # Return true if the role is a user role
86
  def user?
87
    !self.builtin?
88
  end
89

  
90
  # Return true if role is allowed to do the specified action
91
  # action can be:
92
  # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
93
  # * a permission Symbol (eg. :edit_project)
94
  def allowed_to?(action)
95
    if action.is_a? Hash
96
      allowed_actions.include? "#{action[:controller]}/#{action[:action]}"
97
    else
98
      allowed_permissions.include? action
99
    end
100
  end
101

  
102
  # Return all the permissions that can be given to the role
103
  def setable_permissions
104
    setable_permissions  = Foreman::AccessControl.permissions - Foreman::AccessControl.public_permissions
105
    setable_permissions -= Foreman::AccessControl.loggedin_only_permissions if self.builtin == BUILTIN_ANONYMOUS
106
    setable_permissions
107
  end
108

  
109
  # Find all the roles that can be given to a user
110
  def self.find_all_givable
111
    find(:all, :conditions => {:builtin => 0}, :order => 'name')
112
  end
113

  
114
  # Return the builtin 'default user' role.  If the role doesn't exist,
115
  # it will be created on the fly.
116
  def self.default_user
117
    default_user_role = find(:first, :conditions => {:builtin => BUILTIN_DEFAULT_USER})
118
    if default_user_role.nil?
119
      default_user_role = create(:name => 'Default user') do |role|
120
        role.builtin = BUILTIN_DEFAULT_USER
121
      end
122
      raise 'Unable to create the default user role.' if default_user_role.new_record?
123
    end
124
    default_user_role
125
  end
126

  
127
  # Return the builtin 'anonymous' role.  If the role doesn't exist,
128
  # it will be created on the fly.
129
  def self.anonymous
130
    anonymous_role = find(:first, :conditions => {:builtin => BUILTIN_ANONYMOUS})
131
    if anonymous_role.nil?
132
      anonymous_role = create(:name => 'Anonymous') do |role|
133
        role.builtin = BUILTIN_ANONYMOUS
134
      end
135
      raise "Unable to create the anonymous role." if anonymous_role.new_record?
136
    end
137
    anonymous_role
138
  end
139

  
140
private
141
  def allowed_permissions
142
    @allowed_permissions ||= permissions + Foreman::AccessControl.public_permissions.collect {|p| p.name}
143
  end
144

  
145
  def allowed_actions
146
    @actions_allowed ||= allowed_permissions.inject([]) { |actions, permission| actions += Foreman::AccessControl.allowed_actions(permission) }.flatten
147
  end
148

  
149
  def check_deletable
150
    errors.add_to_base "Role is in use" if users.any?
151
    errors.add_to_base "Can't delete builtin role" if builtin?
152
    errors.empty?
153
  end
154
end
app/models/subnet.rb
1 1
class Subnet < ActiveRecord::Base
2
  include Authorization
2 3
  has_many :hosts, :through => :domain
3
  has_many :sps, :through => :hosts
4
  #has_many :sps, :through => :hosts
4 5
  belongs_to :domain
5 6
  validates_presence_of   :number, :mask
6 7
  validates_uniqueness_of :number
......
9 10
  validates_uniqueness_of :name, :scope => :domain_id
10 11
  validates_associated :domain
11 12

  
12
  before_destroy Ensure_not_used_by.new(:hosts, :sps)
13
  before_destroy Ensure_not_used_by.new(:hosts) #, :sps)
13 14

  
14 15
  # Subnets are displayed in the form of their network number/network mask
15 16
  def to_label
app/models/user.rb
1 1
require 'digest/sha1'
2 2

  
3 3
class User < ActiveRecord::Base
4
  include Authorization
4 5
  attr_protected :password_hash, :password_salt, :admin
5 6
  attr_accessor :password, :password_confirmation
6 7

  
......
9 10
  has_many :usergroups, :through => :usergroup_member
10 11
  has_many :direct_hosts, :as => :owner, :class_name => "Host"
11 12
  has_and_belongs_to_many :notices, :join_table => 'user_notices'
13
  has_many :user_roles
14
  has_many :roles, :through => :user_roles
15
  has_and_belongs_to_many :domains,    :join_table => "user_domains"
16
  has_and_belongs_to_many :hostgroups, :join_table => "user_hostgroups"
17
  has_many :user_facts, :dependent => :destroy
18
  has_many :facts, :through => :user_facts, :source => :fact_name
19

  
20
  accepts_nested_attributes_for :user_facts, :reject_if => lambda { |a| a[:criteria].blank? }, :allow_destroy => true
12 21

  
13 22
  validates_uniqueness_of :login, :message => "already exists"
14 23
  validates_presence_of :login, :mail, :auth_source_id
......
24 33
  before_destroy Ensure_not_used_by.new(:hosts), :ensure_admin_is_not_deleted
25 34
  validate :name_used_in_a_usergroup
26 35
  before_validation :prepare_password
36
  after_destroy Proc.new {|user| user.domains.clear; user.hostgroups.clear}
37

  
38
  cattr_accessor :current
27 39

  
28 40
  def to_label
29 41
    "#{firstname} #{lastname}"
......
31 43
  alias_method :name, :to_label
32 44

  
33 45
  def <=>(other)
34
    self.name <=> other.name
46
    self.name.downcase <=> other.name.downcase
35 47
  end
36 48

  
37 49
  # The text item to see in a select dropdown menu
......
42 54
  def self.create_admin
43 55
    email = SETTINGS[:administrator] || "root@" + Facter.domain
44 56
    user = User.create(:login => "admin", :firstname => "Admin", :lastname => "User",
45
                :mail => email, :auth_source => AuthSourceInternal.first, :password => "changeme")
57
                       :mail => email, :auth_source => AuthSourceInternal.first, :password => "changeme")
46 58
    user.update_attribute :admin, true
47 59
    user
48 60
  end
49 61

  
62
  # Tries to find the user in the DB and then authenticate against their authentication source
63
  # If the user is not in the DB then try to login the user on each available athentication source
64
  # If this succeeds then copy the user's details from the authentication source into the User table
65
  # Returns : User object OR nil
50 66
  def self.try_to_login(login, password)
51 67
    # Make sure no one can sign in with an empty password
52 68
    return nil if password.to_s.empty?
53
    if user = find(:first, :conditions => ["login=?", login])
69

  
70
    if user = find_by_login(login)
54 71
      # user is already in local database
55
      if user.auth_source
56
        # user has an authentication method
57
        return nil unless user.auth_source.authenticate(login, password)
72
      if user.auth_source and user.auth_source.authenticate(login, password)
73
        # user has an authentication method and the authentication was successful
74
        User.current = user
75
        user.update_attribute(:last_login_on, Time.now.utc)
76
      else
77
        user = nil
58 78
      end
59 79
    else
60 80
      # user is not yet registered, try to authenticate with available sources
61 81
      attrs = AuthSource.authenticate(login, password)
62 82
      if attrs
63 83
        user = new(*attrs)
84
        # The default user must be given :create_users permissions for on-the-fly to work.
64 85
        user.login = login
86
        User.current = user
65 87
        if user.save
66 88
          user.reload
67 89
          logger.info "User '#{user.login}' auto-created from #{user.auth_source}"
90
          user.update_attribute(:last_login_on, Time.now.utc)
68 91
        else
69 92
          logger.info "Failed to save User '#{user.login}' #{user.errors.full_messages}"
93
          user = nil
70 94
        end
71 95
      end
72 96
    end
73
    user.update_attribute(:last_login_on, Time.now.utc) if user and not user.new_record?
97
    anonymous = Role.find_by_name("Anonymous")
98
    User.current.roles <<  anonymous unless user.nil? or User.current.roles.include?(anonymous)
74 99
    return user
75 100
  rescue => text
76 101
    raise text
......
80 105
    self.password_hash == encrypt_password(pass)
81 106
  end
82 107

  
83
  def indirect_hosts
108
  def my_usergroups
84 109
    all_groups = []
85 110
    for usergroup in usergroups
86 111
      all_groups += usergroup.all_usergroups
87 112
    end
88
    all_groups.uniq.map{|g| g.hosts}.flatten.uniq
113
    all_groups.uniq
114
  end
115

  
116
  def indirect_hosts
117
    my_usergroups.map{|g| g.hosts}.flatten.uniq
89 118
  end
90 119

  
91 120
  def hosts
......
100 129
    auth_source and auth_source.can_set_password?
101 130
  end
102 131

  
132
  # Return true if the user is allowed to do the specified action
133
  # action can be:
134
  # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
135
  # * a permission Symbol (eg. :edit_project)
136
  def allowed_to?(action, options={})
137
    return true if admin?
138

  
139
    return false if roles.empty?
140
    roles.detect {|role| role.allowed_to?(action)}
141
  end
142

  
143
  def logged?
144
    true
145
  end
146

  
147
  # Indicates whether the user has host filtering enabled
148
  # Returns : Boolean
149
  def filtering?
150
    filter_on_owner or
151
    domains.any?    or
152
    hostgroups.any? or
153
    facts.any?
154
  end
155

  
103 156
  private
104 157

  
105 158
  def prepare_password
......
113 166
    Digest::SHA1.hexdigest([pass, password_salt].join)
114 167
  end
115 168

  
169
  protected
170

  
116 171
  def name_used_in_a_usergroup
117 172
    if Usergroup.all.map(&:name).include?(self.login)
118 173
      errors.add_to_base "A usergroup already exists with this name"
......
124 179
  # admin account automatically
125 180
  def ensure_admin_is_not_deleted
126 181
    if login == "admin"
127
      errors.add_to_base "Can't Delete Internal Admin account"
128
      logger.warn "Unable to delete Internal Admin Account"
182
      errors.add_to_base "Can't delete internal admin account"
183
      logger.warn "Unable to delete internal admin account"
129 184
      return false
130 185
    end
131 186
  end
app/models/user_fact.rb
1
class UserFact < ActiveRecord::Base
2
  belongs_to :user
3
  belongs_to :fact_name, :class_name => "Puppet::Rails::FactName"
4

  
5
  validates_inclusion_of :andor,    :in => %w{and or}
6
  validates_inclusion_of :operator, :in => %w{= !=  > >= < <= }
7
  validates_presence_of  :fact_name
8
  validates_presence_of  :criteria
9
  validates_presence_of  :user
10

  
11
  def initialize *args
12
    super *args
13
    operator = "="  if operator.empty?
14
    andor    = "or" if andor.empty?
15
  end
16

  
17
  def to_s
18
    n  = user.try(:name) || "Unknown user"
19
    fn = fact_name.try(:name) || "Unknown fact"
20
    "#{n}:#{fn}:#{criteria.empty? ? "Empty" : criteria}:#{operator}:#{andor}"
21
  end
22
end
app/models/user_role.rb
1
# Redmine - project management software
2
# Copyright (C) 2006-2009  Jean-Philippe Lang
3
#
4
# This program is free software; you can redistribute it and/or
5
# modify it under the terms of the GNU General Public License
6
# as published by the Free Software Foundation; either version 2
7
# of the License, or (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13
#
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
... This diff was truncated because it exceeds the maximum size that can be displayed.