-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshrtn.rb
110 lines (95 loc) · 2.29 KB
/
shrtn.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
105
106
107
108
109
110
require 'sinatra'
require 'redis'
require 'sinatra/flash'
configure do
SiteConfig = OpenStruct.new(
:title => 'shrtn » url shortener',
:author => 'Denny Mueller',
:url_base => 'http://localhost:4567/', # the url of your application
:username => 'admin',
:token => 'maketh1$longandh@rdtoremember',
:password => 'password'
)
end
enable :sessions
set :session_secret, '*&(^B234'
r = Redis.new
helpers do
include Rack::Utils
alias_method :h, :escape_html
def random_string(length)
rand(36**length).to_s(36)
end
def get_site_url(short_url)
SiteConfig.url_base + short_url
end
def admin?
request.cookies[SiteConfig.username] == SiteConfig.token
end
def protected!
redirect '/login' unless admin?
end
end
get '/' do
erb :index
end
post '/' do
if params[:url] and not params[:url].empty?
unless params[:url] =~ /[a-zA-Z]+:\/\/.*/
seconds = 60
unless params[:url] =~ /\+(\d+)min/
expire = 259200 # seconds have 3 days
else
expire = params[:url].match(/\+(\d+)min/)[1]
end
params[:url] = "http://#{params[:url]}".gsub(/\+(\d+)min/,"")
expire = expire.to_i*seconds
end
@shortcode = random_string 5
r.MULTI do
r.SET "links:#{@shortcode}", params[:url], :nx => true, :ex => expire
r.SET "clicks:#{@shortcode}", "0", :nx => true, :ex => expire
end
end
erb :index
end
get '/login' do
erb :login
end
post '/login' do
if params[:username]==SiteConfig.username&¶ms[:password]==SiteConfig.password
response.set_cookie(SiteConfig.username,SiteConfig.token)
redirect '/admin'
else
flash[:error] = "Wrong Login Data!"
redirect '/admin'
end
end
get '/logout' do
response.set_cookie(SiteConfig.username, false)
redirect '/'
end
get '/admin' do
protected!
seconds = 60
@count = r.EVAL("return #redis.call('keys', 'links:*')")
@url_shortcodes = r.KEYS("links:*")
@clicks = [] ; @urls = [] ; @timeouts = [] #init arrays
@url_shortcodes.each do |shortcode|
shortcode.slice! "links:"
@urls << r.GET("links:#{shortcode}")
@clicks << r.GET("clicks:#{shortcode}")
@timeouts << r.TTL("links:#{shortcode}"))/seconds
end
erb :admin
end
get '/:shortcode' do
@url = r.GET "links:#{params[:shortcode]}"
r.INCR "clicks:#{params[:shortcode]}"
redirect @url
else
flash[:error] = "Ups, Something went wrong!"
redirect '/'
end
end