Class: Milk::Application

Inherits:
Object show all
Defined in:
lib/milk/application.rb

Constant Summary collapse

PAGE_PATH_REGEX =
/^\/([a-zA-Z0-9_]+(\/[a-zA-Z0-9_]+)*)+\/*$/
EDIT_PATH_REGEX =
/^\/([a-zA-Z0-9_]+(\/[a-zA-Z0-9_]+)*)+\/edit\/*$/

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(require_ssl = false) ⇒ Application

Returns a new instance of Application.



9
10
11
# File 'lib/milk/application.rb', line 9

def initialize(require_ssl=false)
  @require_ssl = require_ssl
end

Instance Attribute Details

#reqObject (readonly)

Returns the value of attribute req.



7
8
9
# File 'lib/milk/application.rb', line 7

def req
  @req
end

Class Method Details

.join_tree(obj, parent) ⇒ Object

method that walks an object linking Milk objects to eachother



258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/milk/application.rb', line 258

def self.join_tree(obj, parent)
  if [Milk::Page, Milk::Component, Milk::Application].any? {|klass| obj.kind_of? klass}
    obj.parent = parent
    obj.instance_variables.each do |name|
      var = obj.instance_variable_get(name)
      if var.class == Array
        var.each do |subvar|
          join_tree(subvar, obj)
        end
      end
    end
  end
end

Instance Method Details

#call(env) ⇒ Object

Rack call interface



195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'lib/milk/application.rb', line 195

def call(env)
  @req = Rack::Request.new(env)
  @resp = Rack::Response.new
  load_user
  
  # Route the request
  @action, page_name, @page = route
  
  # Send proper mime types for browsers that claim to accept it
  @resp["Content-Type"] = 
  if env['HTTP_ACCEPT'].include? "application/xhtml+xml"
    "application/xhtml+xml"
    "text/html"
  else
    "text/html"
  end

  case @action
    when :not_found
      @resp.status = 404
      page = Milk::Page.find('NotFound')
      Milk::Application.join_tree(page, self)
      @action = :view
      @resp.write page.view
    when :view
      Milk::Application.join_tree(@page, self)
      html = @page.view
      @page.save_to_cache(html) if Milk::USE_CACHE
      @resp.write html
    when :https_redirect
      @resp.redirect('https://' +  @req.host + @req.fullpath)
    when :http_redirect
      @resp.redirect('http://' +  @req.host + @req.fullpath)
    when :edit
      Milk::Application.join_tree(@page, self)
      @resp.write @page.edit
    when :save
      Milk::Application.join_tree(@page, self)
      yaml = @page.save
      @page.save_to_cache if Milk::USE_CACHE
      @resp.write yaml
    when :preview
      Milk::Application.join_tree(@page, self)
      @resp.write @page.preview
    when :login_form
      @resp.write(haml("login"))
    when :login
      
    when :logout
      logout
    when :form_submit
      form_submit
    when :access_denied
      @resp.staus = 403
      @resp.write "Access Denied"
    else
      @resp.status = 500
      @resp.write @action.to_s
  end
  @resp.finish
end

#decode(code) ⇒ Object



91
92
93
94
95
96
97
# File 'lib/milk/application.rb', line 91

def decode(code)
  require 'base64'
  len = Milk::SECRET.length
  value = Base64.decode64(code)
  result = (0...value.length).collect { |i| value[i].ord ^ Milk::SECRET[i%len].ord }
  result.pack("C*")
end

#encode(value) ⇒ Object



84
85
86
87
88
89
# File 'lib/milk/application.rb', line 84

def encode(value)
  require 'base64'
  len = Milk::SECRET.length
  result = (0...value.length).collect { |i| value[i].ord ^ Milk::SECRET[i%len].ord }
  Base64.encode64(result.pack("C*"))
end

#flash(message = nil) ⇒ Object



136
137
138
139
140
# File 'lib/milk/application.rb', line 136

def flash(message=nil)
  @resp.delete_cookie('flash', :path => "/") unless message
  @resp.set_cookie('flash', :path => "/", :value => message) if message
  @req.cookies['flash']
end

#form_submitObject



118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/milk/application.rb', line 118

def form_submit
  instr = eval(decode(@req.params['instructions']))
  p = @req.params.reject { |k,v| k == 'instructions'}
  print instr.inspect+"\n"
  print instr[:sendto].inspect+"\n"
  print instr[:sendto].split(' ').inspect+"\n"
  instr[:sendto].split(' ').each do |email|
    continue unless u = USERS[email]
    send_email("milk@#{@req.host}", "Milk Server at #{@req.host}", email, u[:name], "Someone messaged you from #{@req.referer}", YAML.dump(p))
  end
  @resp.redirect(instr[:dest])
end

#hash(email, password) ⇒ Object



99
100
101
102
# File 'lib/milk/application.rb', line 99

def hash(email, password)
  require 'digest/md5'
  Digest::MD5.hexdigest("#{password}")
end

#load_deps(list, target) ⇒ Object



182
183
184
185
186
187
188
189
190
191
# File 'lib/milk/application.rb', line 182

def load_deps(list, target)
  return list unless DEPENDENCY_TREE[target]
  DEPENDENCY_TREE[target].each do |more|
    if more.class == Symbol
      load_deps(list, more)
    else
      list << more
    end
  end
end

#load_userObject



163
164
165
166
167
168
169
170
# File 'lib/milk/application.rb', line 163

def load_user
  @user = nil
  if current = @req.cookies['auth']
    email = decode(current)
    @user = USERS[email]
    @resp.delete_cookie('auth', :path => "/") unless @user
  end
end

#loginObject



142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/milk/application.rb', line 142

def 
  email = @req.params['email']
  if email.length > 0
    user = USERS[email]
    if user
      expected = user[:hash]
      actual = hash(email, @req.params['password'])
      if actual == expected
        @resp.set_cookie('auth', :path => "/", :value => encode(email), :secure=>@require_ssl, :httponly=>true)
      else
        flash "Incorrect password for user #{email}"
      end
    else
      flash "User #{email} not found"
    end
  else
    flash "Please enter user email and password"
  end
  @resp.redirect(@req.params['dest'])
end

#logoutObject



131
132
133
134
# File 'lib/milk/application.rb', line 131

def logout
  @resp.delete_cookie('auth', :path => "/")
  @resp.redirect(@req.params['dest'])
end

#render_dependencies(deps = []) ⇒ Object



172
173
174
175
176
177
178
179
180
# File 'lib/milk/application.rb', line 172

def render_dependencies(deps=[])
  deps << @action
  list = []
  deps.each do |target|
    load_deps(list, target)
  end
  list.uniq!
  haml("dependencies", :list => list)
end

#routeObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/milk/application.rb', line 13

def route
  path = @req.path_info
  
  if path == '/'
    # Special case for root
    path = '/Home'
  end
  
  # Fallback to match everything
  regex = /(.*)/
  
  # Route the request to the right callback
  https = @req.env['HTTPS'] == 'on'
  action = case 
    when @req.get?
      case
        when path == "/logout"
          :logout
        when path =~ EDIT_PATH_REGEX
          regex = EDIT_PATH_REGEX
          if @require_ssl && !https
            :https_redirect
          else
            :edit
          end
        when path =~ PAGE_PATH_REGEX
          regex = PAGE_PATH_REGEX
          :view
      end
    when @req.delete?
      if path =~ PAGE_PATH_REGEX
        regex = PAGE_PATH_REGEX
        :delete
      end
    when @req.post?
      if path == '/login'
        :login
      elsif path == '/form_submit'
        :form_submit
      elsif path =~ PAGE_PATH_REGEX
        regex = PAGE_PATH_REGEX
        :preview
      end
    when @req.put?
      if path =~ PAGE_PATH_REGEX
        regex = PAGE_PATH_REGEX
        :save
      end
  end || :not_found
  
  page_name = regex.match(path)[1]
  
  if (action == :view || action == :edit)
    begin 
      page = Milk::Page.find(page_name)
    rescue Milk::PageNotFoundError
      action = :not_found
    end
  end

  if (action == :preview || action == :save)
    page = Milk::Page.json_unserialize(YAML.load(@req.body.read), page_name)
  end
  
  if !@user && [:edit, :save, :delete].include?(action)
    action = :login_form
  end

  return action, page_name, page
end

#send_email(from, from_alias, to, to_alias, subject, message) ⇒ Object



104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/milk/application.rb', line 104

def send_email(from, from_alias, to, to_alias, subject, message)
 msg = <<END_OF_MESSAGE
From: #{from_alias} <#{from}>
To: #{to_alias} <#{to}>
Subject: #{subject}

#{message}
END_OF_MESSAGE
  require 'net/smtp'	
 Net::SMTP.start('localhost') do |smtp|
  smtp.send_message msg, from, to
 end
end