This repository was archived by the owner on Dec 21, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathconfig.ru
More file actions
75 lines (60 loc) · 1.86 KB
/
config.ru
File metadata and controls
75 lines (60 loc) · 1.86 KB
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
require 'sinatra'
require "sinatra/param"
require "json"
set :raise_sinatra_param_exceptions, true
disable :show_exceptions
disable :raise_errors
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 == ['admin@teachable.com', 'secret']
end
end
error Sinatra::Param::InvalidParameterError do
status 422
{error: "#{env['sinatra.error'].param} is invalid/blank"}.to_json
end
error 500 do
"I have been instructed to inform you that 'Shit just got real.'"
end
get "/homepage" do
send_file 'public/homepage.html'
end
##QUERY THE USERS LIST
get "/" do
protected!
File.open("./test-users.json").read
end
##ADD A NEW USER
post "/" do
protected!
param :name, String, required: true
param :email, String, required: true, format: /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/
contents = File.open("./test-users.json").read
parsed_contents = JSON.parse(contents)
File.delete("./test-users.json")
parsed_contents["guests"] << {"email": params["email"], "name": params["name"]}
File.open("./test-users.json", "w+") do |f|
f.puts JSON.pretty_generate(parsed_contents)
end
"#{params['name']} now signed up with #{params['email']}"
end
##DELETE A USER
delete "/:email" do
protected!
param :email, String, required: true
contents = File.open("./test-users.json").read
parsed_contents = JSON.parse(contents)
File.delete("./test-users.json")
parsed_contents["guests"].delete_if {|guest| guest["email"] == params["email"]}
File.open("./test-users.json", "w+") do |f|
f.puts JSON.pretty_generate(parsed_contents)
end
"#{params['email']}has been removed successfully".to_json
end
run Sinatra::Application