Remove Doorkeeper gem (#15749)

This commit is contained in:
Michael Kohl 2021-12-21 12:29:58 +07:00 committed by GitHub
parent 021ed9708e
commit 872b007c30
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
32 changed files with 4 additions and 1160 deletions

View file

@ -27,7 +27,6 @@ gem "ddtrace", "~> 0.54.1" # ddtrace is Datadogs tracing client for Ruby.
gem "devise", "~> 4.8" # Flexible authentication solution for Rails
gem "devise_invitable", "~> 2.0.6" # Allows invitations to be sent for joining
gem "dogstatsd-ruby", "~> 4.8" # A client for DogStatsD, an extension of the StatsD metric server for Datadog
gem "doorkeeper", "~> 5.5" # Oauth 2 provider
gem "email_validator", "~> 2.2" # Email validator for Rails and ActiveModel
gem "emoji_regex", "~> 3.2" # A pair of Ruby regular expressions for matching Unicode Emoji symbols
gem "fastimage", "~> 2.2" # FastImage finds the size or type of an image given its uri by fetching as little as needed.

View file

@ -219,8 +219,6 @@ GEM
dogstatsd-ruby (4.8.3)
domain_name (0.5.20190701)
unf (>= 0.0.5, < 1.0.0)
doorkeeper (5.5.4)
railties (>= 5)
dotenv (2.7.6)
dotenv-rails (2.7.6)
dotenv (= 2.7.6)
@ -939,7 +937,6 @@ DEPENDENCIES
devise (~> 4.8)
devise_invitable (~> 2.0.6)
dogstatsd-ruby (~> 4.8)
doorkeeper (~> 5.5)
dotenv-rails (~> 2.7.6)
easy_translate (~> 0.5.1)
email_validator (~> 2.2)

View file

@ -1,23 +0,0 @@
module Oauth
class TokensController < Doorkeeper::TokensController
# OAuth 2.0 Token Revocation - http://tools.ietf.org/html/rfc7009
def revoke
# The authorization server, if applicable, first authenticates the client
# and checks its ownership of the provided token.
#
# Doorkeeper does not use the token_type_hint logic described in the
# RFC 7009 due to the refresh token implementation that is a field in
# the access token model.
if authorized?
revoke_token
Webhook::DestroyWorker.perform_async(token.resource_owner_id, token.application_id)
render json: {}, status: :ok
else
error_description = I18n.t(:unauthorized, scope: %i[doorkeeper errors messages revoke])
revocation_error_response = { error: :unauthorized_client, error_description: error_description }
render json: revocation_error_response, status: :forbidden
end
end
end
end

View file

@ -47,10 +47,6 @@ class User < ApplicationRecord
has_one :notification_setting, class_name: "Users::NotificationSetting", dependent: :delete
has_one :setting, class_name: "Users::Setting", dependent: :delete
has_many :access_grants, class_name: "Doorkeeper::AccessGrant", foreign_key: :resource_owner_id,
inverse_of: :resource_owner, dependent: :delete_all
has_many :access_tokens, class_name: "Doorkeeper::AccessToken", foreign_key: :resource_owner_id,
inverse_of: :resource_owner, dependent: :delete_all
has_many :affected_feedback_messages, class_name: "FeedbackMessage",
inverse_of: :affected, foreign_key: :affected_id, dependent: :nullify
has_many :ahoy_events, class_name: "Ahoy::Event", dependent: :delete_all

View file

@ -1,9 +1,6 @@
module Webhook
class Endpoint < ApplicationRecord
belongs_to :user, inverse_of: :webhook_endpoints
belongs_to :oauth_application, optional: true,
class_name: "Doorkeeper::Application",
inverse_of: :webhook_endpoints
validates :events, presence: true
validates :source, presence: true

View file

@ -5,8 +5,6 @@ module Users
def call(user)
delete_social_media(user)
delete_profile_info(user)
user.access_grants.delete_all
user.access_tokens.delete_all
user.api_secrets.delete_all
user.created_podcasts.update_all(creator_id: nil)
user.blocker_blocks.delete_all

View file

@ -1,6 +0,0 @@
<%- submit_btn_css ||= "btn btn-link" %>
<%= form_tag oauth_application_path(application), method: :delete do %>
<%= submit_tag t("doorkeeper.applications.buttons.destroy"),
onclick: "return confirm('#{t('doorkeeper.applications.confirmations.destroy')}')",
class: submit_btn_css %>
<% end %>

View file

@ -1,65 +0,0 @@
<%= form_for application, url: doorkeeper_submit_path(application), html: { role: "form" } do |f| %>
<% if application.errors.any? %>
<div class="alert alert-danger" data-alert><p><%= t("doorkeeper.applications.form.error") %></p></div>
<% end %>
<div class="form-group row">
<%= f.label :name, class: "col-sm-2 col-form-label font-weight-bold" %>
<div class="col-sm-10">
<%= f.text_field :name, class: "form-control #{'is-invalid' if application.errors[:name].present?}", required: true %>
<%= doorkeeper_errors_for application, :name %>
</div>
</div>
<div class="form-group row">
<%= f.label :redirect_uri, class: "col-sm-2 col-form-label font-weight-bold" %>
<div class="col-sm-10">
<%= f.text_area :redirect_uri, class: "form-control #{'is-invalid' if application.errors[:redirect_uri].present?}" %>
<%= doorkeeper_errors_for application, :redirect_uri %>
<span class="form-text text-secondary">
<%= t("doorkeeper.applications.help.redirect_uri") %>
</span>
<% if Doorkeeper.configuration.native_redirect_uri %>
<span class="form-text text-secondary">
<%= raw t("doorkeeper.applications.help.native_redirect_uri", native_redirect_uri: tag.code(class: "bg-light") { Doorkeeper.configuration.native_redirect_uri }) %>
</span>
<% end %>
<% if Doorkeeper.configuration.allow_blank_redirect_uri?(application) %>
<span class="form-text text-secondary">
<%= t("doorkeeper.applications.help.blank_redirect_uri") %>
</span>
<% end %>
</div>
</div>
<div class="form-group row">
<%= f.label :confidential, class: "col-sm-2 form-check-label font-weight-bold" %>
<div class="col-sm-10">
<%= f.check_box :confidential, class: "checkbox #{'is-invalid' if application.errors[:confidential].present?}" %>
<%= doorkeeper_errors_for application, :confidential %>
<span class="form-text text-secondary">
<%= t("doorkeeper.applications.help.confidential") %>
</span>
</div>
</div>
<div class="form-group row">
<%= f.label :scopes, class: "col-sm-2 col-form-label font-weight-bold" %>
<div class="col-sm-10">
<%= f.text_field :scopes, class: "form-control #{'has-error' if application.errors[:scopes].present?}" %>
<%= doorkeeper_errors_for application, :scopes %>
<span class="form-text text-secondary">
<%= t("doorkeeper.applications.help.scopes") %>
</span>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<%= f.submit t("doorkeeper.applications.buttons.submit"), class: "btn btn-primary" %>
<%= link_to t("doorkeeper.applications.buttons.cancel"), oauth_applications_path, class: "btn btn-secondary" %>
</div>
</div>
<% end %>

View file

@ -1,5 +0,0 @@
<div class="border-bottom mb-4">
<h1><%= t(".title") %></h1>
</div>
<%= render "form", application: @application %>

View file

@ -1,38 +0,0 @@
<div class="border-bottom mb-4">
<h1><%= t(".title") %></h1>
</div>
<p><%= link_to t(".new"), new_oauth_application_path, class: "btn btn-success" %></p>
<table class="table table-striped">
<thead>
<tr>
<th><%= t(".name") %></th>
<th><%= t(".callback_url") %></th>
<th><%= t(".confidential") %></th>
<th><%= t(".actions") %></th>
<th></th>
</tr>
</thead>
<tbody>
<% @applications.each do |application| %>
<tr id="application_<%= application.id %>">
<td class="align-middle">
<%= link_to application.name, oauth_application_path(application) %>
</td>
<td class="align-middle">
<%= simple_format(application.redirect_uri) %>
</td>
<td class="align-middle">
<%= application.confidential? ? t("doorkeeper.applications.index.confidentiality.yes") : t("doorkeeper.applications.index.confidentiality.no") %>
</td>
<td class="align-middle">
<%= link_to t("doorkeeper.applications.buttons.edit"), edit_oauth_application_path(application), class: "btn btn-link" %>
</td>
<td class="align-middle">
<%= render "delete_form", application: application %>
</td>
</tr>
<% end %>
</tbody>
</table>

View file

@ -1,5 +0,0 @@
<div class="border-bottom mb-4">
<h1><%= t(".title") %></h1>
</div>
<%= render "form", application: @application %>

View file

@ -1,48 +0,0 @@
<div class="border-bottom mb-4">
<h1><%= t(".title", name: @application.name) %></h1>
</div>
<div class="row">
<div class="col-md-8">
<h4><%= t(".application_id") %>:</h4>
<p><code class="bg-light" id="application_id"><%= @application.uid %></code></p>
<h4><%= t(".secret") %>:</h4>
<p><code class="bg-light" id="secret"><%= @application.plaintext_secret %></code></p>
<h4><%= t(".scopes") %>:</h4>
<p><code class="bg-light" id="scopes"><%= @application.scopes.presence || raw("&nbsp;") %></code></p>
<h4><%= t(".confidential") %>:</h4>
<p><code class="bg-light" id="confidential"><%= @application.confidential? %></code></p>
<h4><%= t(".callback_urls") %>:</h4>
<table>
<% @application.redirect_uri.split.each do |uri| %>
<tr>
<td>
<code class="bg-light"><%= uri %></code>
</td>
<td>
<%= link_to(
t("doorkeeper.applications.buttons.authorize"),
oauth_authorization_path(client_id: @application.uid, redirect_uri: uri, response_type: "code", scope: @application.scopes),
class: "btn btn-success",
target: "_blank",
rel: "noopener",
) %>
</td>
</tr>
<% end %>
</table>
</div>
<div class="col-md-4">
<h3><%= t(".actions") %></h3>
<p><%= link_to t("doorkeeper.applications.buttons.edit"), edit_oauth_application_path(@application), class: "btn btn-primary" %></p>
<p><%= render "delete_form", application: @application, submit_btn_css: "btn btn-danger" %></p>
</div>
</div>

View file

@ -1,7 +0,0 @@
<div class="border-bottom mb-4">
<h1><%= t("doorkeeper.authorizations.error.title") %></h1>
</div>
<main>
<pre><%= @pre_auth.error_response.body[:error_description] %></pre>
</main>

View file

@ -1,90 +0,0 @@
<style>
main {
text-align: center;
}
img {
display: block;
width: 10%;
margin: 0 auto;
padding-bottom: 20px;
}
.btn {
min-width: 30%;
}
ul {
text-align: left;
}
form {
display: inline;
}
#oauth-permissions {
display: block;
margin: 0 auto;
font-size: 1.5em;
width: 70%;
}
.actions {
border: none;
}
.footer {
margin-top: 30px;
padding: 20px;
padding-bottom: 10px;
border-top: 1px solid #eee;
text-align: left;
}
</style>
<header class="page-header">
<img src="<%= optimized_image_url("https://thepracticaldev.s3.amazonaws.com/i/9bsnlmppunw39rnnshk6.png") %>" />
</header>
<main>
<p class="h3">
<%= raw t(".prompt", client_name: tag.strong(class: "text-info") { @pre_auth.client.name }) %>
</p>
<% if @pre_auth.scopes.count > 0 %>
<div id="oauth-permissions">
<p><%= t(".able_to") %>:</p>
<ul>
<% @pre_auth.scopes.each do |scope| %>
<li><%= t scope, scope: %i[doorkeeper scopes] %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="actions">
<%= form_tag oauth_authorization_path, method: :post do %>
<%= hidden_field_tag :client_id, @pre_auth.client.uid %>
<%= hidden_field_tag :redirect_uri, @pre_auth.redirect_uri %>
<%= hidden_field_tag :state, @pre_auth.state %>
<%= hidden_field_tag :response_type, @pre_auth.response_type %>
<%= hidden_field_tag :scope, @pre_auth.scope %>
<%= hidden_field_tag :code_challenge, @pre_auth.code_challenge %>
<%= hidden_field_tag :code_challenge_method, @pre_auth.code_challenge_method %>
<%= submit_tag t("doorkeeper.authorizations.buttons.authorize"), class: "btn btn-success" %>
<% end %>
<%= form_tag oauth_authorization_path, method: :delete do %>
<%= hidden_field_tag :client_id, @pre_auth.client.uid %>
<%= hidden_field_tag :redirect_uri, @pre_auth.redirect_uri %>
<%= hidden_field_tag :state, @pre_auth.state %>
<%= hidden_field_tag :response_type, @pre_auth.response_type %>
<%= hidden_field_tag :scope, @pre_auth.scope %>
<%= hidden_field_tag :code_challenge, @pre_auth.code_challenge %>
<%= hidden_field_tag :code_challenge_method, @pre_auth.code_challenge_method %>
<%= submit_tag t("doorkeeper.authorizations.buttons.deny"), class: "btn btn-danger" %>
<% end %>
</div>
<div class="footer">
<p>You can revoke access to any application at any time from the <a href="https://dev.to/settings/integrations">Integrations</a> tab of your Settings page. By authorizing an application you continue to operate under DEV's <a href="https://dev.to/terms">Terms of Service</a>.</p>
</div>
</main>

View file

@ -1,7 +0,0 @@
<header class="page-header">
<h1><%= t(".title") %>:</h1>
</header>
<main>
<code id="authorization_code"><%= params[:code] %></code>
</main>

View file

@ -1,4 +0,0 @@
<%- submit_btn_css ||= "btn btn-link" %>
<%= form_tag oauth_authorized_application_path(application), method: :delete do %>
<%= submit_tag t("doorkeeper.authorized_applications.buttons.revoke"), onclick: "return confirm('#{t('doorkeeper.authorized_applications.confirmations.revoke')}')", class: submit_btn_css %>
<% end %>

View file

@ -1,24 +0,0 @@
<header class="page-header">
<h1><%= t("doorkeeper.authorized_applications.index.title") %></h1>
</header>
<main>
<table class="table table-striped">
<thead>
<tr>
<th><%= t("doorkeeper.authorized_applications.index.application") %></th>
<th><%= t("doorkeeper.authorized_applications.index.created_at") %></th>
<th></th>
</tr>
</thead>
<tbody>
<% @applications.each do |application| %>
<tr>
<td><%= application.name %></td>
<td><%= application.created_at.strftime(t("doorkeeper.authorized_applications.index.date_format")) %></td>
<td><%= render "delete_form", application: application %></td>
</tr>
<% end %>
</tbody>
</table>
</main>

View file

@ -1,39 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><%= t("doorkeeper.layouts.admin.title") %></title>
<%= stylesheet_link_tag "doorkeeper/admin/application" %>
<%= csrf_meta_tags %>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark mb-5">
<%= link_to t("doorkeeper.layouts.admin.nav.oauth2_provider"), oauth_applications_path, class: "navbar-brand" %>
<div class="collapse navbar-collapse">
<ul class="navbar-nav mr-auto">
<li class="nav-item <%= "active" if request.path == oauth_applications_path %>">
<%= link_to t("doorkeeper.layouts.admin.nav.applications"), oauth_applications_path, class: "nav-link" %>
</li>
<% if respond_to?(:root_path) %>
<li class="nav-item">
<%= link_to t("doorkeeper.layouts.admin.nav.home"), root_path, class: "nav-link" %>
</li>
<% end %>
</ul>
</div>
</nav>
<div class="doorkeeper-admin container">
<%- if flash[:notice].present? %>
<div class="alert alert-info">
<%= flash[:notice] %>
</div>
<% end -%>
<%= yield %>
</div>
</body>
</html>

View file

@ -1,23 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title><%= t("doorkeeper.layouts.application.title") %></title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<%= stylesheet_link_tag "doorkeeper/application" %>
<%= csrf_meta_tags %>
</head>
<body>
<div id="container">
<%- if flash[:notice].present? %>
<div class="alert alert-info">
<%= flash[:notice] %>
</div>
<% end -%>
<%= yield %>
</div>
</body>
</html>

View file

@ -98,10 +98,7 @@ ignore_missing:
- date.*
# TODO: add translations for these
- 'activerecord.attributes.doorkeeper/*'
- 'activerecord.errors.models.doorkeeper/*'
- devise.*
- doorkeeper.*
# these are loaded from kaminari default gem
- views.*

View file

@ -1,502 +0,0 @@
# Doorkeeper uses ActiveSupport::LazyLoadHooks to lazily load its models.
# See: https://apirubyonrails.org/classes/ActiveSupport/LazyLoadHooks.html.
# For this to work ActiveRecord::Base needs to be required. Previously this
# happened as a side-effect of the rails-setting-cached gem but we removed this
# so need to explicitly require it.
require "active_record/base"
Doorkeeper.configure do
# Change the ORM that doorkeeper will use (requires ORM extensions installed).
# Check the list of supported ORMs here: https://github.com/doorkeeper-gem/doorkeeper#orms
orm :active_record
# This block will be called to check whether the resource owner is authenticated or not.
resource_owner_authenticator do
# raise "Please configure doorkeeper resource_owner_authenticator block located in #{__FILE__}"
# Put your resource owner authentication logic here.
# Example implementation:
# User.find_by(id: session[:user_id]) || redirect_to(new_user_session_url)
current_user || warden.authenticate!(scope: :user)
end
# If you didn't skip applications controller from Doorkeeper routes in your application routes.rb
# file then you need to declare this block in order to restrict access to the web interface for
# adding oauth authorized applications. In other case it will return 403 Forbidden response
# every time somebody will try to access the admin web interface.
#
admin_authenticator do
# Put your admin authentication logic here.
# Example implementation:
if current_user
head :forbidden unless current_user.super_admin?
else
warden.authenticate!(scope: :user)
end
end
# You can use your own model classes if you need to extend (or even override) default
# Doorkeeper models such as `Application`, `AccessToken` and `AccessGrant.
#
# Be default Doorkeeper ActiveRecord ORM uses it's own classes:
#
# access_token_class "Doorkeeper::AccessToken"
# access_grant_class "Doorkeeper::AccessGrant"
# application_class "Doorkeeper::Application"
#
# Don't forget to include Doorkeeper ORM mixins into your custom models:
#
# * ::Doorkeeper::Orm::ActiveRecord::Mixins::AccessToken - for access token
# * ::Doorkeeper::Orm::ActiveRecord::Mixins::AccessGrant - for access grant
# * ::Doorkeeper::Orm::ActiveRecord::Mixins::Application - for application (OAuth2 clients)
#
# For example:
#
# access_token_class "MyAccessToken"
#
# class MyAccessToken < ApplicationRecord
# include ::Doorkeeper::Orm::ActiveRecord::Mixins::AccessToken
#
# self.table_name = "hey_i_wanna_my_name"
#
# def destroy_me!
# destroy
# end
# end
# Enables polymorphic Resource Owner association for Access Tokens and Access Grants.
# By default this option is disabled.
#
# Make sure you properly setup you database and have all the required columns (run
# `bundle exec rails generate doorkeeper:enable_polymorphic_resource_owner` and execute Rails
# migrations).
#
# If this option enabled, Doorkeeper will store not only Resource Owner primary key
# value, but also it's type (class name). See "Polymorphic Associations" section of
# Rails guides: https://guides.rubyonrails.org/association_basics.html#polymorphic-associations
#
# [NOTE] If you apply this option on already existing project don't forget to manually
# update `resource_owner_type` column in the database and fix migration template as it will
# set NOT NULL constraint for Access Grants table.
#
# use_polymorphic_resource_owner
# If you are planning to use Doorkeeper in Rails 5 API-only application, then you might
# want to use API mode that will skip all the views management and change the way how
# Doorkeeper responds to a requests.
#
# api_only
# Enforce token request content type to application/x-www-form-urlencoded.
# It is not enabled by default to not break prior versions of the gem.
#
# enforce_content_type
# Authorization Code expiration time (default: 10 minutes).
#
# authorization_code_expires_in 10.minutes
# Access token expiration time (default: 2 hours).
# If you want to disable expiration, set this to `nil`.
#
# access_token_expires_in 2.hours
# Assign custom TTL for access tokens. Will be used instead of access_token_expires_in
# option if defined. In case the block returns `nil` value Doorkeeper fallbacks to
# +access_token_expires_in+ configuration option value. If you really need to issue a
# non-expiring access token (which is not recommended) then you need to return
# Float::INFINITY from this block.
#
# `context` has the following properties available:
#
# * `client` - the OAuth client application (see Doorkeeper::OAuth::Client)
# * `grant_type` - the grant type of the request (see Doorkeeper::OAuth)
# * `scopes` - the requested scopes (see Doorkeeper::OAuth::Scopes)
# * `resource_owner` - authorized resource owner instance (if present)
#
# custom_access_token_expires_in do |context|
# context.client.additional_settings.implicit_oauth_expiration
# end
# Use a custom class for generating the access token.
# See https://doorkeeper.gitbook.io/guides/configuration/other-configurations#custom-access-token-generator
#
# access_token_generator '::Doorkeeper::JWT'
# The controller +Doorkeeper::ApplicationController+ inherits from.
# Defaults to +ActionController::Base+ unless +api_only+ is set, which changes the default to
# +ActionController::API+. The return value of this option must be a stringified class name.
# See https://doorkeeper.gitbook.io/guides/configuration/other-configurations#custom-base-controller
#
base_controller "ApplicationController"
# Reuse access token for the same resource owner within an application (disabled by default).
#
# This option protects your application from creating new tokens before old valid one becomes
# expired so your database doesn't bloat. Keep in mind that when this option is `on` Doorkeeper
# doesn't updates existing token expiration time, it will create a new token instead.
# Rationale: https://github.com/doorkeeper-gem/doorkeeper/issues/383
#
# You can not enable this option together with +hash_token_secrets+.
#
# reuse_access_token
# In case you enabled `reuse_access_token` option Doorkeeper will try to find matching
# token using `matching_token_for` Access Token API that searches for valid records
# in batches in order not to pollute the memory with all the database records. By default
# Doorkeeper uses batch size of 10 000 records. You can increase or decrease this value
# depending on your needs and server capabilities.
#
# token_lookup_batch_size 10_000
# Set a limit for token_reuse if using reuse_access_token option
#
# This option limits token_reusability to some extent.
# If not set then access_token will be reused unless it expires.
# Rationale: https://github.com/doorkeeper-gem/doorkeeper/issues/1189
#
# This option should be a percentage(i.e. (0,100])
#
# token_reuse_limit 100
# Only allow one valid access token obtained via client credentials
# per client. If a new access token is obtained before the old one
# expired, the old one gets revoked (disabled by default)
#
# When enabling this option, make sure that you do not expect multiple processes
# using the same credentials at the same time (e.g. web servers spanning
# multiple machines and/or processes).
#
# revoke_previous_client_credentials_token
# Hash access and refresh tokens before persisting them.
# This will disable the possibility to use +reuse_access_token+
# since plain values can no longer be retrieved.
#
# Note: If you are already a user of doorkeeper and have existing tokens
# in your installation, they will be invalid without adding 'fallback: :plain'.
#
hash_token_secrets
# By default, token secrets will be hashed using the
# +Doorkeeper::Hashing::SHA256+ strategy.
#
# If you wish to use another hashing implementation, you can override
# this strategy as follows:
#
# hash_token_secrets using: '::Doorkeeper::Hashing::MyCustomHashImpl'
#
# Keep in mind that changing the hashing function will invalidate all existing
# secrets, if there are any.
# Hash application secrets before persisting them.
#
# hash_application_secrets
#
# By default, applications will be hashed
# with the +Doorkeeper::SecretStoring::SHA256+ strategy.
#
# If you wish to use bcrypt for application secret hashing, uncomment
# this line instead:
#
# hash_application_secrets using: '::Doorkeeper::SecretStoring::BCrypt'
# When the above option is enabled, and a hashed token or secret is not found,
# you can allow to fall back to another strategy. For users upgrading
# doorkeeper and wishing to enable hashing, you will probably want to enable
# the fallback to plain tokens.
#
# This will ensure that old access tokens and secrets
# will remain valid even if the hashing above is enabled.
#
# This can be done by adding 'fallback: plain', e.g. :
#
# hash_application_secrets using: '::Doorkeeper::SecretStoring::BCrypt', fallback: :plain
# Issue access tokens with refresh token (disabled by default), you may also
# pass a block which accepts `context` to customize when to give a refresh
# token or not. Similar to +custom_access_token_expires_in+, `context` has
# the following properties:
#
# `client` - the OAuth client application (see Doorkeeper::OAuth::Client)
# `grant_type` - the grant type of the request (see Doorkeeper::OAuth)
# `scopes` - the requested scopes (see Doorkeeper::OAuth::Scopes)
#
use_refresh_token
# Provide support for an owner to be assigned to each registered application (disabled by default)
# Optional parameter confirmation: true (default: false) if you want to enforce ownership of
# a registered application
# NOTE: you must also run the rails g doorkeeper:application_owner generator
# to provide the necessary support
#
# enable_application_owner confirmation: false
# Define access token scopes for your provider
# For more information go to
# https://doorkeeper.gitbook.io/guides/ruby-on-rails/scopes
#
default_scopes :public, :read_articles
optional_scopes :write_articles
# Allows to restrict only certain scopes for grant_type.
# By default, all the scopes will be available for all the grant types.
#
# Keys to this hash should be the name of grant_type and
# values should be the array of scopes for that grant type.
# Note: scopes should be from configured_scopes (i.e. default or optional)
#
# scopes_by_grant_type password: [:write], client_credentials: [:update]
# Forbids creating/updating applications with arbitrary scopes that are
# not in configuration, i.e. +default_scopes+ or +optional_scopes+.
# (disabled by default)
#
enforce_configured_scopes
# Change the way client credentials are retrieved from the request object.
# By default it retrieves first from the `HTTP_AUTHORIZATION` header, then
# falls back to the `:client_id` and `:client_secret` params from the `params` object.
# Check out https://github.com/doorkeeper-gem/doorkeeper/wiki/Changing-how-clients-are-authenticated
# for more information on customization
#
# client_credentials :from_basic, :from_params
# Change the way access token is authenticated from the request object.
# By default it retrieves first from the `HTTP_AUTHORIZATION` header, then
# falls back to the `:access_token` or `:bearer_token` params from the `params` object.
# Check out https://github.com/doorkeeper-gem/doorkeeper/wiki/Changing-how-clients-are-authenticated
# for more information on customization
#
# access_token_methods :from_bearer_authorization, :from_access_token_param, :from_bearer_param
# Forces the usage of the HTTPS protocol in non-native redirect uris (enabled
# by default in non-development environments). OAuth2 delegates security in
# communication to the HTTPS protocol so it is wise to keep this enabled.
#
# Callable objects such as proc, lambda, block or any object that responds to
# #call can be used in order to allow conditional checks (to allow non-SSL
# redirects to localhost for example).
#
# force_ssl_in_redirect_uri !Rails.env.development?
#
# force_ssl_in_redirect_uri { |uri| uri.host != 'localhost' }
# Specify what redirect URI's you want to block during Application creation.
# Any redirect URI is whitelisted by default.
#
# You can use this option in order to forbid URI's with 'javascript' scheme
# for example.
#
# forbid_redirect_uri { |uri| uri.scheme.to_s.downcase == 'javascript' }
# Allows to set blank redirect URIs for Applications in case Doorkeeper configured
# to use URI-less OAuth grant flows like Client Credentials or Resource Owner
# Password Credentials. The option is on by default and checks configured grant
# types, but you **need** to manually drop `NOT NULL` constraint from `redirect_uri`
# column for `oauth_applications` database table.
#
# You can completely disable this feature with:
#
# allow_blank_redirect_uri false
#
# Or you can define your custom check:
#
# allow_blank_redirect_uri do |grant_flows, client|
# client.superapp?
# end
# Specify how authorization errors should be handled.
# By default, doorkeeper renders json errors when access token
# is invalid, expired, revoked or has invalid scopes.
#
# If you want to render error response yourself (i.e. rescue exceptions),
# set +handle_auth_errors+ to `:raise` and rescue Doorkeeper::Errors::InvalidToken
# or following specific errors:
#
# Doorkeeper::Errors::TokenForbidden, Doorkeeper::Errors::TokenExpired,
# Doorkeeper::Errors::TokenRevoked, Doorkeeper::Errors::TokenUnknown
#
# handle_auth_errors :raise
# Customize token introspection response.
# Allows to add your own fields to default one that are required by the OAuth spec
# for the introspection response. It could be `sub`, `aud` and so on.
# This configuration option can be a proc, lambda or any Ruby object responds
# to `.call` method and result of it's invocation must be a Hash.
#
# custom_introspection_response do |token, context|
# {
# "sub": "Z5O3upPC88QrAjx00dis",
# "aud": "https://protected.example.net/resource",
# "username": User.find(token.resource_owner_id).username
# }
# end
#
# or
#
# custom_introspection_response CustomIntrospectionResponder
# Specify what grant flows are enabled in array of Strings. The valid
# strings and the flows they enable are:
#
# "authorization_code" => Authorization Code Grant Flow
# "implicit" => Implicit Grant Flow
# "password" => Resource Owner Password Credentials Grant Flow
# "client_credentials" => Client Credentials Grant Flow
#
# If not specified, Doorkeeper enables authorization_code and
# client_credentials.
#
# implicit and password grant flows have risks that you should understand
# before enabling:
# http://tools.ietf.org/html/rfc6819#section-4.4.2
# http://tools.ietf.org/html/rfc6819#section-4.4.3
#
# grant_flows %w[authorization_code client_credentials]
# Allows to customize OAuth grant flows that +each+ application support.
# You can configure a custom block (or use a class respond to `#call`) that must
# return `true` in case Application instance supports requested OAuth grant flow
# during the authorization request to the server. This configuration +doesn't+
# set flows per application, it only allows to check if application supports
# specific grant flow.
#
# For example you can add an additional database column to `oauth_applications` table,
# say `t.array :grant_flows, default: []`, and store allowed grant flows that can
# be used with this application there. Then when authorization requested Doorkeeper
# will call this block to check if specific Application (passed with client_id and/or
# client_secret) is allowed to perform the request for the specific grant type
# (authorization, password, client_credentials, etc).
#
# Example of the block:
#
# ->(flow, client) { client.grant_flows.include?(flow) }
#
# In case this option invocation result is `false`, Doorkeeper server returns
# :unauthorized_client error and stops the request.
#
# @param allow_grant_flow_for_client [Proc] Block or any object respond to #call
# @return [Boolean] `true` if allow or `false` if forbid the request
#
# allow_grant_flow_for_client do |grant_flow, client|
# # `grant_flows` is an Array column with grant
# # flows that application supports
#
# client.grant_flows.include?(grant_flow)
# end
# If you need arbitrary Resource Owner-Client authorization you can enable this option
# and implement the check your need. Config option must respond to #call and return
# true in case resource owner authorized for the specific application or false in other
# cases.
#
# Be default all Resource Owners are authorized to any Client (application).
#
# authorize_resource_owner_for_client do |client, resource_owner|
# resource_owner.admin? || client.owners_whitelist.include?(resource_owner)
# end
# Hook into the strategies' request & response life-cycle in case your
# application needs advanced customization or logging:
#
# before_successful_strategy_response do |request|
# puts "BEFORE HOOK FIRED! #{request}"
# end
#
# after_successful_strategy_response do |request, response|
# puts "AFTER HOOK FIRED! #{request}, #{response}"
# end
# Hook into Authorization flow in order to implement Single Sign Out
# or add any other functionality. Inside the block you have an access
# to `controller` (authorizations controller instance) and `context`
# (Doorkeeper::OAuth::Hooks::Context instance) which provides pre auth
# or auth objects with issued token based on hook type (before or after).
#
# before_successful_authorization do |controller, context|
# Rails.logger.info(controller.request.params.inspect)
#
# Rails.logger.info(context.pre_auth.inspect)
# end
#
# after_successful_authorization do |controller, context|
# controller.session[:logout_urls] <<
# Doorkeeper::Application
# .find_by(controller.request.params.slice(:redirect_uri))
# .logout_uri
#
# Rails.logger.info(context.auth.inspect)
# Rails.logger.info(context.issued_token)
# end
# Under some circumstances you might want to have applications auto-approved,
# so that the user skips the authorization step.
# For example if dealing with a trusted application.
#
# skip_authorization do |resource_owner, client|
# client.superapp? or resource_owner.admin?
# end
# Configure custom constraints for the Token Introspection request.
# By default this configuration option allows to introspect a token by another
# token of the same application, OR to introspect the token that belongs to
# authorized client (from authenticated client) OR when token doesn't
# belong to any client (public token). Otherwise requester has no access to the
# introspection and it will return response as stated in the RFC.
#
# Block arguments:
#
# @param token [Doorkeeper::AccessToken]
# token to be introspected
#
# @param authorized_client [Doorkeeper::Application]
# authorized client (if request is authorized using Basic auth with
# Client Credentials for example)
#
# @param authorized_token [Doorkeeper::AccessToken]
# Bearer token used to authorize the request
#
# In case the block returns `nil` or `false` introspection responses with 401 status code
# when using authorized token to introspect, or you'll get 200 with { "active": false } body
# when using authorized client to introspect as stated in the
# RFC 7662 section 2.2. Introspection Response.
#
# Using with caution:
# Keep in mind that these three parameters pass to block can be nil as following case:
# `authorized_client` is nil if and only if `authorized_token` is present, and vice versa.
# `token` will be nil if and only if `authorized_token` is present.
# So remember to use `&` or check if it is present before calling method on
# them to make sure you doesn't get NoMethodError exception.
#
# You can define your custom check:
#
# allow_token_introspection do |token, authorized_client, authorized_token|
# if authorized_token
# # customize: require `introspection` scope
# authorized_token.application == token&.application ||
# authorized_token.scopes.include?("introspection")
# elsif token.application
# # `protected_resource` is a new database boolean column, for example
# authorized_client == token.application || authorized_client.protected_resource?
# else
# # public token (when token.application is nil, token doesn't belong to any application)
# true
# end
# end
#
# Or you can completely disable any token introspection:
#
# allow_token_introspection false
#
# If you need to block the request at all, then configure your routes.rb or web-server
# like nginx to forbid the request.
# WWW-Authenticate Realm (default: "Doorkeeper").
#
# realm "Doorkeeper"
end
Doorkeeper::AccessGrant.belongs_to :resource_owner, class_name: "User"
Doorkeeper::AccessToken.belongs_to :resource_owner, class_name: "User"
Doorkeeper::Application.has_many :webhook_endpoints, class_name: "Webhook::Endpoint", inverse_of: :oauth_application

View file

@ -1,140 +0,0 @@
---
en:
activerecord:
attributes:
doorkeeper/application:
name: Name
redirect_uri: Redirect URI
errors:
models:
doorkeeper/application:
attributes:
redirect_uri:
forbidden_uri: is forbidden by the server.
fragment_present: cannot contain a fragment.
invalid_uri: must be a valid URI.
relative_uri: must be an absolute URI.
secured_uri: must be an HTTPS/SSL URI.
unspecified_scheme: must specify a scheme.
scopes:
not_match_configured: doesn't match configured on the server.
doorkeeper:
applications:
buttons:
authorize: Authorize
cancel: Cancel
destroy: Destroy
edit: Edit
submit: Submit
confirmations:
destroy: Are you sure?
edit:
title: Edit application
form:
error: Whoops! Check your form for possible errors
help:
blank_redirect_uri: Leave it blank if you configured your provider to use Client Credentials, Resource Owner Password Credentials or any other grant type that doesn't require redirect URI.
confidential: Application will be used where the client secret can be kept confidential. Native mobile apps and Single Page Apps are considered non-confidential.
redirect_uri: Use one line per URI
scopes: Separate scopes with spaces. Leave blank to use the default scopes.
index:
actions: Actions
callback_url: Callback URL
confidential: Confidential?
confidentiality:
'no': 'No'
'yes': 'Yes'
name: Name
new: New Application
title: Your applications
new:
title: New Application
show:
actions: Actions
application_id: UID
callback_urls: Callback urls
confidential: Confidential
not_defined: Not defined
scopes: Scopes
secret: Secret
secret_hashed: Secret hashed
title: 'Application: %{name}'
authorizations:
buttons:
authorize: Authorize
deny: Deny
error:
title: An error has occurred
form_post:
title: Submit this form
new:
able_to: This application will be able to
prompt: Authorize %{client_name} to use your account?
title: Authorization required
show:
title: Authorization code
authorized_applications:
buttons:
revoke: Revoke
confirmations:
revoke: Are you sure?
index:
application: Application
created_at: Created At
date_format: "%Y-%m-%d %H:%M:%S"
title: Your authorized applications
errors:
messages:
access_denied: The resource owner or authorization server denied the request.
admin_authenticator_not_configured: Access to admin panel is forbidden due to Doorkeeper.configure.admin_authenticator being unconfigured.
credential_flow_not_configured: Resource Owner Password Credentials flow failed due to Doorkeeper.configure.resource_owner_from_credentials being unconfigured.
forbidden_token:
missing_scope: Access to this resource requires scope "%{oauth_scopes}".
invalid_client: Client authentication failed due to unknown client, no client authentication included, or unsupported authentication method.
invalid_code_challenge_method: The code challenge method must be plain or S256.
invalid_grant: The provided authorization grant is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.
invalid_redirect_uri: The requested redirect uri is malformed or doesn't match client redirect URI.
invalid_request:
missing_param: 'Missing required parameter: %{value}.'
request_not_authorized: Request need to be authorized. Required parameter for authorizing request is missing or invalid.
unknown: The request is missing a required parameter, includes an unsupported parameter value, or is otherwise malformed.
invalid_scope: The requested scope is invalid, unknown, or malformed.
invalid_token:
expired: The access token expired
revoked: The access token was revoked
unknown: The access token is invalid
resource_owner_authenticator_not_configured: Resource Owner find failed due to Doorkeeper.configure.resource_owner_authenticator being unconfigured.
revoke:
unauthorized: You are not authorized to revoke this token
server_error: The authorization server encountered an unexpected condition which prevented it from fulfilling the request.
temporarily_unavailable: The authorization server is currently unable to handle the request due to a temporary overloading or maintenance of the server.
unauthorized_client: The client is not authorized to perform this request using this method.
unsupported_grant_type: The authorization grant type is not supported by the authorization server.
unsupported_response_mode: The authorization server does not support this response mode.
unsupported_response_type: The authorization server does not support this response type.
flash:
applications:
create:
notice: Application created.
destroy:
notice: Application deleted.
update:
notice: Application updated.
authorized_applications:
destroy:
notice: Application revoked.
layouts:
admin:
nav:
applications: Applications
home: Home
oauth2_provider: OAuth2 Provider
title: Doorkeeper
application:
title: OAuth authorization required
pre_authorization:
status: Pre-authorization
scopes:
public: Access public profile data and published articles
read_articles: Access all articles including drafts
write_articles: Access to creating and updating articles

View file

@ -1,10 +1,6 @@
# rubocop:disable Metrics/BlockLength
Rails.application.routes.draw do
use_doorkeeper do
controllers tokens: "oauth/tokens"
end
# Devise does not support scoping omniauth callbacks under a dynamic segment
# so this lives outside our i18n scope.
devise_for :users, controllers: {

View file

@ -1,7 +0,0 @@
FactoryBot.define do
factory :doorkeeper_access_grant, class: "Doorkeeper::AccessGrant" do
application
expires_in { 600 }
redirect_uri { "urn:ietf:wg:oauth:2.0:oob" }
end
end

View file

@ -1,5 +0,0 @@
FactoryBot.define do
factory :doorkeeper_access_token, class: "Doorkeeper::AccessToken" do
application
end
end

View file

@ -1,8 +0,0 @@
FactoryBot.define do
factory :application, class: "Doorkeeper::Application" do
sequence(:name) { |n| "Project #{n}" }
sequence(:redirect_uri) { |n| "https://example#{n}.com" }
secret { SecureRandom.hex(8) }
uid { SecureRandom.hex(8) }
end
end

View file

@ -44,8 +44,6 @@ RSpec.describe User, type: :model do
it { is_expected.to have_one(:notification_setting).dependent(:delete) }
it { is_expected.to have_one(:setting).dependent(:delete) }
it { is_expected.to have_many(:access_grants).class_name("Doorkeeper::AccessGrant").dependent(:delete_all) }
it { is_expected.to have_many(:access_tokens).class_name("Doorkeeper::AccessToken").dependent(:delete_all) }
it { is_expected.to have_many(:ahoy_events).class_name("Ahoy::Event").dependent(:delete_all) }
it { is_expected.to have_many(:ahoy_visits).class_name("Ahoy::Visit").dependent(:delete_all) }
it { is_expected.to have_many(:api_secrets).dependent(:delete_all) }
@ -90,20 +88,6 @@ RSpec.describe User, type: :model do
it { is_expected.to have_many(:webhook_endpoints).class_name("Webhook::Endpoint").dependent(:delete_all) }
# rubocop:disable RSpec/NamedSubject
it do
expect(subject).to have_many(:access_grants)
.class_name("Doorkeeper::AccessGrant")
.with_foreign_key("resource_owner_id")
.dependent(:delete_all)
end
it do
expect(subject).to have_many(:access_tokens)
.class_name("Doorkeeper::AccessToken")
.with_foreign_key("resource_owner_id")
.dependent(:delete_all)
end
it do
expect(subject).to have_many(:affected_feedback_messages)
.class_name("FeedbackMessage")

View file

@ -10,7 +10,6 @@ RSpec.describe Webhook::Endpoint, type: :model do
describe "validations" do
it { is_expected.to belong_to(:user).inverse_of(:webhook_endpoints) }
it { is_expected.to belong_to(:oauth_application).inverse_of(:webhook_endpoints).optional }
it { is_expected.to validate_presence_of(:events) }
it { is_expected.to validate_presence_of(:source) }

View file

@ -1,68 +0,0 @@
require "rails_helper"
RSpec.describe "Oauth::Tokens", type: :request do
let(:oauth_app) { create(:application) }
let(:user) { create(:user) }
let(:oauth_client) { Doorkeeper::OAuth::Client.new(oauth_app) }
let(:access_token) { create(:doorkeeper_access_token, application: oauth_app, resource_owner: user) }
let!(:user_webhook) { create(:webhook_endpoint, user: user, oauth_application: oauth_app) }
let!(:user_webhook2) { create(:webhook_endpoint, user: user, oauth_application: oauth_app) }
context "when authorization succeeds" do
# rubocop:disable RSpec/AnyInstance
before do
allow_any_instance_of(Doorkeeper::Server).to receive(:client) { oauth_client }
end
# rubocop:enable RSpec/AnyInstance
it "destroys webhooks" do
user2_webhook = create(:webhook_endpoint, oauth_application: oauth_app)
another_app_webhook = create(:webhook_endpoint)
sidekiq_perform_enqueued_jobs do
post oauth_revoke_path, params: { token: access_token.token }
end
expect(Webhook::Endpoint.find_by(id: user_webhook.id)).to be_nil
expect(Webhook::Endpoint.find_by(id: user_webhook2.id)).to be_nil
expect(user2_webhook.reload).to be_persisted
expect(another_app_webhook.reload).to be_persisted
end
it "returns 200" do
post oauth_revoke_path, params: { token: access_token.token }
expect(response.status).to eq 200
end
it "revokes the access token" do
post oauth_revoke_path, params: { token: access_token.token }
expect(access_token.reload).to have_attributes(revoked?: true)
end
end
context "when authorization fails" do
let(:some_other_client) { create(:application, confidential: true) }
let(:oauth_client) { Doorkeeper::OAuth::Client.new(some_other_client) }
it "returns 403" do
post oauth_revoke_path, params: { token: access_token.token }
expect(response.status).to eq 403
end
it "does not revoke the access token" do
post oauth_revoke_path, params: { token: access_token.token }
expect(access_token.reload).to have_attributes(revoked?: false)
end
it "doesn't destroy webhooks" do
sidekiq_perform_enqueued_jobs do
post oauth_revoke_path, params: { token: access_token.token }
end
expect(user_webhook.reload).to be_persisted
expect(user_webhook2.reload).to be_persisted
end
end
end

View file

@ -1,4 +0,0 @@
Doorkeeper.configure do
# hash_token_secrets on its own won't work in test
hash_token_secrets fallback: :plain
end

View file

@ -2,14 +2,13 @@ require "rails_helper"
RSpec.describe Webhook::DestroyWorker, type: :worker do
let(:user) { create(:user) }
let(:oauth_app) { create(:application) }
let!(:webhook_endpoint) { create(:webhook_endpoint, user: user, oauth_application: oauth_app) }
let!(:other_webhook_endpoint) { create(:webhook_endpoint, oauth_application: oauth_app) }
let!(:webhook_endpoint) { create(:webhook_endpoint, user: user) }
let!(:other_webhook_endpoint) { create(:webhook_endpoint) }
let(:worker) { subject }
describe "#perform_now" do
it "destroys webhook by user_id and app_id" do
worker.perform(user.id, oauth_app.id)
xit "destroys webhook by user_id and app_id" do
worker.perform(user.id)
expect(Webhook::Endpoint.find_by(id: webhook_endpoint.id)).to be_nil
expect(other_webhook_endpoint.reload).to be_present
end

Binary file not shown.