Knock: Multiple Entity Authentication

Created on 4 Apr 2017  路  5Comments  路  Source: nsarno/knock

I want to use Knock with multiple models, like User, Admin...etc.
Now I can use jwt token which get form user to pass before_action :authenticate_admin.
Should I custom payload with each Model class name?


Update
I customed model payload with class name and check it after Knock::AuthToken initialized and called entity_for with raise unless @payload['class'] == entity_class.name.
It works but seems wired, cos I override Knock's source, if anyone have better idea, please tell me. 馃槀

def to_token_payload
    {
      sub: id,
      class: self.class.name
    }
end

Most helpful comment

def to_token_payload
    return {sub: self.id, class: 'User' }
end
def self.from_token_payload payload
    self.find payload["sub"] if payload["class"] && payload["class"] == 'User'
end

@kjgarza This is what i used in my models to allow authentication with multiple models.

All 5 comments

I want to achieve this same thing. But it's not clear to me how to achieve it.

def to_token_payload
    return {sub: self.id, class: 'User' }
end
def self.from_token_payload payload
    self.find payload["sub"] if payload["class"] && payload["class"] == 'User'
end

@kjgarza This is what i used in my models to allow authentication with multiple models.

I think there should be a more elegant way of implementing such a basic functionality.
@charlesharvey workaround did the job (thanks by the way), i just made some syntax improvement:

  def to_token_payload
    { sub: id, class: self.class.to_s }
  end

  def self.from_token_payload(payload)
    find payload['sub'] if payload['class'] && payload['class'] == to_s
  end

Where to put those 2 def-s and is authenticate_[class_name] on controller is enough after adding those lines?

@ShiningBomb you should put those methods on your class model.
If your class is Admin, you put it on app/model/Admin.rb, then you can use authenticate_admin on your controller

Was this page helpful?
0 / 5 - 0 ratings

Related issues

PelagicDev picture PelagicDev  路  3Comments

vcavallo picture vcavallo  路  5Comments

psantos10 picture psantos10  路  3Comments

FNGR2911 picture FNGR2911  路  7Comments

YMonnier picture YMonnier  路  3Comments