Skip to content

Commit

Permalink
feat: read only handler
Browse files Browse the repository at this point in the history
Signed-off-by: Hoang Pham <hoangmaths96@gmail.com>
  • Loading branch information
hweihwang committed Jun 18, 2024
1 parent 718ea1d commit 03f28d4
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 20 deletions.
7 changes: 6 additions & 1 deletion src/collaboration/Portal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,18 +47,23 @@ export class Portal {
open(socket: Socket) {
this.socket = socket

const eventsNeedingTokenRefresh = ['connect_error', 'token-expired', 'invalid-token']
const eventsNeedingTokenRefresh = ['connect_error']
eventsNeedingTokenRefresh.forEach((event) =>
this.socket?.on(event, async () => {
await this.handleTokenRefresh()
})

Check warning on line 54 in src/collaboration/Portal.ts

View workflow job for this annotation

GitHub Actions / NPM lint

Missing trailing comma
)

this.socket.on('read-only', () => this.handleReadOnlySocket())
this.socket.on('init-room', () => this.handleInitRoom())
this.socket.on('room-user-change', (users: any) => this.collab.updateCollaborators(users))

Check failure on line 59 in src/collaboration/Portal.ts

View workflow job for this annotation

GitHub Actions / NPM lint

Unexpected any. Specify a different type
this.socket.on('client-broadcast', (data) => this.handleClientBroadcast(data))
}

async handleReadOnlySocket() {
this.collab.makeBoardReadOnly()
}

async handleTokenRefresh() {
const newToken = await this.refreshJWT()
if (this.socket && newToken) {
Expand Down
8 changes: 8 additions & 0 deletions src/collaboration/collab.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,4 +115,12 @@ export class Collab {
})
}

makeBoardReadOnly = () => {
this.excalidrawAPI.updateScene({
appState: {
viewModeEnabled: true
}
})
}

}
53 changes: 34 additions & 19 deletions websocket_server/socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,17 @@ dotenv.config()

const {
NEXTCLOUD_URL = 'http://nextcloud.local',
JWT_SECRET_KEY,
JWT_SECRET_KEY
} = process.env

const verifyToken = (token) => new Promise((resolve, reject) => {
jwt.verify(token, JWT_SECRET_KEY, (err, decoded) => {
if (err) {
console.log(err.name === 'TokenExpiredError' ? 'Token expired' : 'Token verification failed')

return reject(new Error('Authentication error'))
}

resolve(decoded)
})
})
Expand All @@ -29,23 +31,12 @@ export const initSocket = (server) => {
cors: {
origin: NEXTCLOUD_URL,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
credentials: true,
},
})

io.use(async (socket, next) => {
try {
const token = socket.handshake.auth.token
if (!token) throw new Error('No token provided')
socket.decodedData = await verifyToken(token)

next()
} catch (error) {
console.log(error.message)
next(error)
credentials: true
}
})

io.use(socketAuthenticateHandler)

io.on('connection', (socket) => {
setupSocketEvents(socket, io)
})
Expand All @@ -60,6 +51,30 @@ const setupSocketEvents = (socket, io) => {
socket.on('disconnect', () => socket.removeAllListeners())
}

const socketAuthenticateHandler = async (socket, next) => {
try {
const token = socket.handshake.auth.token || null
if (!token) {
console.error('No token provided')
next(new Error('Authentication error'))
}

socket.decodedData = await verifyToken(token)

console.log(`User ${socket.decodedData.user.name} with permission ${socket.decodedData.permissions} connected`)

if (socket.decodedData.permissions === 1) {
socket.emit('read-only')
}

next()
} catch (error) {
console.error(error.message)

next(new Error('Authentication error'))
}
}

const joinRoomHandler = async (socket, io, roomID) => {
console.log(`${socket.decodedData.user.name} has joined ${roomID}`)
await socket.join(roomID)
Expand All @@ -75,7 +90,7 @@ const joinRoomHandler = async (socket, io, roomID) => {

io.in(roomID).emit('room-user-change', sockets.map((s) => ({
socketId: s.id,
user: s.decodedData.user,
user: s.decodedData.user
})))
}

Expand All @@ -96,8 +111,8 @@ const serverVolatileBroadcastHandler = (socket, roomID, encryptedData) => {
type: 'MOUSE_LOCATION',
payload: {
...payload.payload,
user: socket.decodedData.user,
},
user: socket.decodedData.user
}
}

const encodedEventData = convertStringToArrayBuffer(JSON.stringify(eventData))
Expand All @@ -121,7 +136,7 @@ const disconnectingHandler = async (socket, io) => {
if (otherClients.length > 0) {
socket.broadcast.to(roomID).emit('room-user-change', otherClients.map((s) => ({
socketId: s.id,
user: s.decodedData.user,
user: s.decodedData.user
})))
}
}
Expand Down

0 comments on commit 03f28d4

Please sign in to comment.