2
votes

Is there any way of making the authentication_keys configuration conditional depending on the user type?

For instance in my User model I have two different user, standard user and student, defined by the value of a bitmask attribute. I want to authenticate Students on the basis of username and school_id. Standard users don't have to have a value for school_id. In order to accommodate this I have two types of login screens, one for students and another for standard users. The student login screen has a hidden school_id field that authenticates them to their school.

In my devise configuration file I have:

config.authentication_keys = [ :username, :school_id ] 

However with this setup standard users are unable to login, my guess is that it's expecting a school_id for all Users being authenticated. Is it possible to make the authentication keys conditional? Or give an allow_blank option for school_id? I want to be able to keep standard users and students in the same model.

1

1 Answers

2
votes

Yes, simply do in your models:

class User < ActiveRecord::Base
  devise :database_authenticatable, authentication_keys: [:username]
end

class Student < ActiveRecord::Base
  devise :database_authenticatable, authentication_keys: [:username, :student_id]
end