slack-ruby-bot-server 2.2.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/README.md CHANGED
@@ -17,9 +17,15 @@ Build a complete Slack bot service with Slack button integration, in Ruby.
17
17
  - [Storage](#storage)
18
18
  - [MongoDB](#mongodb)
19
19
  - [ActiveRecord](#activerecord)
20
+ - [Extending Team](#extending-team)
21
+ - [Mongoid Attributes](#mongoid-attributes)
22
+ - [Active Record Attributes](#active-record-attributes)
23
+ - [Rails Loading and Reloading](#rails-loading-and-reloading)
20
24
  - [OAuth Version and Scopes](#oauth-version-and-scopes)
21
25
  - [Slack App](#slack-app)
22
26
  - [API](#api)
27
+ - [Custom Endpoints](#custom-endpoints)
28
+ - [Team Endpoint Visibility](#team-endpoint-visibility)
23
29
  - [App](#app)
24
30
  - [Service Manager](#service-manager)
25
31
  - [Lifecycle Callbacks](#lifecycle-callbacks)
@@ -27,7 +33,9 @@ Build a complete Slack bot service with Slack button integration, in Ruby.
27
33
  - [Extensions](#extensions)
28
34
  - [Service Class](#service-class)
29
35
  - [HTML Templates](#html-templates)
36
+ - [Page Middleware Configuration](#page-middleware-configuration)
30
37
  - [Access Tokens](#access-tokens)
38
+ - [Testing](#testing)
31
39
  - [Sample Bots Using Slack Ruby Bot Server](#sample-bots-using-slack-ruby-bot-server)
32
40
  - [Copyright & License](#copyright--license)
33
41
 
@@ -37,7 +45,7 @@ A library that contains a web server and a RESTful [Grape](http://github.com/rub
37
45
 
38
46
  ## Stable Release
39
47
 
40
- You're reading the documentation for the **stable** release of slack-ruby-bot-server, v2.2.0. See [UPGRADING](UPGRADING.md) when upgrading from an older version. See [MIGRATING](MIGRATING.md) for help with migrating Legacy Slack Apps to Granular Scopes.
48
+ You're reading the documentation for the **stable** release of slack-ruby-bot-server, 2.3.0. See [UPGRADING](UPGRADING.md) when upgrading from an older version. See [MIGRATING](MIGRATING.md) for help with migrating Legacy Slack Apps to Granular Scopes.
41
49
 
42
50
  ## Make Your Own
43
51
 
@@ -107,6 +115,76 @@ db_config = if Gem::Version.new(Psych::VERSION) >= Gem::Version.new('3.1.0.pre1'
107
115
  ActiveRecord::Base.establish_connection(db_config)
108
116
  ```
109
117
 
118
+ #### Extending Team
119
+
120
+ The installation model is the top-level `::Team` class for both adapters, not `SlackRubyBotServer::Models::Team`. Load `slack-ruby-bot-server` before extending it. The model already includes its database adapter and timestamps; do not include them again or declare a different superclass.
121
+
122
+ ##### Mongoid Attributes
123
+
124
+ Add fields by reopening the existing class in an application file, for example `lib/team_extensions.rb`:
125
+
126
+ ```ruby
127
+ require 'slack-ruby-bot-server'
128
+
129
+ class Team
130
+ field :subscription_plan, type: String, default: 'free'
131
+
132
+ def paid_plan?
133
+ subscription_plan == 'paid'
134
+ end
135
+ end
136
+ ```
137
+
138
+ Require that file from your startup code after loading the framework and before serving requests or starting the service. Mongoid does not require a schema migration for the new field.
139
+
140
+ ##### Active Record Attributes
141
+
142
+ Add a column to the existing `teams` table with an application migration. Use your application's migration version; this example is also compatible with older supported Active Record versions:
143
+
144
+ ```ruby
145
+ class AddSubscriptionPlanToTeams < ActiveRecord::Migration[6.0]
146
+ def change
147
+ add_column :teams, :subscription_plan, :string, default: 'free', null: false
148
+ end
149
+ end
150
+ ```
151
+
152
+ Run the migration before code uses the attribute. Active Record provides its reader and writer from the column; do not use `attr_accessor`, which would bypass persistence. Add methods by reopening `class Team` after loading the framework, as above, but omit the Mongoid-only `field` declaration.
153
+
154
+ ##### Rails Loading and Reloading
155
+
156
+ Putting another `app/models/team.rb` in a Rails app is not a reliable way to extend a class already loaded by a gem. Put reloadable behavior in a concern instead:
157
+
158
+ ```ruby
159
+ # app/models/concerns/team_extensions.rb
160
+ module TeamExtensions
161
+ extend ActiveSupport::Concern
162
+
163
+ def paid_plan?
164
+ subscription_plan == 'paid'
165
+ end
166
+ end
167
+ ```
168
+
169
+ Include it in `::Team` from a reloader callback, rather than autoloading the concern directly during initializer execution:
170
+
171
+ ```ruby
172
+ # config/initializers/team_extensions.rb
173
+ require 'slack-ruby-bot-server'
174
+
175
+ if SlackRubyBotServer.config.mongoid?
176
+ ::Team.field :subscription_plan, type: String, default: 'free'
177
+ end
178
+
179
+ Rails.application.config.to_prepare do
180
+ ::Team.include(TeamExtensions)
181
+ end
182
+ ```
183
+
184
+ With Active Record, use the migration above instead of declaring a field in the initializer. The callback runs at boot and after development reloads; including the same concern more than once is safe. Keep one-time field declarations outside the callback. Do not query the database or swallow database errors just to attach methods: the extension can be loaded before the `teams` table exists.
185
+
186
+ The framework currently owns the global `Team` constant. An unrelated application model with the same name is a separate [name-collision limitation](https://github.com/slack-ruby/slack-ruby-bot-server/pull/83), not an extension mechanism.
187
+
110
188
  ### OAuth Version and Scopes
111
189
 
112
190
  Configure your app's [OAuth version](https://api.slack.com/authentication/oauth-v2) and [scopes](https://api.slack.com/legacy/oauth-scopes) as needed by your application.
@@ -151,6 +229,58 @@ Navigate to either [localhost:9292](http://localhost:9292) or the ngrok URL abov
151
229
 
152
230
  This library implements an app, [SlackRubyBotServer::App](lib/slack-ruby-bot-server/app.rb) and a service manager, [SlackRubyBotServer::Service](lib/slack-ruby-bot-server/service.rb). It also provides [default HTML templates and JS scripts](public) for Slack integration.
153
231
 
232
+ #### Custom Endpoints
233
+
234
+ Set `config.api` to a Rack application, typically a `Grape::API` class, to customize the API without reopening the framework's classes. The default is `nil`, which uses `SlackRubyBotServer::Api::Endpoints::RootEndpoint`, including extensions mounted there by other gems. `SlackRubyBotServer::Config.reset!` restores this default.
235
+
236
+ To add an endpoint alongside the default API:
237
+
238
+ ```ruby
239
+ class ExtraApi < Grape::API
240
+ prefix 'api'
241
+ format :json
242
+
243
+ get :foobar do
244
+ { ok: true }
245
+ end
246
+ end
247
+
248
+ class ApplicationApi < Grape::API
249
+ mount SlackRubyBotServer::Api::Endpoints::RootEndpoint
250
+ mount ExtraApi
251
+ end
252
+
253
+ SlackRubyBotServer.configure do |config|
254
+ config.api = ApplicationApi
255
+ end
256
+ ```
257
+
258
+ Configure this before starting the application. In `config.ru`, continue running `SlackRubyBotServer::Api::Middleware.instance`; both `/api/foobar` and the existing `/api` routes then share the framework's CORS, URL-rewrite, and page middleware. A separate `Rack::Cascade` stack is unnecessary.
259
+
260
+ In Rails, require the file defining `ApplicationApi` from your initializer before assigning `config.api`. For reloadable classes, make the assignment inside `Rails.application.config.to_prepare` so it references the current class. Mount `SlackRubyBotServer::Api::Middleware.instance` in your routes, for example `mount SlackRubyBotServer::Api::Middleware.instance => '/'`, rather than bypassing that middleware stack.
261
+
262
+ #### Team Endpoint Visibility
263
+
264
+ The default API exposes `GET /api/teams` and `GET /api/teams/:id` publicly. To retain OAuth registration without those read endpoints, use the separately mountable `TeamsEndpoint::Create`. `TeamsEndpoint::Read` contains the list and detail routes; `TeamsEndpoint` continues to mount both for backward compatibility.
265
+
266
+ ```ruby
267
+ class RegistrationApi < Grape::API
268
+ include SlackRubyBotServer::Api::Helpers::ErrorHelpers
269
+
270
+ prefix 'api'
271
+ format :json
272
+ formatter :json, Grape::Formatter::Roar
273
+
274
+ mount SlackRubyBotServer::Api::Endpoints::TeamsEndpoint::Create
275
+ end
276
+
277
+ SlackRubyBotServer.configure do |config|
278
+ config.api = RegistrationApi
279
+ end
280
+ ```
281
+
282
+ This replaces the default root API: it does not expose its status, root discovery, Swagger, or team-read routes. Do not also mount `RootEndpoint` or `TeamsEndpoint`, since either would restore the public team reads. If you use the Events extension or other custom endpoints, explicitly mount their routes with their required signature verification too. Add your own authentication before mounting `TeamsEndpoint::Read` if you need protected team queries. OAuth registration still requires a valid Slack authorization code; this configuration does not add a general authentication layer.
283
+
154
284
  #### App
155
285
 
156
286
  The app instance checks for a working database connection, ensures indexes, performs migrations, sets up bot aliases and log levels. You can introduce custom behavior into the app lifecycle by subclassing `SlackRubyBotServer::App` and creating an instance of the child class in `config.ru`.
@@ -307,10 +437,51 @@ SlackRubyBotServer.configure do |config|
307
437
  end
308
438
  ```
309
439
 
440
+ #### Page Middleware Configuration
441
+
442
+ Use `config.server_pages` to configure the underlying [`Rack::ServerPages`](https://github.com/migrs/rack-server-pages) middleware in an initializer, before `SlackRubyBotServer::Api::Middleware.instance` is first accessed. The block receives its configuration object after the framework applies `view_paths`, so it can customize any option supported by your installed `rack-server-pages` version.
443
+
444
+ For example, with `rack-server-pages` 0.3.0 or newer:
445
+
446
+ ```ruby
447
+ SlackRubyBotServer.configure do |config|
448
+ config.server_pages do |pages|
449
+ pages.cache_control = 'private, no-cache'
450
+ pages.static_cache_control = 'public, no-cache'
451
+ end
452
+ end
453
+ ```
454
+
455
+ `cache_control` sets the default `Cache-Control` header for rendered templates, including generated CSS. `static_cache_control` sets it for static files. `no-cache` allows storage but requires revalidation before reuse; use `private, no-store` for sensitive pages. You can also configure `static_etags` and `static_timestamps` with version 0.3.0 or newer. These settings do not change downstream API responses.
456
+
457
+ Without a block, the framework preserves the installed library's defaults and existing `view_paths` behavior. Registering another block replaces the previous one, and `SlackRubyBotServer::Config.reset!` clears it. The block runs when the middleware stack is built, not on each request. If you change configuration after initialization, rebuild the stack with `SlackRubyBotServer::Api::Middleware.reset!`; configure it before startup in production.
458
+
310
459
  ### Access Tokens
311
460
 
312
461
  By default the implementation of [Team](lib/slack-ruby-bot-server/models/team) stores the value of the token with all the requested OAuth scopes in both `token` and `activated_user_access_token` (for backwards compatibility), along with `oauth_version` and `oauth_scope`. If a legacy Slack bot integration `bot_access_token` is present, it is stored as `token`, and `activated_user_access_token` is the token that has all the requested OAuth scopes.
313
462
 
463
+ ## Testing
464
+
465
+ The optional test helpers use [Fabrication](https://fabricationgem.org/) and Faker. Add `fabrication` and `faker` to your application's test dependencies; neither is a runtime dependency of this gem.
466
+
467
+ To use the framework's installation defaults without reserving your application's `:team` fabricator name, load the prefixed-only helper:
468
+
469
+ ```ruby
470
+ require 'slack-ruby-bot-server/rspec/fabricators'
471
+
472
+ team = Fabricate(:slack_ruby_bot_server_team)
473
+ ```
474
+
475
+ This fabricator creates the existing `::Team` model with unique token/team ID sequences and a generated name. Applications can register their own `:team` before or after this helper, or inherit the framework defaults:
476
+
477
+ ```ruby
478
+ Fabricator(:team, from: :slack_ruby_bot_server_team) do
479
+ name { 'My application team' }
480
+ end
481
+ ```
482
+
483
+ The existing `require 'slack-ruby-bot-server/rspec'` remains supported. It loads the prefixed fabricator and registers the legacy `:team` alias only when no `:team` definition already exists. If your application defines `:team` later, replace the legacy require with `slack-ruby-bot-server/rspec/fabricators`; loading both entry points still opts into the legacy alias.
484
+
314
485
  ## Sample Bots Using Slack Ruby Bot Server
315
486
 
316
487
  * [slack-ruby-bot-server-events-sample](https://github.com/slack-ruby/slack-ruby-bot-server-events-sample), a generic sample
data/RELEASING.md CHANGED
@@ -4,19 +4,25 @@ There're no hard rules about when to release slack-ruby-bot-server. Release bug
4
4
 
5
5
  ### Release
6
6
 
7
- Run tests, check that all tests succeed locally.
7
+ Start from a clean, up-to-date canonical checkout on `master`. Confirm that the version in `lib/slack-ruby-bot-server/version.rb` matches the next changelog heading and has not already been published on RubyGems or tagged in Git.
8
8
 
9
- ```
9
+ Run the tests against dedicated local test databases as described in [CONTRIBUTING.md](CONTRIBUTING.md). Set the adapter and version selectors before installing dependencies. For example, with Ruby 4 and MongoDB running locally:
10
+
11
+ ```sh
12
+ export DATABASE_ADAPTER=mongoid MONGOID_VERSION='~> 9.1' GRAPE_VERSION='~> 4.0' JSON_VERSION='~> 3.0'
13
+ export DATABASE_URL=mongodb://localhost/slack_ruby_bot_server_test
10
14
  bundle install
11
- rake
15
+ bundle exec rake
12
16
  ```
13
17
 
14
- Check that the last build succeeded in [Github Actions](https://github.com/slack-ruby/slack-ruby-bot-server/actions) for all supported platforms.
18
+ Also validate the Active Record adapter with its own test database. Do not run adapter suites concurrently on one host; browser tests share port 9293. Never use a production database.
19
+
20
+ Check that [GitHub Actions](https://github.com/slack-ruby/slack-ruby-bot-server/actions) succeeded for the release commit across both database matrices and RuboCop. A successful build for a different commit is not sufficient.
15
21
 
16
22
  Change "Next" in [CHANGELOG.md](CHANGELOG.md) to the current date.
17
23
 
18
24
  ```
19
- ### 2.0.1 (2023/02/20)
25
+ ### 2.2.1 (2026/10/24)
20
26
  ```
21
27
 
22
28
  Remove the line with "Your contribution here.", since there will be no more contributions to this release.
@@ -26,34 +32,36 @@ Change `**next**` in the "Stable Release" section in README that warns users tha
26
32
  ```
27
33
  ## Stable Release
28
34
 
29
- You're reading the documentation for the **stable** release of slack-ruby-bot-server, 2.0.1. See [UPGRADING](UPGRADING.md) when upgrading from an older version.
35
+ You're reading the documentation for the **stable** release of slack-ruby-bot-server, 2.2.1. See [UPGRADING](UPGRADING.md) when upgrading from an older version. See [MIGRATING](MIGRATING.md) for help with migrating Legacy Slack Apps to Granular Scopes.
30
36
  ```
31
37
 
32
38
  Commit your changes.
33
39
 
34
40
  ```
35
- git add README.md CHANGELOG.md
36
- git commit -m "Preparing for release, 2.0.1."
41
+ git add README.md CHANGELOG.md RELEASING.md
42
+ git commit -m "Preparing for release, 2.2.1."
37
43
  git push origin master
38
44
  ```
39
45
 
40
- Release.
46
+ Wait for the release commit's GitHub Actions checks to succeed before publishing.
41
47
 
42
- ```
43
- $ rake release
48
+ RubyGems publishing requires a maintainer's credentials and may require a fresh one-time password (OTP). For an agent-assisted release, ask the maintainer for the OTP immediately before publishing, after tests, commits, and CI are complete. Use it only for the publishing process; never put OTPs or API keys in committed files, release notes, or logs.
49
+
50
+ Pass the temporary code through `GEM_HOST_OTP_CODE`. With `OTP` holding the freshly supplied code:
44
51
 
45
- slack-ruby-bot-server 2.0.1 built to pkg/slack-ruby-bot-server-2.0.1.gem.
46
- Tagged v2.0.1.
47
- Pushed git commits and tags.
48
- Pushed slack-ruby-bot-server 2.0.1 to rubygems.org.
52
+ ```sh
53
+ GEM_HOST_OTP_CODE="$OTP" bundle exec rake release
54
+ unset OTP
49
55
  ```
50
56
 
57
+ The release task builds the gem in `pkg/`, tags the release, pushes commits and the tag, and publishes to RubyGems. Confirm that the remote tag points to the release commit and that RubyGems lists the expected version before proceeding. If publishing fails, inspect which steps completed before retrying; do not move an existing release tag or overwrite a published version.
58
+
51
59
  ### Prepare for the Next Version
52
60
 
53
61
  Add the next release to [CHANGELOG.md](CHANGELOG.md).
54
62
 
55
63
  ```
56
- ### 2.0.2 (Next)
64
+ ### 2.2.2 (Next)
57
65
 
58
66
  * Your contribution here.
59
67
  ```
@@ -65,13 +73,13 @@ Undo your change in README about the stable release.
65
73
  ```
66
74
  ## Stable Release
67
75
 
68
- You're reading the documentation for the **next** release of slack-ruby-bot-server. Please see the documentation for the [last stable release, v2.0.1](https://github.com/slack-ruby/slack-ruby-bot-server/blob/v2.0.1/README.md) unless you're integrating with HEAD. See [UPGRADING](UPGRADING.md) when upgrading from an older version. See [MIGRATING](MIGRATING.md) for help with migrating Legacy Slack Apps to Granular Scopes.
76
+ You're reading the documentation for the **next** release of slack-ruby-bot-server. Please see the documentation for the [last stable release, v2.2.1](https://github.com/slack-ruby/slack-ruby-bot-server/blob/v2.2.1/README.md) unless you're integrating with HEAD. See [UPGRADING](UPGRADING.md) when upgrading from an older version. See [MIGRATING](MIGRATING.md) for help with migrating Legacy Slack Apps to Granular Scopes.
69
77
  ```
70
78
 
71
79
  Commit your changes.
72
80
 
73
81
  ```
74
82
  git add README.md CHANGELOG.md lib/slack-ruby-bot-server/version.rb
75
- git commit -m "Preparing for next development iteration, 2.0.2."
83
+ git commit -m "Preparing for next development iteration, 2.2.2."
76
84
  git push origin master
77
85
  ```
data/UPGRADING.md CHANGED
@@ -1,6 +1,30 @@
1
1
  Upgrading Slack-Ruby-Bot-Server
2
2
  ===============================
3
3
 
4
+ ### Upgrading to >= 2.3.0
5
+
6
+ #### Recommended Test Helper Migration
7
+
8
+ If your application defines its own `:team` fabricator, replace `require 'slack-ruby-bot-server/rspec'` with `require 'slack-ruby-bot-server/rspec/fabricators'`. This is recommended, not required: the new entry point registers only `:slack_ruby_bot_server_team`, leaving `:team` available regardless of whether your application's fabricator is loaded before or after the helper.
9
+
10
+ Use `Fabricate(:slack_ruby_bot_server_team)` for the framework defaults, or inherit them in your application's fabricator:
11
+
12
+ ```ruby
13
+ require 'slack-ruby-bot-server/rspec/fabricators'
14
+
15
+ Fabricator(:team, from: :slack_ruby_bot_server_team) do
16
+ name { 'My application team' }
17
+ end
18
+ ```
19
+
20
+ The legacy helper remains supported and registers `:team` only if no definition already exists. Replace the old require rather than adding the new one alongside it; loading both still opts into the legacy alias and can conflict with a `:team` definition loaded later.
21
+
22
+ #### Status Checks and Inactive Installations
23
+
24
+ `GET /api/status` now pings only active installations. When Slack returns `account_inactive` or `invalid_auth`, the installation is deactivated through `Service#deactivate!`, and the endpoint returns HTTP `200` with `ping: { "ok": false, "error": "account_inactive" }` (or `"invalid_auth"`). The active-team count reflects that deactivation. Monitoring should inspect the failed `ping` as well as the HTTP status.
25
+
26
+ When no active installations remain, no Slack ping is attempted. Other Slack errors retain their existing error response and do not deactivate installations.
27
+
4
28
  ### Upgrading to >= 2.2.0
5
29
 
6
30
  #### Cursor Helper Iterator Changes
@@ -2,118 +2,129 @@ module SlackRubyBotServer
2
2
  module Api
3
3
  module Endpoints
4
4
  class TeamsEndpoint < Grape::API
5
- format :json
6
- helpers Helpers::CursorHelpers
7
- helpers Helpers::SortHelpers
8
- helpers Helpers::PaginationParameters
9
-
10
- namespace :teams do
11
- desc 'Get a team.'
12
- params do
13
- requires :id, type: String, desc: 'Team ID.'
14
- end
15
- get ':id' do
16
- team = Team.find(params[:id]) || error!('Not Found', 404)
17
- present team, with: Presenters::TeamPresenter
18
- end
5
+ class Read < Grape::API
6
+ format :json
7
+ helpers Helpers::CursorHelpers
8
+ helpers Helpers::SortHelpers
9
+ helpers Helpers::PaginationParameters
19
10
 
20
- desc 'Get all the teams.'
21
- params do
22
- optional :active, type: ::Grape::API::Boolean, desc: 'Return active teams only.'
23
- use :pagination
24
- end
25
- sort Team::SORT_ORDERS
26
- get do
27
- teams = Team.all
28
- teams = teams.active if params[:active]
29
- teams = paginate_and_sort_by_cursor(teams, default_sort_order: '-id')
30
- present teams, with: Presenters::TeamsPresenter
31
- end
11
+ namespace :teams do
12
+ desc 'Get a team.'
13
+ params do
14
+ requires :id, type: String, desc: 'Team ID.'
15
+ end
16
+ get ':id' do
17
+ team = Team.find(params[:id]) || error!('Not Found', 404)
18
+ present team, with: Presenters::TeamPresenter
19
+ end
32
20
 
33
- desc 'Create a team using an OAuth token.'
34
- params do
35
- requires :code, type: String
36
- optional :state, type: String
37
- end
38
- post do
39
- client = Slack::Web::Client.new
40
-
41
- raise 'Missing SLACK_CLIENT_ID or SLACK_CLIENT_SECRET.' unless ENV.key?('SLACK_CLIENT_ID') && ENV.key?('SLACK_CLIENT_SECRET')
42
-
43
- options = {
44
- client_id: ENV.fetch('SLACK_CLIENT_ID', nil),
45
- client_secret: ENV.fetch('SLACK_CLIENT_SECRET', nil),
46
- code: params[:code]
47
- }
48
-
49
- rc = client.send(SlackRubyBotServer.config.oauth_access_method, options)
50
-
51
- token = nil
52
- access_token = nil
53
- user_id = nil
54
- bot_user_id = nil
55
- team_id = nil
56
- team_name = nil
57
- oauth_scope = nil
58
- oauth_version = SlackRubyBotServer::Config.oauth_version
59
-
60
- case oauth_version
61
- when :v2
62
- access_token = rc.access_token
63
- token = rc.access_token
64
- user_id = rc.authed_user&.id
65
- bot_user_id = rc.bot_user_id
66
- team_id = rc.team&.id
67
- team_name = rc.team&.name
68
- oauth_scope = rc.scope
69
- when :v1
70
- access_token = rc.access_token
71
- bot = rc.bot if rc.key?(:bot)
72
- token = bot ? bot.bot_access_token : access_token
73
- user_id = rc.user_id
74
- bot_user_id = bot ? bot.bot_user_id : nil
75
- team_id = rc.team_id
76
- team_name = rc.team_name
77
- oauth_scope = rc.scope
21
+ desc 'Get all the teams.'
22
+ params do
23
+ optional :active, type: ::Grape::API::Boolean, desc: 'Return active teams only.'
24
+ use :pagination
25
+ end
26
+ sort Team::SORT_ORDERS
27
+ get do
28
+ teams = Team.all
29
+ teams = teams.active if params[:active]
30
+ teams = paginate_and_sort_by_cursor(teams, default_sort_order: '-id')
31
+ present teams, with: Presenters::TeamsPresenter
78
32
  end
33
+ end
34
+ end
35
+
36
+ class Create < Grape::API
37
+ format :json
79
38
 
80
- team = Team.where(token: token).first
81
- team ||= Team.where(team_id: team_id, oauth_version: oauth_version).first
82
- team ||= Team.where(team_id: team_id).first
83
-
84
- if team
85
- team.ping_if_active!
86
-
87
- team.update!(
88
- oauth_version: oauth_version,
89
- oauth_scope: oauth_scope,
90
- activated_user_id: user_id,
91
- activated_user_access_token: access_token,
92
- bot_user_id: bot_user_id
93
- )
94
-
95
- raise "Team #{team.name} is already registered." if team.active?
96
-
97
- team.activate!(token)
98
- else
99
- team = Team.create!(
100
- token: token,
101
- oauth_version: oauth_version,
102
- oauth_scope: oauth_scope,
103
- team_id: team_id,
104
- name: team_name,
105
- activated_user_id: user_id,
106
- activated_user_access_token: access_token,
107
- bot_user_id: bot_user_id
108
- )
39
+ namespace :teams do
40
+ desc 'Create a team using an OAuth token.'
41
+ params do
42
+ requires :code, type: String
43
+ optional :state, type: String
109
44
  end
45
+ post do
46
+ client = Slack::Web::Client.new
47
+
48
+ raise 'Missing SLACK_CLIENT_ID or SLACK_CLIENT_SECRET.' unless ENV.key?('SLACK_CLIENT_ID') && ENV.key?('SLACK_CLIENT_SECRET')
110
49
 
111
- options = params.slice(:state)
50
+ options = {
51
+ client_id: ENV.fetch('SLACK_CLIENT_ID', nil),
52
+ client_secret: ENV.fetch('SLACK_CLIENT_SECRET', nil),
53
+ code: params[:code]
54
+ }
112
55
 
113
- Service.instance.create!(team, options)
114
- present team, with: Presenters::TeamPresenter
56
+ rc = client.send(SlackRubyBotServer.config.oauth_access_method, options)
57
+
58
+ token = nil
59
+ access_token = nil
60
+ user_id = nil
61
+ bot_user_id = nil
62
+ team_id = nil
63
+ team_name = nil
64
+ oauth_scope = nil
65
+ oauth_version = SlackRubyBotServer::Config.oauth_version
66
+
67
+ case oauth_version
68
+ when :v2
69
+ access_token = rc.access_token
70
+ token = rc.access_token
71
+ user_id = rc.authed_user&.id
72
+ bot_user_id = rc.bot_user_id
73
+ team_id = rc.team&.id
74
+ team_name = rc.team&.name
75
+ oauth_scope = rc.scope
76
+ when :v1
77
+ access_token = rc.access_token
78
+ bot = rc.bot if rc.key?(:bot)
79
+ token = bot ? bot.bot_access_token : access_token
80
+ user_id = rc.user_id
81
+ bot_user_id = bot ? bot.bot_user_id : nil
82
+ team_id = rc.team_id
83
+ team_name = rc.team_name
84
+ oauth_scope = rc.scope
85
+ end
86
+
87
+ team = Team.where(token: token).first
88
+ team ||= Team.where(team_id: team_id, oauth_version: oauth_version).first
89
+ team ||= Team.where(team_id: team_id).first
90
+
91
+ if team
92
+ team.ping_if_active!
93
+
94
+ team.update!(
95
+ oauth_version: oauth_version,
96
+ oauth_scope: oauth_scope,
97
+ activated_user_id: user_id,
98
+ activated_user_access_token: access_token,
99
+ bot_user_id: bot_user_id
100
+ )
101
+
102
+ raise "Team #{team.name} is already registered." if team.active?
103
+
104
+ team.activate!(token)
105
+ else
106
+ team = Team.create!(
107
+ token: token,
108
+ oauth_version: oauth_version,
109
+ oauth_scope: oauth_scope,
110
+ team_id: team_id,
111
+ name: team_name,
112
+ activated_user_id: user_id,
113
+ activated_user_access_token: access_token,
114
+ bot_user_id: bot_user_id
115
+ )
116
+ end
117
+
118
+ options = params.slice(:state)
119
+
120
+ Service.instance.create!(team, options)
121
+ present team, with: Presenters::TeamPresenter
122
+ end
115
123
  end
116
124
  end
125
+
126
+ mount Read
127
+ mount Create
117
128
  end
118
129
  end
119
130
  end
@@ -10,42 +10,42 @@ module SlackRubyBotServer
10
10
  Middleware.logger.error "#{e.class.name}: #{e.message}\n #{backtrace}"
11
11
  error = { type: 'other_error', message: e.message }
12
12
  error[:backtrace] = backtrace
13
- rack_response(error.to_json, 400)
13
+ error!(error, 400)
14
14
  end
15
15
  # rescue document validation errors into detail json
16
16
  if SlackRubyBotServer::Config.mongoid?
17
17
  rescue_from Mongoid::Errors::Validations do |e|
18
18
  backtrace = e.backtrace[0..5].join("\n ")
19
19
  Middleware.logger.warn "#{e.class.name}: #{e.message}\n #{backtrace}"
20
- rack_response({
21
- type: 'param_error',
22
- message: e.document.errors.full_messages.uniq.join(', ') + '.',
23
- detail: e.document.errors.messages.each_with_object({}) do |(k, v), h|
24
- h[k] = v.uniq
25
- end
26
- }.to_json, 400)
20
+ error!({
21
+ type: 'param_error',
22
+ message: e.document.errors.full_messages.uniq.join(', ') + '.',
23
+ detail: e.document.errors.messages.each_with_object({}) do |(k, v), h|
24
+ h[k] = v.uniq
25
+ end
26
+ }, 400)
27
27
  end
28
28
  end
29
29
  rescue_from Grape::Exceptions::Validation do |e|
30
30
  backtrace = e.backtrace[0..5].join("\n ")
31
31
  Middleware.logger.warn "#{e.class.name}: #{e.message}\n #{backtrace}"
32
- rack_response({
33
- type: 'param_error',
34
- message: 'Invalid parameters.',
35
- detail: { e.params.join(', ') => [e.message] }
36
- }.to_json, 400)
32
+ error!({
33
+ type: 'param_error',
34
+ message: 'Invalid parameters.',
35
+ detail: { e.params.join(', ') => [e.message] }
36
+ }, 400)
37
37
  end
38
38
  rescue_from Grape::Exceptions::ValidationErrors do |e|
39
39
  backtrace = e.backtrace[0..5].join("\n ")
40
40
  Middleware.logger.warn "#{e.class.name}: #{e.message}\n #{backtrace}"
41
- rack_response({
42
- type: 'param_error',
43
- message: 'Invalid parameters.',
44
- detail: e.errors.each_with_object({}) do |(k, v), h|
45
- # JSON does not permit having a key of type Array
46
- h[k.count == 1 ? k.first : k.join(', ')] = v
47
- end
48
- }.to_json, 400)
41
+ error!({
42
+ type: 'param_error',
43
+ message: 'Invalid parameters.',
44
+ detail: e.errors.each_with_object({}) do |(k, v), h|
45
+ # JSON does not permit having a key of type Array
46
+ h[k.count == 1 ? k.first : k.join(', ')] = v
47
+ end
48
+ }, 400)
49
49
  end
50
50
  end
51
51
  end
@@ -30,6 +30,7 @@ module SlackRubyBotServer
30
30
 
31
31
  use Rack::ServerPages do |config|
32
32
  config.view_path = SlackRubyBotServer::Config.view_paths
33
+ SlackRubyBotServer::Config.server_pages&.call(config)
33
34
  end
34
35
 
35
36
  run Middleware.new
@@ -37,7 +38,7 @@ module SlackRubyBotServer
37
38
  end
38
39
 
39
40
  def call(env)
40
- Endpoints::RootEndpoint.call(env)
41
+ (SlackRubyBotServer::Config.api || Endpoints::RootEndpoint).call(env)
41
42
  end
42
43
  end
43
44
  end