]> git.openstreetmap.org Git - rails.git/blob - config/initializers/doorkeeper.rb
Make database_offline mode work
[rails.git] / config / initializers / doorkeeper.rb
1 # frozen_string_literal: true
2
3 Rails.application.reloader.to_prepare do
4   Doorkeeper.configure do
5     # Change the ORM that doorkeeper will use (requires ORM extensions installed).
6     # Check the list of supported ORMs here: https://github.com/doorkeeper-gem/doorkeeper#orms
7     orm :active_record
8
9     # This block will be called to check whether the resource owner is authenticated or not.
10     resource_owner_authenticator do
11       current_user
12     end
13
14     # If you didn't skip applications controller from Doorkeeper routes in your application routes.rb
15     # file then you need to declare this block in order to restrict access to the web interface for
16     # adding oauth authorized applications. In other case it will return 403 Forbidden response
17     # every time somebody will try to access the admin web interface.
18
19     admin_authenticator do
20       current_user
21     end
22
23     # You can use your own model classes if you need to extend (or even override) default
24     # Doorkeeper models such as `Application`, `AccessToken` and `AccessGrant.
25     #
26     # Be default Doorkeeper ActiveRecord ORM uses it's own classes:
27     #
28     # access_token_class "Doorkeeper::AccessToken"
29     # access_grant_class "Doorkeeper::AccessGrant"
30     # application_class "Doorkeeper::Application"
31     #
32     # Don't forget to include Doorkeeper ORM mixins into your custom models:
33     #
34     #   *  ::Doorkeeper::Orm::ActiveRecord::Mixins::AccessToken - for access token
35     #   *  ::Doorkeeper::Orm::ActiveRecord::Mixins::AccessGrant - for access grant
36     #   *  ::Doorkeeper::Orm::ActiveRecord::Mixins::Application - for application (OAuth2 clients)
37     #
38     # For example:
39     #
40     # access_token_class "MyAccessToken"
41     #
42     # class MyAccessToken < ApplicationRecord
43     #   include ::Doorkeeper::Orm::ActiveRecord::Mixins::AccessToken
44     #
45     #   self.table_name = "hey_i_wanna_my_name"
46     #
47     #   def destroy_me!
48     #     destroy
49     #   end
50     # end
51
52     application_class "Oauth2Application" unless Settings.status == "database_offline"
53
54     # Enables polymorphic Resource Owner association for Access Tokens and Access Grants.
55     # By default this option is disabled.
56     #
57     # Make sure you properly setup you database and have all the required columns (run
58     # `bundle exec rails generate doorkeeper:enable_polymorphic_resource_owner` and execute Rails
59     # migrations).
60     #
61     # If this option enabled, Doorkeeper will store not only Resource Owner primary key
62     # value, but also it's type (class name). See "Polymorphic Associations" section of
63     # Rails guides: https://guides.rubyonrails.org/association_basics.html#polymorphic-associations
64     #
65     # [NOTE] If you apply this option on already existing project don't forget to manually
66     # update `resource_owner_type` column in the database and fix migration template as it will
67     # set NOT NULL constraint for Access Grants table.
68     #
69     # use_polymorphic_resource_owner
70
71     # If you are planning to use Doorkeeper in Rails 5 API-only application, then you might
72     # want to use API mode that will skip all the views management and change the way how
73     # Doorkeeper responds to a requests.
74     #
75     # api_only
76
77     # Enforce token request content type to application/x-www-form-urlencoded.
78     # It is not enabled by default to not break prior versions of the gem.
79
80     enforce_content_type
81
82     # Authorization Code expiration time (default: 10 minutes).
83     #
84     # authorization_code_expires_in 10.minutes
85
86     # Access token expiration time (default: 2 hours).
87     # If you want to disable expiration, set this to `nil`.
88
89     access_token_expires_in nil
90
91     # Assign custom TTL for access tokens. Will be used instead of access_token_expires_in
92     # option if defined. In case the block returns `nil` value Doorkeeper fallbacks to
93     # +access_token_expires_in+ configuration option value. If you really need to issue a
94     # non-expiring access token (which is not recommended) then you need to return
95     # Float::INFINITY from this block.
96     #
97     # `context` has the following properties available:
98     #
99     #   * `client` - the OAuth client application (see Doorkeeper::OAuth::Client)
100     #   * `grant_type` - the grant type of the request (see Doorkeeper::OAuth)
101     #   * `scopes` - the requested scopes (see Doorkeeper::OAuth::Scopes)
102     #   * `resource_owner` - authorized resource owner instance (if present)
103     #
104     # custom_access_token_expires_in do |context|
105     #   context.client.additional_settings.implicit_oauth_expiration
106     # end
107
108     # Use a custom class for generating the access token.
109     # See https://doorkeeper.gitbook.io/guides/configuration/other-configurations#custom-access-token-generator
110     #
111     # access_token_generator '::Doorkeeper::JWT'
112
113     # The controller +Doorkeeper::ApplicationController+ inherits from.
114     # Defaults to +ActionController::Base+ unless +api_only+ is set, which changes the default to
115     # +ActionController::API+. The return value of this option must be a stringified class name.
116     # See https://doorkeeper.gitbook.io/guides/configuration/other-configurations#custom-controllers
117
118     base_controller "ApplicationController"
119
120     # Reuse access token for the same resource owner within an application (disabled by default).
121     #
122     # This option protects your application from creating new tokens before old valid one becomes
123     # expired so your database doesn't bloat. Keep in mind that when this option is `on` Doorkeeper
124     # doesn't updates existing token expiration time, it will create a new token instead.
125     # Rationale: https://github.com/doorkeeper-gem/doorkeeper/issues/383
126     #
127     # You can not enable this option together with +hash_token_secrets+.
128
129     reuse_access_token
130
131     # In case you enabled `reuse_access_token` option Doorkeeper will try to find matching
132     # token using `matching_token_for` Access Token API that searches for valid records
133     # in batches in order not to pollute the memory with all the database records. By default
134     # Doorkeeper uses batch size of 10 000 records. You can increase or decrease this value
135     # depending on your needs and server capabilities.
136     #
137     # token_lookup_batch_size 10_000
138
139     # Set a limit for token_reuse if using reuse_access_token option
140     #
141     # This option limits token_reusability to some extent.
142     # If not set then access_token will be reused unless it expires.
143     # Rationale: https://github.com/doorkeeper-gem/doorkeeper/issues/1189
144     #
145     # This option should be a percentage(i.e. (0,100])
146     #
147     # token_reuse_limit 100
148
149     # Only allow one valid access token obtained via client credentials
150     # per client. If a new access token is obtained before the old one
151     # expired, the old one gets revoked (disabled by default)
152     #
153     # When enabling this option, make sure that you do not expect multiple processes
154     # using the same credentials at the same time (e.g. web servers spanning
155     # multiple machines and/or processes).
156     #
157     # revoke_previous_client_credentials_token
158
159     # Hash access and refresh tokens before persisting them.
160     # This will disable the possibility to use +reuse_access_token+
161     # since plain values can no longer be retrieved.
162     #
163     # Note: If you are already a user of doorkeeper and have existing tokens
164     # in your installation, they will be invalid without adding 'fallback: :plain'.
165     #
166     # hash_token_secrets
167     # By default, token secrets will be hashed using the
168     # +Doorkeeper::Hashing::SHA256+ strategy.
169     #
170     # If you wish to use another hashing implementation, you can override
171     # this strategy as follows:
172
173     hash_token_secrets :using => "::Doorkeeper::SecretStoring::Plain",
174                        :fallback => "::Doorkeeper::SecretStoring::Sha256Hash"
175
176     # Keep in mind that changing the hashing function will invalidate all existing
177     # secrets, if there are any.
178
179     # Hash application secrets before persisting them.
180
181     hash_application_secrets
182
183     # By default, applications will be hashed
184     # with the +Doorkeeper::SecretStoring::SHA256+ strategy.
185     #
186     # If you wish to use bcrypt for application secret hashing, uncomment
187     # this line instead:
188     #
189     # hash_application_secrets using: '::Doorkeeper::SecretStoring::BCrypt'
190
191     # When the above option is enabled, and a hashed token or secret is not found,
192     # you can allow to fall back to another strategy. For users upgrading
193     # doorkeeper and wishing to enable hashing, you will probably want to enable
194     # the fallback to plain tokens.
195     #
196     # This will ensure that old access tokens and secrets
197     # will remain valid even if the hashing above is enabled.
198     #
199     # This can be done by adding 'fallback: plain', e.g. :
200     #
201     # hash_application_secrets using: '::Doorkeeper::SecretStoring::BCrypt', fallback: :plain
202
203     # Issue access tokens with refresh token (disabled by default), you may also
204     # pass a block which accepts `context` to customize when to give a refresh
205     # token or not. Similar to +custom_access_token_expires_in+, `context` has
206     # the following properties:
207     #
208     # `client` - the OAuth client application (see Doorkeeper::OAuth::Client)
209     # `grant_type` - the grant type of the request (see Doorkeeper::OAuth)
210     # `scopes` - the requested scopes (see Doorkeeper::OAuth::Scopes)
211     #
212     # use_refresh_token
213
214     # Provide support for an owner to be assigned to each registered application (disabled by default)
215     # Optional parameter confirmation: true (default: false) if you want to enforce ownership of
216     # a registered application
217     # NOTE: you must also run the rails g doorkeeper:application_owner generator
218     # to provide the necessary support
219
220     enable_application_owner :confirmation => true
221
222     # Define access token scopes for your provider
223     # For more information go to
224     # https://doorkeeper.gitbook.io/guides/ruby-on-rails/scopes
225
226     # default_scopes  :public
227     optional_scopes(*Oauth::SCOPES, *Oauth::PRIVILEGED_SCOPES)
228
229     # Allows to restrict only certain scopes for grant_type.
230     # By default, all the scopes will be available for all the grant types.
231     #
232     # Keys to this hash should be the name of grant_type and
233     # values should be the array of scopes for that grant type.
234     # Note: scopes should be from configured_scopes (i.e. default or optional)
235     #
236     # scopes_by_grant_type password: [:write], client_credentials: [:update]
237
238     # Forbids creating/updating applications with arbitrary scopes that are
239     # not in configuration, i.e. +default_scopes+ or +optional_scopes+.
240     # (disabled by default)
241
242     enforce_configured_scopes
243
244     # Change the way client credentials are retrieved from the request object.
245     # By default it retrieves first from the `HTTP_AUTHORIZATION` header, then
246     # falls back to the `:client_id` and `:client_secret` params from the `params` object.
247     # Check out https://github.com/doorkeeper-gem/doorkeeper/wiki/Changing-how-clients-are-authenticated
248     # for more information on customization
249     #
250     # client_credentials :from_basic, :from_params
251
252     # Change the way access token is authenticated from the request object.
253     # By default it retrieves first from the `HTTP_AUTHORIZATION` header, then
254     # falls back to the `:access_token` or `:bearer_token` params from the `params` object.
255     # Check out https://github.com/doorkeeper-gem/doorkeeper/wiki/Changing-how-clients-are-authenticated
256     # for more information on customization
257
258     access_token_methods :from_bearer_authorization
259
260     # Forces the usage of the HTTPS protocol in non-native redirect uris (enabled
261     # by default in non-development environments). OAuth2 delegates security in
262     # communication to the HTTPS protocol so it is wise to keep this enabled.
263     #
264     # Callable objects such as proc, lambda, block or any object that responds to
265     # #call can be used in order to allow conditional checks (to allow non-SSL
266     # redirects to localhost for example).
267
268     force_ssl_in_redirect_uri do |uri|
269       !Rails.env.development? && uri.host != "127.0.0.1"
270     end
271
272     # Specify what redirect URI's you want to block during Application creation.
273     # Any redirect URI is whitelisted by default.
274     #
275     # You can use this option in order to forbid URI's with 'javascript' scheme
276     # for example.
277     #
278     # forbid_redirect_uri { |uri| uri.scheme.to_s.downcase == 'javascript' }
279
280     # Allows to set blank redirect URIs for Applications in case Doorkeeper configured
281     # to use URI-less OAuth grant flows like Client Credentials or Resource Owner
282     # Password Credentials. The option is on by default and checks configured grant
283     # types, but you **need** to manually drop `NOT NULL` constraint from `redirect_uri`
284     # column for `oauth_applications` database table.
285     #
286     # You can completely disable this feature with:
287     #
288     # allow_blank_redirect_uri false
289     #
290     # Or you can define your custom check:
291     #
292     # allow_blank_redirect_uri do |grant_flows, client|
293     #   client.superapp?
294     # end
295
296     # Specify how authorization errors should be handled.
297     # By default, doorkeeper renders json errors when access token
298     # is invalid, expired, revoked or has invalid scopes.
299     #
300     # If you want to render error response yourself (i.e. rescue exceptions),
301     # set +handle_auth_errors+ to `:raise` and rescue Doorkeeper::Errors::InvalidToken
302     # or following specific errors:
303     #
304     #   Doorkeeper::Errors::TokenForbidden, Doorkeeper::Errors::TokenExpired,
305     #   Doorkeeper::Errors::TokenRevoked, Doorkeeper::Errors::TokenUnknown
306     #
307     # handle_auth_errors :raise
308
309     # Customize token introspection response.
310     # Allows to add your own fields to default one that are required by the OAuth spec
311     # for the introspection response. It could be `sub`, `aud` and so on.
312     # This configuration option can be a proc, lambda or any Ruby object responds
313     # to `.call` method and result of it's invocation must be a Hash.
314     #
315     # custom_introspection_response do |token, context|
316     #   {
317     #     "sub": "Z5O3upPC88QrAjx00dis",
318     #     "aud": "https://protected.example.net/resource",
319     #     "username": User.find(token.resource_owner_id).username
320     #   }
321     # end
322     #
323     # or
324     #
325     # custom_introspection_response CustomIntrospectionResponder
326
327     # Specify what grant flows are enabled in array of Strings. The valid
328     # strings and the flows they enable are:
329     #
330     # "authorization_code" => Authorization Code Grant Flow
331     # "implicit"           => Implicit Grant Flow
332     # "password"           => Resource Owner Password Credentials Grant Flow
333     # "client_credentials" => Client Credentials Grant Flow
334     #
335     # If not specified, Doorkeeper enables authorization_code and
336     # client_credentials.
337     #
338     # implicit and password grant flows have risks that you should understand
339     # before enabling:
340     #   http://tools.ietf.org/html/rfc6819#section-4.4.2
341     #   http://tools.ietf.org/html/rfc6819#section-4.4.3
342
343     grant_flows %w[authorization_code]
344
345     # Allows to customize OAuth grant flows that +each+ application support.
346     # You can configure a custom block (or use a class respond to `#call`) that must
347     # return `true` in case Application instance supports requested OAuth grant flow
348     # during the authorization request to the server. This configuration +doesn't+
349     # set flows per application, it only allows to check if application supports
350     # specific grant flow.
351     #
352     # For example you can add an additional database column to `oauth_applications` table,
353     # say `t.array :grant_flows, default: []`, and store allowed grant flows that can
354     # be used with this application there. Then when authorization requested Doorkeeper
355     # will call this block to check if specific Application (passed with client_id and/or
356     # client_secret) is allowed to perform the request for the specific grant type
357     # (authorization, password, client_credentials, etc).
358     #
359     # Example of the block:
360     #
361     #   ->(flow, client) { client.grant_flows.include?(flow) }
362     #
363     # In case this option invocation result is `false`, Doorkeeper server returns
364     # :unauthorized_client error and stops the request.
365     #
366     # @param allow_grant_flow_for_client [Proc] Block or any object respond to #call
367     # @return [Boolean] `true` if allow or `false` if forbid the request
368     #
369     # allow_grant_flow_for_client do |grant_flow, client|
370     #   # `grant_flows` is an Array column with grant
371     #   # flows that application supports
372     #
373     #   client.grant_flows.include?(grant_flow)
374     # end
375
376     # If you need arbitrary Resource Owner-Client authorization you can enable this option
377     # and implement the check your need. Config option must respond to #call and return
378     # true in case resource owner authorized for the specific application or false in other
379     # cases.
380     #
381     # Be default all Resource Owners are authorized to any Client (application).
382     #
383     # authorize_resource_owner_for_client do |client, resource_owner|
384     #   resource_owner.admin? || client.owners_whitelist.include?(resource_owner)
385     # end
386
387     # Hook into the strategies' request & response life-cycle in case your
388     # application needs advanced customization or logging:
389     #
390     # before_successful_strategy_response do |request|
391     #   puts "BEFORE HOOK FIRED! #{request}"
392     # end
393     #
394     # after_successful_strategy_response do |request, response|
395     #   puts "AFTER HOOK FIRED! #{request}, #{response}"
396     # end
397
398     # Hook into Authorization flow in order to implement Single Sign Out
399     # or add any other functionality. Inside the block you have an access
400     # to `controller` (authorizations controller instance) and `context`
401     # (Doorkeeper::OAuth::Hooks::Context instance) which provides pre auth
402     # or auth objects with issued token based on hook type (before or after).
403     #
404     # before_successful_authorization do |controller, context|
405     #   Rails.logger.info(controller.request.params.inspect)
406     #
407     #   Rails.logger.info(context.pre_auth.inspect)
408     # end
409     #
410     # after_successful_authorization do |controller, context|
411     #   controller.session[:logout_urls] <<
412     #     Doorkeeper::Application
413     #       .find_by(controller.request.params.slice(:redirect_uri))
414     #       .logout_uri
415     #
416     #   Rails.logger.info(context.auth.inspect)
417     #   Rails.logger.info(context.issued_token)
418     # end
419
420     # Under some circumstances you might want to have applications auto-approved,
421     # so that the user skips the authorization step.
422     # For example if dealing with a trusted application.
423
424     skip_authorization do |_, client|
425       client.scopes.include?("skip_authorization")
426     end
427
428     # Configure custom constraints for the Token Introspection request.
429     # By default this configuration option allows to introspect a token by another
430     # token of the same application, OR to introspect the token that belongs to
431     # authorized client (from authenticated client) OR when token doesn't
432     # belong to any client (public token). Otherwise requester has no access to the
433     # introspection and it will return response as stated in the RFC.
434     #
435     # Block arguments:
436     #
437     # @param token [Doorkeeper::AccessToken]
438     #   token to be introspected
439     #
440     # @param authorized_client [Doorkeeper::Application]
441     #   authorized client (if request is authorized using Basic auth with
442     #   Client Credentials for example)
443     #
444     # @param authorized_token [Doorkeeper::AccessToken]
445     #   Bearer token used to authorize the request
446     #
447     # In case the block returns `nil` or `false` introspection responses with 401 status code
448     # when using authorized token to introspect, or you'll get 200 with { "active": false } body
449     # when using authorized client to introspect as stated in the
450     # RFC 7662 section 2.2. Introspection Response.
451     #
452     # Using with caution:
453     # Keep in mind that these three parameters pass to block can be nil as following case:
454     #  `authorized_client` is nil if and only if `authorized_token` is present, and vice versa.
455     #  `token` will be nil if and only if `authorized_token` is present.
456     # So remember to use `&` or check if it is present before calling method on
457     # them to make sure you doesn't get NoMethodError exception.
458     #
459     # You can define your custom check:
460     #
461     # allow_token_introspection do |token, authorized_client, authorized_token|
462     #   if authorized_token
463     #     # customize: require `introspection` scope
464     #     authorized_token.application == token&.application ||
465     #       authorized_token.scopes.include?("introspection")
466     #   elsif token.application
467     #     # `protected_resource` is a new database boolean column, for example
468     #     authorized_client == token.application || authorized_client.protected_resource?
469     #   else
470     #     # public token (when token.application is nil, token doesn't belong to any application)
471     #     true
472     #   end
473     # end
474     #
475     # Or you can completely disable any token introspection:
476     #
477     # allow_token_introspection false
478     #
479     # If you need to block the request at all, then configure your routes.rb or web-server
480     # like nginx to forbid the request.
481
482     # WWW-Authenticate Realm (default: "Doorkeeper").
483     #
484     # realm "Doorkeeper"
485   end
486 end