How to require 2FA for credential accounts only?

I see there have already been some related messages about wanting to require that all users setup two-factor authentication. I used to have this working in my middleware, redirecting the user to a setup 2fa page if they didn't have it enabled, but this doesn't work if they signed in with another method, such as passkey. Is there a proper trigger, such as a database hook, regular hook, or custom session that can help me distinguish between the different ways that someone has logged in? Or even just to know if the user has set a password would be enough to know if I should then ensure 2FA is enabled, but where should I do that check so that I don't query the accounts table too often?
Solution:
use hooks -> intercept the request and the user that's logging in -> fetch the user accounts -> if user only has oauth accounts, return -> if user has only a password account/the login method in the request is a credential login, throw some response/error, and proceed to do the logic you want to do (e.g. redirect, database logic) the if statements would probably your best friend in avoiding querying the accounts table often, but pretty much you can't really avoid fetching the table every time someone's logging in with the credentials...
Jump to solution
2 Replies
Solution
sebastian
sebastian2w ago
use hooks -> intercept the request and the user that's logging in -> fetch the user accounts -> if user only has oauth accounts, return -> if user has only a password account/the login method in the request is a credential login, throw some response/error, and proceed to do the logic you want to do (e.g. redirect, database logic) the if statements would probably your best friend in avoiding querying the accounts table often, but pretty much you can't really avoid fetching the table every time someone's logging in with the credentials
sebastian
sebastian2w ago
i actually wrote something simmilar in the hooks, i made a whole custom 2fa that checks the user's login fingerprint, creating and parsing cookies, making custom database calls, redirects, auth tokens etc. and it works great, a lot can be achieved in the hooks

Did you find this page helpful?