forked from adnanh/mikro
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mikro.rb
128 lines (106 loc) · 2.36 KB
/
mikro.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
require 'sinatra'
require_relative 'lib/init'
use Rack::Session::Cookie, CONFIG['cookie']
helpers do
def escape(text)
Rack::Utils.escape_html(text)
end
end
not_found do
erb :not_found
end
get '/' do
posts = Post.order(Sequel.desc(:created_at))
posts_by_year = posts.all.group_by { |post| post[:created_at].year.to_s }
posts_by_year.each { |year, posts| posts_by_year[year] = posts.group_by { |post| post[:created_at].strftime('%B') } }
erb :index, locals: {posts_by_year: posts_by_year, all_posts: posts}
end
get '/post/new' do
if session[:logged_in]
erb :new_post, locals: {body: params[:body]}
else
session[:return_url] = "/post/new?body=#{URI.escape(params[:body])}"
redirect '/login'
end
end
get '/post/:id' do
post = Post.where(:id => params[:id].to_i).first
if post.nil?
404
else
erb :post, locals: {post: post}
end
end
get '/post/:id/update' do
if session[:logged_in]
post = Post.where(:id => params[:id].to_i).first
if post.nil?
404
else
erb :update_post, locals: {post: post}
end
else
session[:return_url] = "/post/#{params[:id].to_i}/update"
redirect '/login'
end
end
get '/post/:id/delete' do
if session[:logged_in]
affected = Post.where(:id => params[:id].to_i).delete
if affected == 0
404
else
redirect '/'
end
else
session[:return_url] = "/post/#{params[:id].to_i}/delete"
redirect '/login'
end
end
get '/login' do
if session[:logged_in]
redirect '/'
else
erb :login, locals: {error: params[:error]}
end
end
get '/logout' do
if session[:logged_in]
session.clear
end
redirect '/'
end
post '/post' do
if session[:logged_in]
unless params[:body].nil? || params[:body].empty?
post = Post.new
post.body = params[:body]
post.save
end
end
redirect '/'
end
post '/post/:id' do
if session[:logged_in]
post = Post.where(:id => params[:id].to_i).first
unless post.nil?
post.update({body: params[:body]})
post.save
end
end
redirect '/'
end
post '/login' do
if params[:password] == CONFIG['settings']['password']
session[:logged_in] = true
return_url = session[:return_url]
if return_url.nil? || return_url.empty?
redirect '/'
else
session.delete :return_url
redirect return_url
end
else
redirect '/login?error=true'
end
end