register new xmpp account with node-xmpp ( node.js ) - node.js

I'm looking at 'XEP-0077 in-band registration' about how to register a new XMPP account. Here is my code. I use node-xmpp to connect my node.js application to an ejabberd server.
var net = require('net');
var xmpp = require('node-xmpp');
var cache = new Object();
net.createServer( function(socket) {
socket.setEncoding('utf8');
socket.addListener('data',function(data) {
data = data.substr(0,data.length-2);
if(cache.admin==undefined && data=='login') {
var ejabberd =new xmpp.Client({jid:"admin#mine",password:'12345',host:'192.168.7.202',port:'5222'});
cache.admin = ejabberd;
cache.admin.addListener('online',function() {
cache.admin.send(new xmpp.Element('presence',{type:'chat'}).c('show').c('status').t('mine status'));
cache.admin.send(new xmpp.Element('iq',{type:'get',id:'reg1'}).c('query',{xmlns:'jabber:iq:register'}));
})
cache.admin.addListener('stanza',function(stanza) {
if(stanza.is('iq')) {
console.log(stanza.children[1]);
}
})
cache.admin.addListener('end',function() {
cache.admin.end();
cache.admin = undefined;
})
}
if(cache.admin!=undefined && data=='logout') {
cache.admin.end();
cache.admin = undefined;
} else if(cache.admin!=undefined && data=='register') {
cache.admin.send(new xmpp.Element('iq',{type:'set',id:'reg1'}).c('query',{xmlns:'jabber:iq:register'}).c('username').t('alow').up().c('password').t('test'));
}
});
}).listen(5000);
If i run this code, I get this error:
{ name: 'error',
parent:
{ name: 'iq',
parent: null,
attrs:
{ from: 'admin#mine',
to: 'admin#mine/20108892991316770090454637',
id: 'reg1',
type: 'error',
xmlns: 'jabber:client',
'xmlns:stream': 'http://etherx.jabber.org/streams' },
children: [ [Object], [Circular] ] },
attrs: { code: '403', type: 'auth' },
children:
[ { name: '**forbidden**',
parent: [Circular],
attrs: [Object],
children: [] } ] }
In 'XEP-0077: In-Band Registration' it says that the forbidden reason means that "The sender does not have sufficient permissions to cancel the registration".
How can I get such permissions?

I have been strugling with something similar, I wanted to register a new user account via in-band registraton from nodejs to an ejabberd server running in ubuntu. Here is what I did and worked for me:
//Dependencies
var xmpp = require('node-xmpp');
//Host configuration
var host = "localhost";
var port = "5222";
var admin = "sebastian#localhost";
var adminPass = "adminPass";
var connection = new xmpp.Client({
jid: admin,
password: adminPass,
host: host,
port: port
});
//user to be registered name & pass
var newUserName = "pepe";
var newUserPass = "pepePass";
//Stream
var iq = "<stream:stream xmlns:stream='http://etherx.jabber.org/streams' xmlns='jabber:component:accept' to='localhost'><iq type='set' id='reg2'><query xmlns='jabber:iq:register'><username>" + newUserName + "</username><password>" + newUserPass + "</password></query></iq></stream>";
//Send
connection.send(iq);
//End
connection.end();
The var iq is kind of messy, I suppose that if you know how to use Strophe.js in a propper way that part could look a little bit nicer and cleaner. I was missing the section of the xml, it seems that if you want to send a stream, you have to provide a valid ejabberd namespace, that was what was failing for me. Hope this helps you sort your problem out.

Which server are you using? Are you sure it has XEP-77 enabled? Test with an existing client. Ensure that the account you're trying to create does not already exist. Ensure that the account has the correct domain name.

Related

How gRPC-web handles bytes data from server-side streaming?

I want to transmit a sample video file from backend grpc service to the browser using grpc-web, I did some tweaks based on official hello world tutorial. Btw, nothing changed in the envoy configuration. The video file is split into 17 chunks, I can receive 17 messages in browser, however there is nothing inside, what should do so I can get the data?
protobuf definition:
syntax = "proto3";
package helloworld;
service Greeter {
rpc SayHello (HelloRequest) returns (stream HelloReply);
}
message HelloRequest {}
message HelloReply {
bytes message = 1;
}
server.js:
var PROTO_PATH = __dirname + '/helloworld.proto';
var grpc = require('grpc');
var fs = require('fs');
var protoLoader = require('#grpc/proto-loader');
var packageDefinition = protoLoader.loadSync(
PROTO_PATH,
{keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true
});
var protoDescriptor = grpc.loadPackageDefinition(packageDefinition);
var helloworld = protoDescriptor.helloworld;
function doSayHello(call) {
let count = 0;
let videoDataStream = fs.createReadStream('./sample.mp4');
videoDataStream.on('data',function(chunk){
console.log(chunk);
console.log(++count);
call.write({videoStream: chunk});
// call.write(chunk);
}).on('end',function(){
call.end();
});
}
function getServer() {
var server = new grpc.Server();
server.addService(helloworld.Greeter.service, {
sayHello: doSayHello,
});
return server;
}
if (require.main === module) {
var server = getServer();
server.bind('0.0.0.0:9090', grpc.ServerCredentials.createInsecure());
server.start();
}
exports.getServer = getServer;
client.js:
const {HelloRequest, HelloReply} = require('./helloworld_pb.js');
const {GreeterClient} = require('./helloworld_grpc_web_pb.js');
var client = new GreeterClient('http://localhost:8080');
var request = new HelloRequest();
client.sayHello(request).on('data', function(chunk){
//console.log(chunk.getMessage());
console.log(chunk);
});
Anyway, in case there is problem with proxy, below is my envoy.yaml:
admin:
access_log_path: /tmp/admin_access.log
address:
socket_address: { address: 0.0.0.0, port_value: 9901 }
static_resources:
listeners:
- name: listener_0
address:
socket_address: { address: 0.0.0.0, port_value: 8080 }
filter_chains:
- filters:
- name: envoy.http_connection_manager
config:
codec_type: auto
stat_prefix: ingress_http
route_config:
name: local_route
virtual_hosts:
- name: local_service
domains: ["*"]
routes:
- match: { prefix: "/" }
route:
cluster: greeter_service
max_grpc_timeout: 0s
cors:
allow_origin_string_match:
- prefix: "*"
allow_methods: GET, PUT, DELETE, POST, OPTIONS
allow_headers: keep-alive,user-agent,cache-control,content-type,content-transfer-encoding,custom-header-1,x-accept-content-transfer-encoding,x-accept-response-streaming,x-user-agent,x-grpc-web,grpc-timeout
max_age: "1728000"
expose_headers: custom-header-1,grpc-status,grpc-message
http_filters:
- name: envoy.grpc_web
- name: envoy.cors
- name: envoy.router
clusters:
- name: greeter_service
connect_timeout: 0.25s
type: logical_dns
http2_protocol_options: {}
lb_policy: round_robin
hosts: [{ socket_address: { address: host.docker.internal, port_value: 9090 }}]
the bytes logged on server side:
and below console output in browser:
Have you tried testing with a gRPC (rather than gRPC Web) client to eliminate the possibility that the proxy is the problem?
I'm not super familiar with the Node.JS implementation but...
Should it not be server.addProtoService(...)?
Also the message streamed by the server is:
message HelloReply {
bytes message = 1;
}
But you:
call.write({videoStream: chunk});
Should it not be:
call.write({message: chunk});

Distributed lock of Hazelcast using nodejs

I have the Hazelcast cluster server running in the 172.30.56.60, 61, 62
(i.e)
[ Member {
address: Address { host: '172.30.56.60', port: 5701, type: 4 },
uuid: 'bd6428f0-e888-453f-872f-6fe8296d751d',
isLiteMember: false,
attributes: {} },
Member {
address: Address { host: '172.30.56.61', port: 5701, type: 4 },
uuid: 'e0cd795a-0ca5-41ab-907a-492b61690a18',
isLiteMember: false,
attributes: {} },
Member {
address: Address { host: '172.30.56.62', port: 5701, type: 4 },
uuid: '0a834ae8-e707-4b5b-945b-362bfea08cf5',
isLiteMember: false,
attributes: {} } ]
I try to implement the Hazelcast distributed locking using nodejs using the following code,
// Initialize the hazelcast client instance.
var HazelcastClient = require('hazelcast-client').Client;
var Config = require('hazelcast-client').Config;
var config = new Config.ClientConfig();
config.networkConfig.addresses = [{host: '172.30.56.60', port: '5701'},{host: '172.30.56.61', port: '5701'}, {host: '172.30.56.62', port: '5701'}];
var lock = {};
var sleep = require('sleep');
HazelcastClient
.newHazelcastClient(config)
.then(function (hazelcastClient) {
lock = hazelcastClient.getLock("lock1");
// do stuff with lock
lock.lock();
console.log('Am locked in node with lock1...will be locked for 20 seconds');
sleep.sleep(20);
console.log('Unlocked now...');
lock.unlock();
process.exit();
});
I started the script node by node, I expected to establish the lock node by node, but instead it locks all the nodes in the same time. So it is not working as a distributed lock, so all the script started and ending in the same time (NOTE : For testing I provided 20 seconds sleep)
Please let me know, How to establish the distributed lock using node js in Hazelcast.
I found the answer myself, I didn't realize the return of promise, my bad (new to nodejs)
// Initialize the hazelcast client instance.
var HazelcastClient = require('hazelcast-client').Client;
var Config = require('hazelcast-client').Config;
var config = new Config.ClientConfig();
config.networkConfig.addresses = [{host: '172.30.56.60', port: '5701'},{host: '172.30.56.61', port: '5701'}, {host: '172.30.56.62', port: '5701'}];
var sleep = require('sleep');
// Test process
HazelcastClient
.newHazelcastClient(config)
.then(function (hazelcastClient) {
var lock = hazelcastClient.getLock('rowId_tablename');
// lock the code here
lock.lock().then(function() {
console.log('Am locked in node with lock3...will be locked for 20 seconds');
sleep.sleep(20);
// unlock after process
return lock.unlock();
}).then(function() {
console.log('unlocked now');
});
});

I got no response from the Node.js Bloomberg API package (blpapi)

I'm working on a Node.js project and I need to price some stocks with the Bloomberg API. I found out that there's an NPM package for this API, so I had it installed and started testing it according to https://github.com/bloomberg/blpapi-node but I'm getting no responses.
This is my code:
var blpapi = require('blpapi');
var bloombergPricing = function ()
{
var session = new blpapi.Session({ host: '127.0.0.1', port: 8194 });
session.on('SessionStarted', function(m) {
console.log('bonjou');
session.openService('//blp/mktdata', 1);
});
var securities = [
{ security: 'AAPL US Equity', correlation: 0, fields: ['LAST_TRADE'] },
{ security: 'GOOG US Equity', correlation: 1, fields: ['LAST_TRADE'] }
];
session.on('ServiceOpened', function(m) {
console.log(session);
if (m.correlations[0].value == service_id) {
console.log(session);
session.subscribe(securities);
}
});
session.on('MarketDataEvents', function(m) {
if (m.data.hasOwnProperty('LAST_TRADE')) {
console.log(securities[m.correlations[0].value].security,
'LAST_TRADE', m.data.LAST_TRADE);
}
});
}
Is this package still working? If not, how is it possible to call the Java Bloomberg API from Node.js?
Thank you very much.
I think you're missing a session.start(); at the end of the function. This will trigger off the connection.
edit to include code that works for me:
var blpapi = require('blpapi');
var bloombergPricing = function ()
{
var session = new blpapi.Session({ host: '127.0.0.1', port: 8194 });
session.on('SessionStarted', function(m) {
console.log('bonjou');
session.openService('//blp/mktdata', 1);
});
var securities = [
{ security: 'AAPL US Equity', correlation: 0, fields: ['LAST_TRADE'] },
{ security: 'GOOG US Equity', correlation: 1, fields: ['LAST_TRADE'] }
];
session.on('ServiceOpened', function(m) {
console.log(session);
if (m.correlations[0].value == 1) {
console.log(session);
session.subscribe(securities);
}
});
session.on('MarketDataEvents', function(m) {
if (m.data.hasOwnProperty('LAST_TRADE')) {
console.log(securities[m.correlations[0].value].security,
'LAST_TRADE', m.data.LAST_TRADE);
}
});
session.start();
}
bloombergPricing();

How to send trap messages from linux to snmp agent on my local machine?

I could not find any solution on internet so i decided to post my question on stackoverflow, I have a program on linux server when i execute it should send trap messages to my local snmp agent. I am setting host name to my system IP address, so i see all logs are printing from the program but its not sedning traps to my local snmp agent any idea how i can make it work in this case ?
app.js
var snmp = require("net-snmp");
var msg = require('./event.js');
function process (msg) {
var host = msg.event.body.trapHost;
var snmpVersion = snmp.Version1;
if (msg.event.body.snmpVersion === "v2"){
snmpVersion = snmp.Version2c
}
var sessionOptions = {
port: 161,
retries: 1,
timeout: 5000,
transport: "udp4",
trapPort: msg.event.body.trapPort,
version: snmpVersion
};
//Create snmp Session
var session = snmp.createSession(host,"public",sessionOptions);
var trapOid = msg.event.body.snmp.trapOID;
var varbinds = msg.event.body.snmp.appOIDs;
var options = {upTime: 1000};
varbinds.forEach(function (oids) {
oids.type = snmp.ObjectType.OctetString;
console.log(oids.value);
});
try {
if (snmp.isVarbindError(varbinds)) {
Logger.error(snmp.varbindError(varbinds));
} else {
session.trap(trapOid, varbinds, options, function (error) {
if (error)
console.log(error);
else
console.log('SNMP successfully delivered');
});
}
} catch (e) {
console.log("SNMP processing error: " + e);
}
};
process(msg);
event.js
module.exports = {
event: {
header: {
eventSource: "d-snmp"
},
body: {
snmp: {
trapHost:"135.68.100.236",
trapPort:"162",
trapOID:"1.3.6.1.4.140.625",
appOIDs: [
{
oid: "1.3.6.1.4.140.900",
type: "",
value: "Problem with Hardware"
},
{
oid: "1.3.6.1.4.140.700",
type: "",
value: "Hardware ok"
}
]
},
snmpVersion: "v2"
}
}
};

node-xmpp --- Create a Persistant and Private Chatroom

I need to create a Private and Persistent Chat room dynamically via Node that does not automatically delete itself.
I've searched the net and couldn't find much on how to do it. This is the code snippet I use to create the chatroom:
var cl = new xmpp.Client({
jid: jabber_creds.jid,
password: jabber_creds.password,
host: jabber_creds.host,
port: jabber_creds.port
});
cl.on('online', function() {
var room_jid = jabber_creds.room_jid.replace("%s", chatRoomName);
// join room (and request no chat history)
cl.send(new xmpp.Element('presence', { to: room_jid }).
c('x', { xmlns: 'http://jabber.org/protocol/muc' })
);
// create room
cl.send(new xmpp.Element('iq', { to: room_jid, id: 'create', type: 'set' }).
c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' }).
c('x', { xmlns: 'jabber:x:data',type: 'submit' })
);
});
Chat room persistence is handled at the server not the client. Yes the client can request that a server hold onto a chat room but you can't actually persist it from the client. Check with the server documentation that you are using to make sure it supports this.
Try to follow XEP-0045
http://xmpp.org/extensions/xep-0045.html#createroom
Just read The workflow for creating and configuring such rooms is as follows section
You need to do the next:
Send 1st presence to a new room
Server returns you a couple of messages that room was created, but you should unlock it
You should create configuration form and send to the server. In this form you can set 'Persistent' type & 'Only members' type
Server will return you success result if everything is OK
You can reference https://github.com/node-xmpp/node-xmpp/blob/master/examples/create_room.js and send configuration you want by XEP-0045
//create_room.js
'use strict'
var xmpp = require('../index')
,argv = process.argv
if (argv.length < 5) {
console.error('Usage: node create_room.js <my-jid> <my-password> <room-name>')
process.exit(1)
}
var cl = new xmpp.Client({ jid: argv[2], password: argv[3] })
cl.on('online', function(data) {
var userJid = data.jid.user + '#' + data.jid.domain,
roomJid = argv[4] + '#conference.' + data.jid.domain,
pres,
iq
console.log('Connected as ' + userJid + '/' + data.jid.resource)
console.log('Create room - ' + argv[4])
pres = new xmpp.Element(
'presence',
{ from: userJid, to: roomJid + '/' + data.jid.user })
.c('x', {'xmlns':'http://jabber.org/protocol/muc'})
cl.send(pres.tree())
iq = new xmpp.Element(
'iq',
{ to: roomJid, type: 'set' })
.c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' })
.c('x', { xmlns: "jabber:x:data", type: "submit"})
//set room to be hidden by sending configuration. ref: http://xmpp.org/extensions/xep-0045.html
iq.c('field', { 'var': 'FORM_TYPE' })
.c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up()
.c('field', { 'var': 'muc#roomconfig_publicroom'})
.c('value').t('0').up().up()
cl.send(iq.tree())
// exit later for sending configuration done
setTimeout(function() {
cl.end()
}, 100)
})
cl.on('error', function(e) {
console.error(e)
process.exit(1)
})

Resources