nsarno / knock

Seamless JWT authentication for Rails API

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Is there any way to use Knock with route constraints?

toadkicker opened this issue · comments

I'm looking at authenticating Shrine presigned routes through constraints and if the Knock::Authenticatable could be leveraged in a route constraint.

Something like:

lib/constraints/authenticated_request.rb

module Constraints
  class AuthenticatedRequest
    include Knock::Authenticable

    def matches?(request)
      auth_header = request.headers.fetch('Authorization')
      return false unless auth_header
      authenticate_user
    end

  end
end

and in routes:

  mount ImageUploader.presign_endpoint(:cache) => '/images/presign', constraints: Constraints::AuthenticatedRequest.new

I know this is an old issue but I bumped into this problem today. This is the current implementation I'm using:

##
# This constraint asserts the current user is an admin
class AdminConstraint
  def matches?(request)
    return false unless request.headers['Authorization']

    token = request.headers['Authorization'].split(' ')[1]

    user_id = Knock::AuthToken.new(token: token).payload['sub']
    user = User.find(user_id)

    user.admin?
  end
end

Be wary as I'm not familiar with the Knock APIs.