-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdfill.rb
104 lines (73 loc) · 1.69 KB
/
dfill.rb
1
2
3
4
5
6
7
8
9
10
11
12
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
require 'sinatra'
require 'haml'
require 'data_mapper'
require 'dm-sqlite-adapter'
require 'json'
require './config'
# DB
DataMapper::setup(:default, "sqlite3://#{Dir.pwd}/dfill.db")
class Line
include DataMapper::Resource
property :id, Serial
property :content, Text, :required => true, :length => 255
end
DataMapper.finalize.auto_upgrade!
# HTTP auth
helpers do
def protected!
return if authorized?
headers['WWW-Authenticate'] = 'Basic realm="Restricted Area"'
halt 401, "Not authorized\n"
end
def authorized?
@auth ||= Rack::Auth::Basic::Request.new(request.env)
@auth.provided? and @auth.basic? and @auth.credentials and @auth.credentials == [$config[:login], $config[:password]]
end
end
# ROUTES - Front-end
range = {
:min => 1,
:max => 100,
:value => 10
}
get '/' do
@range = range
haml :index
end
get '/api/:count' do
count = params[:count].to_i
unless (count >= range[:min] && count <= range[:max]) then
halt 400
end
lines = Line.all.map(&:content)
while (lines.length < count) do
lines.concat(lines)
end
lines.shuffle!.slice!(0, lines.length - count)
content_type :json
lines.to_json
end
# ROUTES - Back-end
get '/admin' do
protected!
@range = range
@lines = Line.all :order => :id.desc
haml :admin
end
post '/admin' do
protected!
(1..range[:value]).each do |counter|
line = Line.new
line.content = params["line#{counter}"]
line.save
end
redirect '/admin'
nil
end
get '/admin/delete/:id' do
protected!
line = Line.get params[:id]
line.destroy
redirect '/admin'
nil
end