-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsocket.ts
More file actions
58 lines (52 loc) · 1.76 KB
/
socket.ts
File metadata and controls
58 lines (52 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import AuthManager from '@ioc:Adonis/Addons/Auth'
import HttpContext from '@ioc:Adonis/Core/HttpContext'
import User from 'App/Models/User'
import Ws from 'App/Services/Ws'
Ws.boot()
Ws.io
.use(async (socket, next) => {
const apiAuthToken: undefined | string = socket.handshake.auth.Authorization
if (apiAuthToken) {
socket.request.headers.authorization = apiAuthToken
}
const ctx = HttpContext.create('/', {}, socket.request)
const auth = AuthManager.getAuthForRequest(ctx)
const shouldUseApiTokensAuthenticationMode = apiAuthToken !== undefined
if (shouldUseApiTokensAuthenticationMode) {
const isAuthenticated = await auth.use('api').check()
if (isAuthenticated) {
socket.handshake['user'] = auth.user
next()
} else {
next(new Error('User must be authenticated to perform socket protocol'))
}
} else {
try {
const readyOnly = true
await ctx.session.initiate(readyOnly)
const isAuthenticated = await auth.use('web').check()
if (isAuthenticated) {
socket.handshake['user'] = auth.user
next()
} else {
next(new Error('User must be authenticated to perform socket protocol'))
}
} catch (e) {
next(new Error('Adonis session init failed'))
}
}
})
.on('connection', async (socket) => {
try {
const userAuth: User = socket.handshake['user']
if (!(userAuth instanceof User)) {
throw new Error('Should never occurs userAuth is not a User model instance')
}
console.log(userAuth.email)
socket.on('GET_ACKNOWLEDGE_SOCKET_CONNECTION', async () => {
socket.emit('ACKNOWLEDGE_SOCKET_CONNECTION')
})
} catch (e) {
console.error(e)
}
})