Login-in by roles feathers-authentication

954 Views Asked by At

i have two users in database and they have the same email and password, but different roles. It look like:

  email        pass   roles
+------------+------+-------
 [email protected]   123    user
 [email protected]   123    admin

and when user try to login in, i send request with params

{
    email:"[email protected]"
    password:"123"
    roles:"user"
    strategy:"local"
}

The questuin is:how i can to identify user by role (when i send from front-end req with param roles:"user" user must to login by role "user", when roles:"admin" - by admin)

It's my hook from auth

app.service('authentication').hooks({
before: {
  create: [
    authentication.hooks.authenticate(['local', 'jwt'])
  ],
  remove: [
    authentication.hooks.authenticate('jwt')
  ]
},
1

There are 1 best solutions below

2
On

A user (or other authenticated) entity should be uniquely identifiable so it makes more sense to store a list of roles for one user like this:

  email        pass   roles
+------------+------+-------
 [email protected]   123    user,admin

And then can log in with that user and in a hook check if the roles list contains what you need:

const { Forbidden } = require('feathers-errors');

function hasRole(name) {
  return function(context) {
    const { user = {} } = context.params;

    if(!user.roles || !user.roles.split(',').includes(name)) {
      throw new Forbidden('You are not allowed to access this');
    }
  }
}

app.service('myservice').hooks({
  before: {
    get: [ hasRole('user') ],
    find: [ hasRole('user') ],
    create: [ hasRole('admin') ],
    patch: [ hasRole('admin') ],
    update: [ hasRole('admin') ],
    remove: [ hasRole('admin') ]
  }
})