FeathersJS Customise Local Auth Strategy
I often see people in the FeathersJS community asking how they can customize the LocalAuth to implement some additional user verifications and throw their errors. I thought I would walk through how easy it is in v4 to do this by extending the LocalStrategy. The LocalStrategy refers to the auth strategy which is used for a username/email & password authentication, as opposed to JWT or OAuth.
By default, the LocalStrategy will verify the username/email and password combination. It will throw an error if the password and username/email combination do not match. But sometimes you may want to do more than verify the username/email & password.
As the documentation shows, you can customize how the user is looked up so that you can restrict to only active users:
In the above snippet, we can see that to create our custom strategy we extend the LocalStrategy and overwrite the getEntityQuery which is used to do the email lookup. This should either return a valid user which will then be used to compare passwords or return no users which will by default throw a NotAuthenticated error. You can change the message of the error by configuration which can be found here.
To extend it even further, we might want to throw a different error or a custom error then we can do the following:
What we can do is extend the findEntity method. We will need to call the super.findEntity so that we can use the existing implementation of fetching the user. Then we can check the user that is returned to see whether they are in support of coffee.
Both of the above methods can be used in combination together also!
Thanks for reading!