I am trying to connect my custom mysql database to Auth0.But i am getting the following error
[Error] ECONNREFUSED - connect ECONNREFUSED 127.0.0.1:3306
my code is,
function create (user, callback) {
var connection = mysql({
host : 'localhost',
user : 'db_user',
password : 'db_password',
database : 'db_name'
});
connection.connect();
var query = "INSERT INTO users SET ?";
var insert = {
password: bcrypt.hashSync(user.password, 10),
email: user.email
};
connection.query(query, insert, function (err, results) {
if (err) return callback(err);
if (results.length === 0) return callback();
callback(null);
});
}
The script runs on Auth0 servers, so localhost would be auth0 itself. You need to use a network address that is reachable from Auth0 servers.
You can check ngrok for bridging your own dev server with a cloud service (like Auth0).
You get that error because Auth0 (Where the script runs) cannot reach your DB server. When the script runs Auth0 goes to localhost, in this case, the same Auth0, hence your connection is refused. You will have to:
bridge your connection with ngrok as Eugenio Pace said, exposing your DB to the internet (thus making it visible to Auth0)
And change the var connection attributes accordingly. (the server url and the user creds)
You can also check Auth0 documentation here
Related
I am trying to use Socket.IO in Node.js, and am trying to allow the server to give an identity to each of the Socket.IO clients. As the socket code is outside the scope of the http server code, it doesn't have easy access to the request information sent, so I'm assuming it will need to be sent up during the connection. What is the best way to
1) get the information to the server about who is connecting via Socket.IO
2) authenticate who they say they are (I'm currently using Express, if that makes things any easier)
Use connect-redis and have redis as your session store for all authenticated users. Make sure on authentication you send the key (normally req.sessionID) to the client. Have the client store this key in a cookie.
On socket connect (or anytime later) fetch this key from the cookie and send it back to the server. Fetch the session information in redis using this key. (GET key)
Eg:
Server side (with redis as session store):
req.session.regenerate...
res.send({rediskey: req.sessionID});
Client side:
//store the key in a cookie
SetCookie('rediskey', <%= rediskey %>); //http://msdn.microsoft.com/en-us/library/ms533693(v=vs.85).aspx
//then when socket is connected, fetch the rediskey from the document.cookie and send it back to server
var socket = new io.Socket();
socket.on('connect', function() {
var rediskey = GetCookie('rediskey'); //http://msdn.microsoft.com/en-us/library/ms533693(v=vs.85).aspx
socket.send({rediskey: rediskey});
});
Server side:
//in io.on('connection')
io.on('connection', function(client) {
client.on('message', function(message) {
if(message.rediskey) {
//fetch session info from redis
redisclient.get(message.rediskey, function(e, c) {
client.user_logged_in = c.username;
});
}
});
});
I also liked the way pusherapp does private channels.
A unique socket id is generated and
sent to the browser by Pusher. This is
sent to your application (1) via an
AJAX request which authorizes the user
to access the channel against your
existing authentication system. If
successful your application returns an
authorization string to the browser
signed with you Pusher secret. This is
sent to Pusher over the WebSocket,
which completes the authorization (2)
if the authorization string matches.
Because also socket.io has unique socket_id for every socket.
socket.on('connect', function() {
console.log(socket.transport.sessionid);
});
They used signed authorization strings to authorize users.
I haven't yet mirrored this to socket.io, but I think it could be pretty interesting concept.
I know this is bit old, but for future readers in addition to the approach of parsing cookie and retrieving the session from the storage (eg. passport.socketio ) you might also consider a token based approach.
In this example I use JSON Web Tokens which are pretty standard. You have to give to the client page the token, in this example imagine an authentication endpoint that returns JWT:
var jwt = require('jsonwebtoken');
// other requires
app.post('/login', function (req, res) {
// TODO: validate the actual user user
var profile = {
first_name: 'John',
last_name: 'Doe',
email: 'john#doe.com',
id: 123
};
// we are sending the profile in the token
var token = jwt.sign(profile, jwtSecret, { expiresInMinutes: 60*5 });
res.json({token: token});
});
Now, your socket.io server can be configured as follows:
var socketioJwt = require('socketio-jwt');
var sio = socketIo.listen(server);
sio.set('authorization', socketioJwt.authorize({
secret: jwtSecret,
handshake: true
}));
sio.sockets
.on('connection', function (socket) {
console.log(socket.handshake.decoded_token.email, 'has joined');
//socket.on('event');
});
The socket.io-jwt middleware expects the token in a query string, so from the client you only have to attach it when connecting:
var socket = io.connect('', {
query: 'token=' + token
});
I wrote a more detailed explanation about this method and cookies here.
Here is my attempt to have the following working:
express: 4.14
socket.io: 1.5
passport (using sessions): 0.3
redis: 2.6 (Really fast data structure to handle sessions; but you can use others like MongoDB too. However, I encourage you to use this for session data + MongoDB to store other persistent data like Users)
Since you might want to add some API requests as well, we'll also use http package to have both HTTP and Web socket working in the same port.
server.js
The following extract only includes everything you need to set the previous technologies up. You can see the complete server.js version which I used in one of my projects here.
import http from 'http';
import express from 'express';
import passport from 'passport';
import { createClient as createRedisClient } from 'redis';
import connectRedis from 'connect-redis';
import Socketio from 'socket.io';
// Your own socket handler file, it's optional. Explained below.
import socketConnectionHandler from './sockets';
// Configuration about your Redis session data structure.
const redisClient = createRedisClient();
const RedisStore = connectRedis(Session);
const dbSession = new RedisStore({
client: redisClient,
host: 'localhost',
port: 27017,
prefix: 'stackoverflow_',
disableTTL: true
});
// Let's configure Express to use our Redis storage to handle
// sessions as well. You'll probably want Express to handle your
// sessions as well and share the same storage as your socket.io
// does (i.e. for handling AJAX logins).
const session = Session({
resave: true,
saveUninitialized: true,
key: 'SID', // this will be used for the session cookie identifier
secret: 'secret key',
store: dbSession
});
app.use(session);
// Let's initialize passport by using their middlewares, which do
//everything pretty much automatically. (you have to configure login
// / register strategies on your own though (see reference 1)
app.use(passport.initialize());
app.use(passport.session());
// Socket.IO
const io = Socketio(server);
io.use((socket, next) => {
session(socket.handshake, {}, next);
});
io.on('connection', socketConnectionHandler);
// socket.io is ready; remember that ^this^ variable is just the
// name that we gave to our own socket.io handler file (explained
// just after this).
// Start server. This will start both socket.io and our optional
// AJAX API in the given port.
const port = 3000; // Move this onto an environment variable,
// it'll look more professional.
server.listen(port);
console.info(`🌐 API listening on port ${port}`);
console.info(`🗲 Socket listening on port ${port}`);
sockets/index.js
Our socketConnectionHandler, I just don't like putting everything inside server.js (even though you perfectly could), especially since this file can end up containing quite a lot of code pretty quickly.
export default function connectionHandler(socket) {
const userId = socket.handshake.session.passport &&
socket.handshake.session.passport.user;
// If the user is not logged in, you might find ^this^
// socket.handshake.session.passport variable undefined.
// Give the user a warm welcome.
console.info(`⚡︎ New connection: ${userId}`);
socket.emit('Grettings', `Grettings ${userId}`);
// Handle disconnection.
socket.on('disconnect', () => {
if (process.env.NODE_ENV !== 'production') {
console.info(`⚡︎ Disconnection: ${userId}`);
}
});
}
Extra material (client):
Just a very basic version of what the JavaScript socket.io client could be:
import io from 'socket.io-client';
const socketPath = '/socket.io'; // <- Default path.
// But you could configure your server
// to something like /api/socket.io
const socket = io.connect('localhost:3000', { path: socketPath });
socket.on('connect', () => {
console.info('Connected');
socket.on('Grettings', (data) => {
console.info(`Server gretting: ${data}`);
});
});
socket.on('connect_error', (error) => {
console.error(`Connection error: ${error}`);
});
References:
I just couldn't reference inside the code, so I moved it here.
1: How to set up your Passport strategies: https://scotch.io/tutorials/easy-node-authentication-setup-and-local#handling-signupregistration
This article (http://simplapi.wordpress.com/2012/04/13/php-and-node-js-session-share-redi/) shows how to
store sessions of the HTTP server in Redis (using Predis)
get these sessions from Redis in node.js by the session id sent in a cookie
Using this code you are able to get them in socket.io, too.
var io = require('socket.io').listen(8081);
var cookie = require('cookie');
var redis = require('redis'), client = redis.createClient();
io.sockets.on('connection', function (socket) {
var cookies = cookie.parse(socket.handshake.headers['cookie']);
console.log(cookies.PHPSESSID);
client.get('sessions/' + cookies.PHPSESSID, function(err, reply) {
console.log(JSON.parse(reply));
});
});
use session and Redis between c/s
Server side
io.use(function(socket, next) {
// get here session id
console.log(socket.handshake.headers.cookie); and match from redis session data
next();
});
this should do it
//server side
io.sockets.on('connection', function (con) {
console.log(con.id)
})
//client side
var io = io.connect('http://...')
console.log(io.sessionid)
I Currently have a php website working. Here i can keep and use any session data to keep track of my user. however if i simply connect to my node.js game from this website using a simple hyper link such as...
<a href="http://localhost:8080">
This works and i do connect to my game running on a local host on that port here is the coded for setting up the node.js game.
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const TDSGame = require('./../tds-game');
const { log } = require('console');
const app = express();
// path for our client files
const clientPath = `${__dirname}/../client`;
console.log(`Serving static from ${clientPath}`);
// for static middleware from express
app.use(express.static(clientPath));
const server = http.createServer(app);
const io = socketio(server);
var waitingPlayers = [];
io.on('connection', (sock) => {
if(waitingPlayers.length == 3){
waitingPlayers.push(sock);
new TDSGame(waitingPlayers);
waitingPlayers = [];
}
else{
waitingPlayers.push(sock);
sock.emit('message', 'Waiting for opponent');
}
sock.on('message', (text)=>{
// io.emmit everyone connected to the server receives the message
io.emit('message', text);
});
});
server.on('error', (err)=>{
console.log('Server Error', err);
});
server.listen(8080, ()=>{
console.log('TDS started on 8080');
});
What would be a good way of passing the players i dunno hash and
username or something. to the the game so on connection i can get
these variables and check to see if my player exists in the database?
if so then pass these players and sockets to the game logic?
I am struggling any help would be much appreciated thank you :)
you can add extra params to the socket connection URL "http://localhost:8080?foo=bar&hi=hello" and through that, you can get the data when the socket-clint connects ( io.on('connection') event ).
And you can delete the data from the array (
waitingPlayers ) when it disconnects. Through this way you can manage the connections.
I do use the socket.io for my chat-app where I use redis instead of Array to store the connection id to send and receive messages.
I have a local Minecraft Server set up. I decided to get myself my own domain, because ips arent really pretty. The problem is, that because the ip address of my router changes every night, I can't just do a A-record to my ip address. Instead I need a dynamic dns provider which allows me the use of my own domain. I could not seem to find one, so I coded it by myself with php (I have a free web server with a static ip address). Here's the code of the .php-file:
<?
$usernameTest = $_GET["username"];
$passTest = $_GET["pass"];
$ipaddr = $_GET["ipaddr"];
$username = "USERNAME";
$pass = "*****";
$port = ":25565";
$serverIPtxt = "serverIP.txt";
if(file_exists($serverIPtxt)) {
if($usernameTest == $username) {
if($passTest == $pass) {
$a = fopen("$serverIPtxt", "w");
fwrite($a, $ipaddr);
fclose($a);
echo $ipaddr;
}
} else {
$a = fopen("$serverIPtxt", "r+");
$dynIP = fread($a, filesize($serverIPtxt));
fclose($a);
$url="http://".$dynIP."".$port;
header("Location: $url", true);
die();
}
}
?>
My router is automaticly applying the correct ip address, so in theory I should be able to connect to the minecraft server with my new domain, but I cant. Instead Minecraft gives me this error:
[13:52:38] [Client thread/INFO]: Connecting to DOMAIN, 25565
[13:52:39] [Server Connector #5/ERROR]: Couldn't connect to server
java.net.ConnectException: Connection refused: no further information: DOMAIN/IPADDRESS:25565
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method) ~[?:1.8.0_25]
at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:716) ~[?:1.8.0_25]
at io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:208) ~[NioSocketChannel.class:4.0.23.Final]
at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:287) ~[AbstractNioChannel$AbstractNioUnsafe.class:4.0.23.Final]
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:528) ~[NioEventLoop.class:4.0.23.Final]
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:468) ~[NioEventLoop.class:4.0.23.Final]
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:382) ~[NioEventLoop.class:4.0.23.Final]
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:354) ~[NioEventLoop.class:4.0.23.Final]
at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:116) ~[SingleThreadEventExecutor$2.class:4.0.23.Final]
at java.lang.Thread.run(Thread.java:745) ~[?:1.8.0_25]
What am I doing wrong? Or does Minecraft just not support php redirects?
Minecraft does not use HTTP! It uses its own protocol based on TCP.
The best option, which I have used in the past, is to run a dynamic ip updater client.
Get yourself a No-IP domain name (e.g. myname.ddns.net)
Download the dynamic updater client (available for Windows, Mac or Linux)
Set your custom domain name as a CNAME to point to myname.ddns.net (your NoIP domain name)
Give players your custom domain name (e.g. myname.com). This will refer the client to myname.ddns.net through the CNAME record which will in turn refer to your dynamic IP (e.g. xxx.xxx.xxx.xxx) as an A record.
After this you will be able to connect to your server with your custom domain and the dynamic updater will keep the dynamic IP up to date automatically.
Nodejs trying to connect to a database and pulls me hostinger this error before i use http://www.freemysqlhosting.net/ was similarly placing the host, user, pass and name of the database and did not erro I think that is the port but idk .. I'm using: app.listen (process.env.PORT || 3000)
So I'm doing:
var connection = mysql.createConnection ({
host: 'mysql.hostinger.es',
user: 'XXXXX',
password: 'XX',
database: 'XXX',
});
Error I get:
It tells you that it couldn't resolve mysql.hostinger.es
Check it's the good hostname or try to set directly the IP address.
My project is to make a module enrollment system for our university. So I contacted the IT people in my university for details to authenticate the students into the system. We are developing the system using the existing university login. They gave me some LDAP information, I don't know the usage of that.
I'm using PHP,Mysql on an Apacha server.
How can I authenticate a user logging into my system, given his userid and password with the LDAP information.
Given below is the LDAP information(i have changed the domain name etc.)
LDAP information for blueroom.ac.uk domain
LDAP Host : ad.blueroom.ac.uk
LDAP port no: 389
BASE DN : ou=bluebird, dc=bluebird, dc=ac, dc=my
LDAP account to bind : cn = kikdap, ou=servacc, dc=bluebird,dc=ac,dc=uk
LDAP account password : ********
Attribute : sAMAccountName
The general procedure would be (relevant ext/ldap php commands in brackets):
connect to LDAP server using the "LDAP Host" and "LDAP port no" (ldap_connect()) and set the correct connection options (ldap_set_option()), especially LDAP_OPT_PROTOCOL_VERSION and LDAP_OPT_REFERRALS
bind to LDAP server using the "LDAP account to bind" and "LDAP account password" (ldap_bind()) - if you're authenticating against an Active Directory server you can directly use the username and password from the login page and skip all the following steps.
search the tree for a matching user entry/object by specifing the "BASE DN" and the appropriate LDAP filter - most likely something like (&(objectClass=user)(sAMAccountName=%s)) where %s should be replaced by the username to be authenticated (ldap_search())
check if the number of returned entries is 1 (if <> 1 then something has gone wrong, e.g. no user found or multiple users found)
retrive the distinguished name (DN) of this single entry (ldap_get_dn())
use the DN found in the last step to try to bind to the LDAP server with the password given at the authentication page (ldap_bind())
if the bind succeeds then everything is OK, if not, most likely the password is wrong
It's really not as hard as it sounds at first. Generally I'd propose to use some sort of standard library for authenticating against a LDAP server such as the Net_LDAP2 PEAR package or Zend_Ldap out of the Zend Framework. I have no experience with actually using Net_LDAP2 (although I know the code quite well) but Zend_Ldap works very well against Active Directory servers or ADAMS servers (which is obviously what you're working with).
This will do the trick using Zend_Ldap:
$options = array(
'host' => 'ad.blueroom.ac.uk',
'useStartTls' => true,
'accountDomainName' => 'blueroom.ac.uk',
'accountCanonicalForm' => 4,
'baseDn' => 'ou=bluebird,dc=bluebird,dc=ac,dc=my',
);
$ldap = new Zend_Ldap($options);
try {
$ldap->bind('user', 'password');
} catch (Zend_Ldap_Exception $e) {
// something failed - inspect $e
}
// bind successful
$acctname = $ldap->getCanonicalAccountName('user', Zend_Ldap::ACCTNAME_FORM_DN);
You might try http://code.activestate.com/recipes/101525/ while referring to http://us3.php.net/ldap and other results from a Google search for [php ldap authentication].
#Stephen provided good points. Here is my plain PHP code to authenticate using AD:
first you need to know this parameters: server host, user domain (you need also base dn if you want query AD).
use the following code:
$ldap = ldap_connect($host); // e.g. 165.5.54.6 or an URL
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3); // Recommended for AD
ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
$bind = ldap_bind($ldap, $username.'#'.$userDomain, $passwrod);
if($bind){
// successful authentication.
}
you could use http://pear.php.net/package/Net_LDAP2/docs
it's nice and works.
Example of connection taken by the doc:
// Inclusion of the Net_LDAP2 package:
require_once 'Net/LDAP.php';
// The configuration array:
$config = array (
'binddn' => 'cn=admin,ou=users,dc=example,dc=org',
'bindpw' => 'password',
'basedn' => 'dc=example,dc=org',
'host' => 'ldap.example.org'
);
// Connecting using the configuration:
$ldap = Net_LDAP2::connect($config);
// Testing for connection error
if (PEAR::isError($ldap)) {
die('Could not connect to LDAP-server: '.$ldap->getMessage());
}