mikker / passwordless

πŸ— Authentication for your Rails app without the icky-ness of passwords
MIT License
1.26k stars 85 forks source link

Protecting Sidekiq Web UI with Passwordless: is this interesting enough to add to README? #125

Closed mzrnsh closed 1 year ago

mzrnsh commented 1 year ago

I am using Sidekiq in my Rails project. Since I already implemented authentication via Passwordless, I'd like to keep using Passwordless to protect Sidekiq Web UI, instead of adding another authentication solution, be it basic auth or something else.

Sidekiq docs does not (yet) feature an example for Passwordless, but their restful authentication or sorcery example is pretty close to a working solution. This is how I did it:

# app/models/user.rb

class User < ApplicationRecord
  validates :email, presence: true, uniqueness: { case_sensitive: false }

  passwordless_with :email

  # Treating all users as admins to make the example short. This part will likely look different in your app ✌️
  def admin?
    true
  end
end
# lib/admin_constraint.rb

class AdminConstraint
  def matches?(request)
    passwordless_session_id = request.session['passwordless_session_id--user']
    return false unless passwordless_session_id

    user = Passwordless::Session.find(passwordless_session_id).authenticatable
    user&.admin?
  end
end
# config/routes.rb

require 'sidekiq/web'
require 'admin_constraint'

Rails.application.routes.draw do
  passwordless_for :users
  mount Sidekiq::Web => '/sidekiq', constraints: AdminConstraint.new
  ...
end

Here's my question:

Is this use case interesting enough to add it to Passwordless' README?

It doesn't have to be Sidekiq-specific either: this can be used to protect routes from other engines as well.

mikker commented 1 year ago

This is really good and helpful. I think the README is getting a bit crowded. Maybe a Wiki page is better?

mikker commented 1 year ago

Made one https://github.com/mikker/passwordless/wiki/Usage-with-Sidekiq::Web. Thank you @mzrnsh β€οΈπŸ§‘πŸ’›πŸ’šπŸ’™πŸ’œ