-
Notifications
You must be signed in to change notification settings - Fork 3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Example of usage #5
Comments
Anyone? |
We are using this in a project. I'll see if I can't find some bits for you that might be useful. |
Frontend is going to be up to you, but we are using this with our authentication layer. Perhaps it may give you an idea? //api/services/WebSocketService.js
'use strict'
const Service = require('trails-service')
const _ = require('lodash')
const rooms = require('primus-rooms')
const emitter = require('primus-emitter')
/**
* @module WebSocketService
* @description WebSocket management service
*/
module.exports = class WebSocketService extends Service {
/**
* Authenticate the user for websocket connection from query param ?token=
* @param req
* @param authorized
* @returns {*}
* @private
*/
_authorize(req, authorized) {
const token = req.query.token
if (!token) {
return authorized(new Error('No auth token'))
}
const jwtConfig = this.app.config.passport.strategies.jwt
const jwtOptions = _.clone(jwtConfig.tokenOptions)
jwtOptions.algorithms = jwtOptions.algorithm
delete jwtOptions.algorithm
const jwtVerifier = jwtConfig.strategy.JwtVerifier
jwtVerifier(token, jwtConfig.options.secretOrKey, jwtOptions, (err, payload) => {
if (err) {
authorized(err)
}
else {
req.user = payload.user
authorized()
}
})
}
init() {
this.app.sockets.use('rooms', rooms)
this.app.sockets.use('emitter', emitter)
this.app.sockets.authorize(this._authorize)
this.app.sockets.on('connection', spark => {
const user = spark.request.user // Retrieve connected user
spark.join('user_' + user.id)
spark.on('join', (room, fn) => {
this.app.services.PermissionService.isUserAllowed(user, room, 'access').then(perm => {
if (perm && perm.length > 0) {
spark.join(room, fn)
}
}).catch(err => this.log.error(err))
})
spark.on('leave', (room, fn) => {
spark.leave(room, fn)
})
spark.on('data', data => {
//spark.room('user_' + user.id).write(data + ' ' + user.email)
this.log.debug(spark.id, 'received message:', data, spark.rooms())
})
})
this.app.sockets.on('disconnection', spark => {
const user = spark.request
spark.leave('user_' + user.id)
})
}
} |
Thank you :) Let me experiment with it based on your example. My apologies for my late response! |
@scott-wyatt |
We use traikpack-bootstrap who run only once :) |
Thanks @jaumard
|
For some reason i cant connect to websocket server, i try to connect from dwst websocket client (chrome app), no luck -.- |
Can we have an example of usage? Or can I maybe e-mail you about this?
The text was updated successfully, but these errors were encountered: