Is phx.gen.auth good enough for role based authentication?
Let’s say for example one was building an e-commerce store.
There would standard users, admins, and sellers.
Could one do:
mix phx.gen.auth Accounts User users
mix phx.gen.auth Accounts Admin admins
mix phx.gen.auth Accounts Sellers sellers
I know that would create a lot of duplicate code, but if you got in there and specified which functions were fore each role, would this work? Also, could this be adaptable to phx.gen.auth? I couldn’t find anything regarding roles in the documentation.
Second alternative: Could one have and admins table that inherits the users table? I’m fairly new to Ecto and Postgres and I don’t know if that works here.
Thank you for your time
I would do it once with
mix phx.gen.auth Accounts User users and then update the migration to have a
role enum field (could be
[:customer, :admin, :seller]). That is the good thing about get.auth, it lets you modify the code after the fact
I’ve spent some time building a Phoenix app with auth and if I had to do it all over again I would use Supabase.com because they not only give you auth, but they also give you a very slick Postgres layer. You can still use Elixir/Phoenix to connect to it. Using Supabase for data+auth and connecting to it with Phoenix seems to me to be the most flexible approach all around. Auth is such a pain-in-the-neck when you don’t basically outsource it.
It’s hard to say whether this is the “right” approach - it’s an approach, but whether it’s right depends on what the application does with users.
For instance, if all three kinds of users do the same sorts of things - or even more, if they all end up attached to the same records - then keeping them in three tables will be a headache.
On the flip side, if they do very different things this approach could be valuable since it’s possible to enforce things like “this can only point to a seller”. There may even be security benefits in some situations, since a User cannot become an Admin by overwriting columns in the database.
Another alternative approach: make a model that manages just the email + password part (call it something like
phx.gen.auth, then have a
credential_id on Admin / User / Seller etc. This could help reduce the duplication of things like password reset machinery etc (IF that machinery is supposed to be the same!)