-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathbootstrap-collabify-api.sh
More file actions
406 lines (342 loc) · 8.63 KB
/
bootstrap-collabify-api.sh
File metadata and controls
406 lines (342 loc) · 8.63 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
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
#!/usr/bin/env bash
set -e
# 1. Create the ruby/ directory and cd into it
mkdir -p ruby && cd ruby
# 2. Initialize a new Gemfile
cat > Gemfile << 'EOF'
source 'https://rubygems.org'
gem 'sinatra', '~> 2.1'
gem 'mongoid', '~> 7.3'
gem 'jwt', '~> 2.6'
gem 'bcrypt', '~> 3.1'
gem 'rack-cors', '~> 1.1'
gem 'dotenv', '~> 3.3'
group :development do
gem 'rerun', '~> 0.14'
gem 'pry'
end
EOF
# 3. Create config.ru to boot the app
cat > config.ru << 'EOF'
require 'dotenv/load'
require './app/app'
run Collabify::App
EOF
# 4. Create .env.example
cat > .env.example << 'EOF'
# MongoDB URI, e.g. mongodb://localhost:27017/collabify
MONGODB_URI=
# JWT secret for signing tokens
JWT_SECRET=
# Auth0 audience (if integrating Auth0 M2M)
AUTH0_AUDIENCE=
EOF
# 5. Mongoid config
mkdir -p config
cat > config/mongoid.yml << 'EOF'
development:
clients:
default:
uri: <%= ENV['MONGODB_URI'] || 'mongodb://localhost:27017/collabify_development' %>
options:
server_selection_timeout: 5
test:
clients:
default:
uri: <%= ENV['MONGODB_URI'] || 'mongodb://localhost:27017/collabify_test' %>
Production:
clients:
default:
uri: <%= ENV['MONGODB_URI'] %>
EOF
# 6. Initializer for JWT
mkdir -p config/initializers
cat > config/initializers/jwt.rb << 'EOF'
require 'jwt'
module Collabify
module Auth
SECRET = ENV.fetch('JWT_SECRET') { 'please_set_me' }
def self.issue(payload, exp = 24*3600)
payload[:exp] = Time.now.to_i + exp
JWT.encode(payload, SECRET, 'HS256')
end
def self.decode(token)
decoded, = JWT.decode(token, SECRET, true, { algorithm: 'HS256' })
decoded
rescue JWT::DecodeError
nil
end
end
end
EOF
# 7. Application entry point
mkdir -p app
cat > app/app.rb << 'EOF'
require 'sinatra/base'
require 'mongoid'
require 'rack/cors'
require 'dotenv/load'
# Load Mongoid config
Mongoid.load!('config/mongoid.yml', ENV['RACK_ENV'] || :development)
# Require all models, controllers
Dir[File.join(__dir__, '{models,controllers,services}/*.rb')].each { |f| require f }
module Collabify
class App < Sinatra::Base
configure do
enable :logging
set :show_exceptions, false
use Rack::Cors do
allow do
origins '*'
resource '*', headers: :any, methods: [:get, :post, :put, :patch, :delete, :options]
end
end
end
before do
pass if request.path_info.start_with?('/auth')
auth_header = request.env['HTTP_AUTHORIZATION']
halt 401, { error: 'Unauthorized' }.to_json unless auth_header && Auth.decode(auth_header.split.last)
@current_user = User.find(Auth.decode(auth_header.split.last)['user_id'])
end
# Mount controllers
use Controllers::AuthController
use Controllers::UsersController
use Controllers::ProjectsController
use Controllers::TasksController
# 404
not_found { content_type :json; halt 404, { error: 'Not Found' }.to_json }
# Error handler
error do
content_type :json
e = env['sinatra.error']
status 500
{ error: e.message }.to_json
end
end
end
EOF
# 8. Models
mkdir -p app/models
cat > app/models/user.rb << 'EOF'
module Collabify
class User
include Mongoid::Document
include Mongoid::Timestamps
field :email, type: String
field :password_digest, type: String
field :role, type: String, default: 'member'
validates :email, presence: true, uniqueness: true
validates :password_digest, presence: true
has_many :projects
has_many :tasks
def password=(pw)
self.password_digest = BCrypt::Password.create(pw)
end
def authenticate(pw)
BCrypt::Password.new(password_digest) == pw
end
end
end
EOF
cat > app/models/project.rb << 'EOF'
module Collabify
class Project
include Mongoid::Document
include Mongoid::Timestamps
field :name, type: String
field :description, type: String
validates :name, presence: true
belongs_to :user
has_many :tasks, dependent: :destroy
end
end
EOF
cat > app/models/task.rb << 'EOF'
module Collabify
class Task
include Mongoid::Document
include Mongoid::Timestamps
field :title, type: String
field :details, type: String
field :completed, type: Boolean, default: false
validates :title, presence: true
belongs_to :project
belongs_to :user
end
end
EOF
# 9. Services (business logic)
mkdir -p app/services
cat > app/services/project_service.rb << 'EOF'
module Collabify
class ProjectService
def initialize(user)
@user = user
end
def list
@user.projects
end
def create(attrs)
@user.projects.create!(attrs)
end
def find(id)
@user.projects.find(id)
end
def update(id, attrs)
p = find(id)
p.update!(attrs)
p
end
def delete(id)
find(id).destroy!
end
end
end
EOF
cat > app/services/task_service.rb << 'EOF'
module Collabify
class TaskService
def initialize(user, project)
@user, @project = user, project
end
def list
@project.tasks
end
def create(attrs)
@project.tasks.create!(attrs.merge(user: @user))
end
def toggle(id)
t = @project.tasks.find(id)
t.update!(completed: !t.completed)
t
end
def update(id, attrs)
t = @project.tasks.find(id)
t.update!(attrs)
t
end
def delete(id)
@project.tasks.find(id).destroy!
end
end
end
EOF
# 10. Controllers
mkdir -p app/controllers
# Auth
cat > app/controllers/auth_controller.rb << 'EOF'
module Collabify
module Controllers
class AuthController < Sinatra::Base
post '/auth/register' do
data = JSON.parse(request.body.read)
user = User.new(email: data['email'])
user.password = data['password']
user.save!
token = Auth.issue(user_id: user.id.to_s)
{ token: token }.to_json
end
post '/auth/login' do
data = JSON.parse(request.body.read)
user = User.where(email: data['email']).first
halt 401, { error: 'Invalid credentials' }.to_json unless user&.authenticate(data['password'])
token = Auth.issue(user_id: user.id.to_s)
{ token: token }.to_json
end
end
end
end
EOF
# Users
cat > app/controllers/users_controller.rb << 'EOF'
module Collabify
module Controllers
class UsersController < Sinatra::Base
get '/users/me' do
content_type :json
@current_user.as_document.except('_id','password_digest').to_json
end
end
end
end
EOF
# Projects
cat > app/controllers/projects_controller.rb << 'EOF'
module Collabify
module Controllers
class ProjectsController < Sinatra::Base
before do
content_type :json
@svc = ProjectService.new(@current_user)
end
get '/projects' do
@svc.list.to_json
end
post '/projects' do
data = JSON.parse(request.body.read)
@svc.create(data).to_json
end
get '/projects/:id' do |id|
@svc.find(id).to_json
end
put '/projects/:id' do |id|
data = JSON.parse(request.body.read)
@svc.update(id, data).to_json
end
delete '/projects/:id' do |id|
@svc.delete(id)
status 204
end
end
end
end
EOF
# Tasks
cat > app/controllers/tasks_controller.rb << 'EOF'
module Collabify
module Controllers
class TasksController < Sinatra::Base
before do
content_type :json
project = Project.find(params['project_id'])
@svc = TaskService.new(@current_user, project)
end
get '/projects/:project_id/tasks' do
@svc.list.to_json
end
post '/projects/:project_id/tasks' do
data = JSON.parse(request.body.read)
@svc.create(data).to_json
end
patch '/projects/:project_id/tasks/:id/toggle' do |proj_id, id|
@svc.toggle(id).to_json
end
put '/projects/:project_id/tasks/:id' do |proj_id, id|
data = JSON.parse(request.body.read)
@svc.update(id, data).to_json
end
delete '/projects/:project_id/tasks/:id' do |proj_id, id|
@svc.delete(id)
status 204
end
end
end
end
EOF
# 11. Rakefile for easy tasks
cat > Rakefile << 'EOF'
require 'rake'
require 'mongoid'
Mongoid.load!('config/mongoid.yml', :development)
namespace :db do
desc 'Drop the development database'
task :drop do
Mongoid::Clients.default.database.drop
puts 'Database dropped'
end
end
EOF
# 12. Bundle install
bundle install
echo "✅ Collabify API scaffold complete in $(pwd)"
echo " • Run with: cd ruby && JWT_SECRET=your_secret MONGODB_URI=... rerun -- rackup config.ru"