

module.exports = {


    friendlyName: 'Subscribe to socket Create',
  
  
    description: 'Subscribe create.',
  
  
    inputs: {
    
    },
  
  
    exits: {
      fail:{
        statusCode: 400
      }
    },
  
  
  fn: async function (inputs, exits) {
    console.log('REQ', this.req.isSocket)
    if (!this.req.isSocket) {
      throw { fail : {message: 'Not socket req'}}
    }
    let parts = this.req.socket.handshake.query['Authorization'].split(' ');
      if (parts.length !== 2) {
        proceed("authentification fail", false)
      }
      let scheme = parts[0];
      let credentials = parts[1];

      if (!/^Bearer$/i.test(scheme) || !credentials || credentials == null) {
        throw {fail:{message:'Req failed'}}
      }

      let token = await Token.findOne({
        token_salt: credentials
      })
      if (!token) {
        throw { fail: { message: 'Req failed' } }
      }
      try {
        var req = this.req;
        await jwt.verify(token.token_salt, sails.config.custom.secret, async function (err, decoded) {
          if (err) {
            throw { fail: { message: 'Req failed' } }
          }
          let user = await User.find(decoded.data.id).then(_.first)
          if (!user) {
            throw { fail: { message: 'Req failed' } }
          }
          console.log('USER', user)

          if (user.groupe /*!== 'VENTE'*/) {
            sails.sockets.join(req, 'createCommandeSocket')
            console.log('subscribe _____ createCommandeSocket')
          }

          /*let userRole = await Role.findOne(user.role)
          if (!userRole) {
            throw { fail: { message: 'Req failed' } }
          }

          if (userRole.slug == 'SUPPORT_ROLE') {
            sails.sockets.join(req, 'demandeSocket')
            console.log('subscribe _____')
          }*/
        })
      } catch (e) {
        //console.log("isAuthorized/token verify error=>",e)
        throw { fail: { message: 'Req failed' } }
      }
        // All done.
      return exits.success({Done: true});
  
    }
  
  
  };
  