How to custom withRefreshToken() with different table tokens

I try to create 2 table

  • Admin
  • User

using JWT Login first I define In Auth.js

user: {
    serializer: 'lucid',
    model: 'App/Models/User',
    scheme: 'jwt',
    uid: 'username',
    password: 'password',
    options: {
      secret: Env.get('APP_KEY'),
    },
  },
  admin: {
    serializer: 'lucid',
    model: 'App/Models/Admin',
    scheme: 'jwt',
    uid: 'username',
    password: 'password',
    options: {
      secret: Env.get('APP_KEY'),
    },

And here Is my Admin login function

const { username, password } = request.all();
        try {
            const token = await auth
                .authenticator('admin')
                .withRefreshToken()
                .attempt(username, password);
            const user = await Admin.findBy('username', username);
            const emp = await Admin.query()
                .where('id', user.id)
                .first();
            return response.status(200).json({
                status: 200,
                token: token,
                username: user.username,
            });
        } catch (error) {
            throw new CustomErrorException('error', 401);
        }

the Problem is here .withRefreshToken() , it’s return user.tokens is not a function

How can I custom
if adminLogin await auth.authenticator(‘admin’) use token_admin table
if userLogin use token_user table

Note: in token_admin I modify table I changed from user_id into admin_id

table
        .integer('admin_id')
        .unsigned()
        .references('id')
        .inTable('admins');

@akirawinz

This is one of the bad designs I regularly see people falling into, that they store admin and other users in two different database tables.

The admin is just a different role for a given user and not a different user. So I suggest fixing that first and keep all users in a central table.

Coming back to the question, nope it’s not possible to have multiple tokens table

4 Likes

So It will be better if I use only table users and separate by roles using

right ?

You can use it