Abdulaziz
Abdulaziz

Reputation: 2211

Devise: How to only authenticate users whom has a relation with another model?

I've the following tables:

users
======
id
email
password
..device columns..

providers
==========
user_id
..irreverent columns..

consumers
==========
user_id
..irrelevant columns..  

Both consumers and providers belong to the users table, we're using this design because there are areas of the web app that both parties can access, however, sometimes there are provider-specific areas which consumers shouldn't be at, such as providers management panel.

So this raised the following question, how do I get Devise to just authenticate providers and not consumers on provider-specific namespaces when it only knows about the users table and not providers/consumers?

Here's what I think I should be doing:

controllers/provider/base_controller.rb:

  before_action :authenticate_provider!

  private
  #A modified wrapper around authenticate_user!
  def authenticate_provider! 
    authenticate_user!
    redirect_to sign_in_path unless Provider.find_by(user: current_user)
  end

Upvotes: 1

Views: 74

Answers (1)

Gjaldon
Gjaldon

Reputation: 5644

A few things you might want to consider:

  1. Instead of using separate tables for providers and consumers, you could create a role attribute for users table. That design seems to be more suited to your needs.

  2. If you want to restrict access to certain parts of your site depending on whether a user is a provider or a consumer, it is authorization you need and not authentication. Assuming you already have a role attribute for your user, you could have code like below for a controller action you don't want consumers to have access to:

#

def new
  redirect_to root_path, alert: "Unauthorized access." if current_user.role == "consumer"
end

Let me know if that helps.

Upvotes: 1

Related Questions