AdonisJS Socket.IO JWT authentication

718 Views Asked by At

How can you define the auth provider? Now every time the auth variable is undefined in the playerLogin method.

I'm are using Adonis v4.1

The code: start/socket.js

const Server = use('Server')
const io = use('socket.io')(Server.getInstance())

// Define controllers here
// Example: const WSController = use('App/Controllers/Http/ChatController')
const AuthenticateController = use('App/Controllers/Http/AuthenticateController');

io.on('connection', function (socket) {
  // Define here the controller methods
  // Example: WSController.goMessage(socket, io)
  AuthenticateController.playerLogin(socket, io);
  AuthenticateController.playerRegister(socket, io);
})

AuthenticateController.js

const Hash = use('Hash')
const User = use('App/Models/User')

class AuthenticateController {
    static playerLogin(socket, io, {auth}) {
        socket.on('playerLogin', async (data) => {
            console.log('WORKS')
            if (await auth.attempt(data.email, data.password)) {
                let user = await User.findBy('email', data.email)
                let accessToken = await auth.generate(user)
                socket.emit('sendPlayerToken', { token: accessToken });
            } else {
                socket.emit('sendPlayerToken', { token: 'Credentials are incorrect' });
            }
        });
    }

    static playerRegister(socket, io) {
        socket.on('playerRegister', async (data) => {
            const safePassword = await Hash.make(data.password)
            const user = new User()
            user.username = data.username
            user.email = data.email
            user.password = safePassword
            await user.save()
            socket.emit('sendPlayerRegister', { success: true });
        });
    }
}

Kind regards,

Corné

1

There are 1 best solutions below

0
On

As this discussion bellow:

https://github.com/adonisjs/core/discussions/2051?sort=new#discussioncomment-274111

You can use the API guard and authenticate using the code from the answer of M4gie.

You only need to install the crypto package with yarn add crypto and if you don't want to create the object to display the socket errors, just turn it into a string: throw new Error('SocketErrors:MissingParameter').