Skip to content

Instantly share code, notes, and snippets.

@chadwilken
Created February 1, 2020 19:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chadwilken/7a8e4105a17d5718a3764413ce507bd7 to your computer and use it in GitHub Desktop.
Save chadwilken/7a8e4105a17d5718a3764413ce507bd7 to your computer and use it in GitHub Desktop.
Doorkeeper with Devise
class BaseController < ApplicationController
before_action :doorkeeper_authorize!, except: [:index, :show, :create, :update, :destroy] # Anything not caught below
before_action :authorize_read_actions!, only: [:index, :show]
before_action :authorize_write_actions!, only: [:create, :update]
before_action :authorize_destroy_actions!, only: [:destroy]
def current_user
unless defined?(@current_user)
if doorkeeper_token.present? && !doorkeeper_token.revoked?
@current_user ||= User.find_by(id: doorkeeper_token.resource_owner_id)
end
end
@current_user
end
private
def authorize_read_actions!
doorkeeper_authorize!(:read)
end
def authorize_write_actions!
doorkeeper_authorize!(:write)
end
def authorize_destroy_actions!
doorkeeper_authorize!(:destroy)
end
def doorkeeper_render_error_with(error)
if error.name == :invalid_scope
forbidden('Access Token is read-only')
elsif error.name == :invalid_token
unauthenticated!
end
end
def current_oauth_application
unless defined?(@oauth_application)
if doorkeeper_token.present? && doorkeeper_token.application.present?
@oauth_application = doorkeeper_token.application
end
end
@oauth_application
end
def require_oauth_application!
return bad_request('Could not find application from X-CompanyCam-Secret') unless current_oauth_application.present?
end
end
Doorkeeper.configure do
resource_owner_authenticator do
current_user || warden.authenticate!(scope: :user)
end
resource_owner_from_credentials do
user = User.find_for_authentication(username: params[:username])
user ||= User.find_for_authentication(email_address: params[:username])
if user && user.valid_for_authentication? { user.valid_password?(params[:password]) }
user
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment