Skip to content
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

Open
weyert opened this issue Jul 1, 2016 · 8 comments
Open

Example of usage #5

weyert opened this issue Jul 1, 2016 · 8 comments

Comments

@weyert
Copy link

weyert commented Jul 1, 2016

Can we have an example of usage? Or can I maybe e-mail you about this?

@weyert
Copy link
Author

weyert commented Jul 31, 2016

Anyone?

@scott-wyatt
Copy link
Member

We are using this in a project. I'll see if I can't find some bits for you that might be useful.

@scott-wyatt
Copy link
Member

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)
    })
  }
}

@weyert
Copy link
Author

weyert commented Aug 12, 2016

Thank you :) Let me experiment with it based on your example. My apologies for my late response!

@Nishchit14
Copy link

@scott-wyatt
Here, If init() will call two times then all events will be listening 2 times. How can you manage that ?
I think you are using WebSocketService.init() only one time.
Is there any way to initialise all socket events only one time when the server starts ?

@jaumard
Copy link
Contributor

jaumard commented Nov 23, 2016

We use traikpack-bootstrap who run only once :)

@Nishchit14
Copy link

Thanks @jaumard
it works bootstrap.js

module.exports = function (app) {
  app.sockets.on('connection', spark => {
    console.log('Connected', spark.id)
  })
}

@christiangelone
Copy link

For some reason i cant connect to websocket server, i try to connect from dwst websocket client (chrome app), no luck -.-

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants