nsarno / knock

Seamless JWT authentication for Rails API
MIT License
2.07k stars 253 forks source link

How to use the NullUser pattern with Knock? #267

Closed unikitty37 closed 4 years ago

unikitty37 commented 4 years ago

When the user is logged out, or passes an invalid token, current_user returns nil.

What I would like is for current_user to return an instance of my NullUser class instead, so that I don't have to keep checking for nil everywhere.

I've tried this in controllers/application_controller.rb

alias_method :original_current_user, :current_user

def current_user
  original_current_user || NullUser.new
end

but it fails with NameError (undefined method 'current_user' for class 'ApplicationController'). This method worked with Devise — I assume it's failing because of the way Knock defines current_user.

I'm using this for now

def current_or_null_user
  current_user || NullUser.new
end

but it's less than ideal because other gems are expecting to use current_user and I'm not sure right now if they can all be easily configured to use something else. Is there a clean way of customising current_user?

PericlesTheo commented 4 years ago

hey @unikitty37 can you paste the whole controller and which version of knock you are using?

unikitty37 commented 4 years ago

Thanks — unfortunately, I gave up on Knock and switched to devise-jwt.

I've had a look in the git reflog, but can't find any actual commits with Knock in them, so I'll close this issue as there's probably not much you'll be able to do to help without that info. Sorry for the waste of time.