Class: Waw::StaticController::WawAccess

Inherits:
Object
  • Object
show all
Includes:
Waw::ScopeUtils
Defined in:
lib/waw/controllers/static/waw_access.rb,
lib/waw/controllers/static/match.rb,
lib/waw/controllers/static/waw_access_dsl.rb

Overview

Waw version of .htaccess files

Defined Under Namespace

Classes: DSL, Match

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Waw::ScopeUtils

#config, #find_kernel_context, #logger, #params, #rack_env, #real_session, #request, #resources, #response, #root_folder, #session

Constructor Details

#initialize(parent = nil, folder = nil, read_file = nil) ⇒ WawAccess

Creates a default WawAccess file



25
26
27
28
29
30
31
32
33
34
# File 'lib/waw/controllers/static/waw_access.rb', line 25

def initialize(parent = nil, folder = nil, read_file = nil)
  @parent = parent
  @folder = folder
  @strategy = :deny_all
  @inherits = true
  @serve = []
  @children = {}
  @file_server = ::Rack::File.new(folder) if parent.nil?
  dsl_merge_file(read_file) if read_file
end

Instance Attribute Details

#folderObject

The folder which is served



8
9
10
# File 'lib/waw/controllers/static/waw_access.rb', line 8

def folder
  @folder
end

#inheritsObject

Does it inherits its parent configuration?



14
15
16
# File 'lib/waw/controllers/static/waw_access.rb', line 14

def inherits
  @inherits
end

#parentObject

The parent wawaccess file



17
18
19
# File 'lib/waw/controllers/static/waw_access.rb', line 17

def parent
  @parent
end

#strategyObject

Strategy :allow_all or :deny_all



11
12
13
# File 'lib/waw/controllers/static/waw_access.rb', line 11

def strategy
  @strategy
end

Class Method Details

.load_hierarchy(root_folder, parent = nil) ⇒ Object

Returns a wawaccess tree for a given folder

Raises:

  • (ArgumentError)


39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/waw/controllers/static/waw_access.rb', line 39

def self.load_hierarchy(root_folder, parent = nil)
  raise ArgumentError, "Invalid folder #{root_folder}" unless (root_folder and File.directory?(root_folder))

  # Locate and load the .wawaccess file or provide a default one
  wawaccess_file = File.join(root_folder, '.wawaccess')
  if File.exists?(wawaccess_file)
    wawaccess = WawAccess.new(parent, root_folder, wawaccess_file)
  else
    wawaccess = WawAccess.new(parent, root_folder)
    wawaccess.strategy = :deny_all
    wawaccess.inherits = true
  end
  
  # Install its children
  Dir.new(root_folder).each do |file|
    next if ['.', '..'].include?(file)
    child_folder = File.join(root_folder, file)
    next unless File.directory?(child_folder)
    
    # Load the child and save it
    wawaccess.add_child(file, WawAccess.load_hierarchy(child_folder, wawaccess))
  end
  wawaccess
end

Instance Method Details

#add_child(folder, wawaccess) ⇒ Object

Adds a child in the hierarchy



72
73
74
# File 'lib/waw/controllers/static/waw_access.rb', line 72

def add_child(folder, wawaccess)
  @children[folder] = wawaccess
end

#add_serve(patterns, &block) ⇒ Object

Installs some pattern services

Raises:

  • (ArgumentError)


77
78
79
80
81
82
83
84
# File 'lib/waw/controllers/static/waw_access.rb', line 77

def add_serve(patterns, &block)
  raise ArgumentError, "WawAccess.add_serve expects a block" unless block 
  patterns.each do |pattern|
    raise WawError, "Invalid serving pattern #{pattern} (#{pattern.class})"\
      unless recognized_pattern?(pattern)
    @serve << [pattern, block]
  end
end

#apply_rules(env) ⇒ Object

Applies the rules defined here or delegate to the parent if allowed



205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/waw/controllers/static/waw_access.rb', line 205

def apply_rules(env)
  if match = find_match(env)
    match.__execute(env)
  elsif (parent and inherits)
    parent.apply_rules(env)
  else
    body = "File not found: #{env['PATH_INFO']}\n"
    [404, {"Content-Type" => "text/plain",
           "Content-Length" => body.size.to_s,
           "X-Cascade" => "pass"},
     [body]]
  end
end

#call(env) ⇒ Object

Makes a Rack standard call



242
243
244
# File 'lib/waw/controllers/static/waw_access.rb', line 242

def call(env)
  do_path_serve(env['PATH_INFO'], env)
end

#do_path_serve(path, env = rack_env) ⇒ Object

Serves a path from a root waw access in the hierarchy



235
236
237
238
239
# File 'lib/waw/controllers/static/waw_access.rb', line 235

def do_path_serve(path, env = rack_env)
  env['REQ_PATH'] = normalize_req_path(path)
  waw_access = (find_wawaccess_for(env['REQ_PATH']) || self)
  waw_access.apply_rules(env)
end

#dsl_merge(dsl_str, read_file = nil) ⇒ Object

Merges a DSL string inside this waw access



87
88
89
90
91
92
93
94
95
96
97
# File 'lib/waw/controllers/static/waw_access.rb', line 87

def dsl_merge(dsl_str, read_file=nil)
  begin
    dsl = WawAccess::DSL.new(self)
    dsl.instance_eval(dsl_str)
  rescue WawError => ex
    raise WawError, "Corrupted .wawaccess file #{read_file}: #{ex.message}", ex.backtrace
  rescue Exception => ex
    raise WawError, "Corrupted .wawaccess file #{read_file}: #{ex.message}", ex.backtrace
  end
  self
end

#dsl_merge_file(read_file) ⇒ Object

Merge with a .wawaccess file

Raises:



100
101
102
103
104
# File 'lib/waw/controllers/static/waw_access.rb', line 100

def dsl_merge_file(read_file)
  raise WawError, "Missing .wawaccess file #{readfile}" unless File.file?(read_file)
  dsl_merge(File.read(read_file), read_file)
  self
end

#file_serverObject

Fake accessor that go to the top of the hierarchy



20
21
22
# File 'lib/waw/controllers/static/waw_access.rb', line 20

def file_server
  @file_server || (parent && parent.file_server)
end

#find_files(pattern) ⇒ Object

Helper to locate css and js files



130
131
132
133
134
135
136
# File 'lib/waw/controllers/static/waw_access.rb', line 130

def find_files(pattern)
  Dir[File.join(folder, pattern, "*.#{pattern}")].sort{|f1, f2|
    File.basename(f1) <=> File.basename(f2)
  }.collect{|f|
    File.join(pattern, File.basename(f))
  }
end

#find_match(env) ⇒ Object

Finds the matching block inside this .wawaccess handler



170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/waw/controllers/static/waw_access.rb', line 170

def find_match(env)
  path = env['REQ_PATH']
  @serve.each do |pattern, block|
    case pattern
      when FalseClass
      when TrueClass
        return Match.new(self, path, block)
      when String
        if pattern=='*'
          return Match.new(self, path, block)
        elsif /^\*?\.[a-z]+$/ =~ pattern
          return Match.new(self, path, block) if File.extname(realpath(path))==pattern
        else
          return Match.new(self, path, block) if File.basename(realpath(path))==pattern
        end
      when Regexp
        if matchdata = pattern.match(path)
          return Match.new(self, path, block, *matchdata.to_a)
        end
      when Waw::Validation::Validator
        if pattern.validate(matching_file(path))
          return Match.new(self, path, block) 
        end
      when StaticController::AbstractMatcher
        if pattern.matches?(env)
          return Match.new(self, path, block)
        end
      else
        raise WawError, "Unrecognized wawaccess pattern #{pattern}"
    end
  end
  nil
end

#find_wawaccess_for(url, url_array = url.split('/').reject{|k| k.empty?}) ⇒ Object

Finds the wawaccess instance for a given url



155
156
157
158
159
160
161
162
163
164
165
# File 'lib/waw/controllers/static/waw_access.rb', line 155

def find_wawaccess_for(url, url_array = url.split('/').reject{|k| k.empty?})
  if url_array.empty?
    self
  else
    if @children.has_key?(nextfolder = url_array.shift)
      @children[nextfolder].find_wawaccess_for(url, url_array)
    else
      self
    end
  end
end

#identifier(append = true) ⇒ Object

Returns an identifier for this wawaccess



141
142
143
144
145
146
147
# File 'lib/waw/controllers/static/waw_access.rb', line 141

def identifier(append = true)
  if parent
    parent.identifier(false) + (append ? "#{File.basename(@folder)}/.wawaccess" : File.basename(@folder))
  else
    (append ? ".wawaccess" : "")
  end
end

#matching_file(path) ⇒ Object

Locates the file that would be matched by a given normalized url.



119
120
121
# File 'lib/waw/controllers/static/waw_access.rb', line 119

def matching_file(path)
  File.join(root.folder, path)
end

#normalize_req_path(req_path) ⇒ Object

Normalizes a requested path, removing any .html, .htm suffix



222
223
224
225
226
227
228
229
230
231
232
# File 'lib/waw/controllers/static/waw_access.rb', line 222

def normalize_req_path(req_path)
  # 1) Decode the req_path with URI::decode
  req_path = URI::decode(req_path)
  # 2) Strip first
  req_path = req_path.strip
  # 3) Remove first slash 
  req_path = req_path[1..-1] if req_path[0,1]=='/'
  # 4) Remove last slash
  req_path = req_path[0..-2] if req_path[req_path.length-1,1]=='/'
  req_path
end

#realpath(file) ⇒ Object

Returns the real path of a file



113
114
115
# File 'lib/waw/controllers/static/waw_access.rb', line 113

def realpath(file)
  File.expand_path(File.join(folder, file))
end

#recognized_pattern?(pattern) ⇒ Boolean

About installation through DSL

Returns:



66
67
68
69
# File 'lib/waw/controllers/static/waw_access.rb', line 66

def recognized_pattern?(pattern)
  [FalseClass, TrueClass, String, 
   Regexp, Waw::Validation::Validator, StaticController::AbstractMatcher].any?{|c| c===pattern}
end

#relativize(file, folder = folder) ⇒ Object

Relativize a path against a given folder



124
125
126
127
# File 'lib/waw/controllers/static/waw_access.rb', line 124

def relativize(file, folder = folder)
  file, folder = File.expand_path(file), File.expand_path(folder)
  file[(folder.length+1)..-1]
end

#req_pathObject

Utilites about paths



108
109
110
# File 'lib/waw/controllers/static/waw_access.rb', line 108

def req_path
  rack_env['REQ_PATH'] || normalize_req_path(rack_env['PATH_INFO'])
end

#rootObject

Returns the root waw access in the hierarchy



150
151
152
# File 'lib/waw/controllers/static/waw_access.rb', line 150

def root
  @root ||= (parent ? parent.root : self)
end