feathersjs / feathers

The API and real-time application framework
https://feathersjs.com
MIT License
15.06k stars 752 forks source link

How To: Include an additional field to Authenticate a user #2039

Closed apmcodes closed 4 years ago

apmcodes commented 4 years ago

Along with email and password need to include an additional field property to authenticate an user. Tried to pass property field in params.query but it seems its not being used to authenticate (but used to return the user and thats generating error.)

Extended Authentication service

        async create(data, params) {
            if (data.strategy == 'local' && data.property) {
                params.query = {
                    property: data.property
                }
            };
            const authResult = await super.create(data, params);
            return authResult;
        }

Getting error

NotFound: No record found for id '2'

MySQL User Model id 2, email, property1 > FeathersJS authenticate user id 2 and returns jwt, user successfully id 5, email, property2 > FeathersJS authenticates as user id 2 (based on email and password) and trying to return user 2 applying params.query (property2) and fails with the NotFound: No record found for id '2'

Background We have two frontend (sites) that connect to a single FeatherJs api. The users from both the sites are differentiated by a property field. Same user (email) can be present in both the sites.

Can someone help me understand how to extend Authentication service to include additional field in authenticate.

daffl commented 4 years ago

This can be done by customizing the getEntityQuery method.

apmcodes commented 4 years ago

Thank you very much. Got it working by extending the LocalStrategy.

    class MyLocalStrategy extends LocalStrategy {
        async getEntityQuery(query, params) {
          return {
            ...query,
            status: 1,
            property: params.query.property,
            $limit: 1
          }
        }
      }

Need to wrap my head aound the docs better.