This repository has been archived by the owner on Jul 22, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.rb
259 lines (209 loc) · 5.84 KB
/
app.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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
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
256
257
258
259
require 'bundler/setup'
Bundler.require
require 'sinatra/namespace'
require 'sinatra/reloader'
require 'securerandom'
require 'digest/sha1'
require './settings'
ActiveModel::Serializer._root = false
Dir['./models/*.rb', './serializers/*.rb'].each(&method(:require))
ActiveRecord::Base.establish_connection(
adapter: 'sqlite3',
database: 'db/data.sqlite3'
)
Time.zone_default = Time.find_zone!('Tokyo')
Oj.default_options = { mode: :compat }
class MoneyApp < Sinatra::Base
register Sinatra::Namespace
configure do
set :app_file, __FILE__
set :show_exceptions, false
disable :session
use Rack::Session::Cookie,
key: 'rack.session',
expire_after: SESSION_EXPIRE_AFTER,
secret: SESSION_SECRET
use Rack::Parser
end
configure :development do
register Sinatra::Reloader
also_reload './models/*.rb', './serializers/*.rb'
end
STATUS_CODES = {
ok: 200,
created: 201,
no_content: 204,
unauthorized: 401,
bad_request: 400,
not_found: 404,
}.freeze
helpers do
def current_user
User.find_by_id(session[:user_id]) if session[:user_id]
end
def sign_in(user)
session[:user_id] = user.id
end
def sign_out
session.delete(:user_id)
end
def ensure_signed_in!
unless current_user
halt json_with_status(:unauthorized, error: 'Unauthorized')
end
end
def status(code=nil)
return super unless code
code = STATUS_CODES[code] if STATUS_CODES.key?(code)
super(code)
end
def json_with_status(code, hash)
status(code)
json(hash)
end
def json(object, **options)
serializer ||= options.delete(:serializer)
serializer ||= ActiveModel::Serializer.serializer_for(object)
if options.key?(:each_serializer)
options[:serializer] = options[:each_serializer]
end
target = serializer ? serializer.new(object, options).as_json : object
content_type(:json)
Oj.dump(target)
end
def csrf_token
session[:csrf_token] ||= SecureRandom.base64(30)
end
def verified_request?
request.get? || request.head? || env['HTTP_X_CSRF_TOKEN'] == csrf_token
end
def set_csrf_token_to_cookie
response.set_cookie('CSRF-TOKEN',
value: csrf_token,
max_age: 1.week.to_s,
path: '/'
)
end
end
namespace '/api' do
before do
next unless current_user
set_csrf_token_to_cookie
unless verified_request?
halt json_with_status(:bad_request, error: 'Invalid token!')
end
end
namespace '/user' do
get '/?' do
if (user = current_user)
json(user)
else
json_with_status(:not_found, error: 'Not found')
end
end
post '/?' do
if params['name'].present? && User.exists?(name: params['name'])
halt json_with_status(:bad_request,
error: 'This username has already been taken')
end
user = User.new(params.slice('name', 'password'))
if user.save
sign_in(user)
json(user)
else
json_with_status(:bad_request, error: 'Invalid')
end
end
post '/auth' do
user = User.find_by(name: params['name'])
if user && user.valid_password?(params['password'])
sign_in(user)
json(user)
else
sign_out
json_with_status(:bad_request, error: 'Invalid username or password')
end
end
put '/logout' do
sign_out
status :no_content
end
end
namespace '/expenses' do
helpers do
def expense_params
params.slice('subject', 'date', 'amount', 'created_at', 'category_id')
end
end
get '/:year-:month' do
ensure_signed_in!
today = Time.zone.today
year = params.fetch('year', today.year).to_i
month = params.fetch('month', today.month).to_i
beginning = Date.new(year, month, 1)
date_range = beginning..beginning.end_of_month
expenses = current_user.expenses
.where(date: date_range)
.reorder(date: :desc, created_at: :desc)
json(expenses, root: :expenses)
end
get '/:id' do
ensure_signed_in!
expense = current_user.expenses.find(params[:id])
json(expense)
end
post '/?' do
expense = current_user.expenses.new(expense_params)
if expense.save
json_with_status(:created, expense)
else
json_with_status(:bad_request, error: expense.errors.to_a.first)
end
end
put '/:id' do
expense = current_user.expenses.find(params[:id])
if expense.update(expense_params)
json(expense)
else
json_with_status(:bad_request, error: expense.errors.to_a.first)
end
end
delete '/:id' do
ensure_signed_in!
expense = current_user.expenses.find(params[:id])
expense.destroy
status(:no_content)
end
end
namespace '/categories' do
def category_params
params.slice('name')
end
get '/?' do
ensure_signed_in!
categories = current_user.categories.reorder(:name)
json(categories, root: :categories)
end
post '/?' do
ensure_signed_in!
category = current_user.categories.new(category_params)
if category.save
json(category)
else
json_with_status(:bad_request, error: category.errors.to_a.first)
end
end
end
error ActiveRecord::RecordNotFound do
json_with_status(:not_found, error: 'Not found')
end
get '/*' do
json_with_status(:not_found, error: 'Not found')
end
end
if ENV['RACK_ENV'] == 'development'
get '/*' do
send_file File.join('public', 'index.html')
end
end
end