There isn't much information about this. Is there a way to check if a user is logged in with AdonisJS V6 and socket.io? I have this code so far, but I can't verify if the user has logged in with CSRF session. Is there also a way to use middleware with socket.io?
start/socket.ts
import adonisServer from '@adonisjs/core/services/server'
import { Server } from 'socket.io'
import UsersController from '#controllers/users_controller'
const io = new Server(adonisServer.getNodeServer())
io.on("connection", (socket) => {
const socketController = new UsersController();
socketController.handleMessage({ socket, io });
socket.on("test", (args: any) => {
socketController.handleTest({ socket, args });
});
});
UsersController:
import type { HttpContext } from '@adonisjs/core/http'
import { Role } from '@holoyan/adonisjs-permissions'
import User from '#models/user'
import { middleware } from '#start/kernel'
import { Request } from '@adonisjs/core/http'
// import { shieldApiClient } from '@adonisjs/shield/plugins/api_client'
// import { sessionApiClient } from '@adonisjs/session/plugins/api_client'
let tttt = null;
export default class UsersController {
/**
* Display a list of resource
*/
async index({ }: HttpContext) { }
/**
* Display form to create a new record
*/
async create({ request }: HttpContext) {
}
public handleMessage({ socket, io }: { socket: any, io: any }) {
socket.emit("message", "world");
}
public async handleTest({ socket, args }: { socket: any, args: any }) {
console.log(args);
const handshake = socket.handshake
console.log(handshake.auth.csrfToken);
}
}
react:
import { PageProps } from "~/Web/types";
import io from "socket.io-client";
export default function Dashboard({ csrf }: PageProps) {
const socket = io({
auth: {
csrfToken: csrf,
},
});
socket.on("message", (args: any) => {
console.log(args);
});
socket.emit("test", csrf);
console.log(csrf);
return <h1>test</h1>;
}
AdonisJS V6 after a lot of research, the solution is as follows: You can use this repository which includes the connection but through the API with an access token. This will solve the auth issue, but I hope the developers of AdonisJS will support this matter themselves and create solutions for this problem and improve their documentation.
Link GitHub: Adonis chat demo
Connection method:
const socket = io("http://localhost:3333/", {
extraHeaders: {
authorization: "Bearer <token>",
},
});