Access to my application (in order)
Whitelist ip address
redirect to 404 on invalid ip
Check if last activity was > 2 hours ago
redirect to login page and expire session
Check if user is logged in, by looking at user data in $_SESSION
redirect to login page if not valid
Index.php
(notice it is very similar to this question):
/**
* Set Timezone
*/
date_default_timezone_set('Zulu');
/**
* Include globals and config files
*/
require_once('env.php');
/*
* Closure for providing lazy initialization of DB connection
*/
$db = new Database();
/*
* Creates basic structures, which will be
* used for interaction with model layer.
*/
$serviceFactory = new ServiceFactory(new RepositoryFactory($db), new EntityFactory);
$serviceFactory->setDefaultNamespace('\\MyApp\\Service');
$request = new Request();
$session = new Session();
$session->start();
$router = new Router($request, $session);
/*
* Whitelist IP addresses
*/
if (!$session->isValidIp()) {
$router->import($whitelist_config);
/*
* Check if Session is expired or invalid
*/
} elseif (!$session->isValid()) {
$router->import($session_config);
/*
* Check if user is logged in
*/
} elseif (!$session->loggedIn()) {
$router->import($login_config);
} else {
$router->import($routes_config);
}
/*
* Find matched route, or throw 400 header.
*
* If matched route, add resource name
* and action to the request object.
*/
$router->route();
/*
* Initialization of View
*/
$class = '\\MyApp\\View\\' . $request->getResourceName();
$view = new $class($serviceFactory);
/*
* Initialization of Controller
*/
$class = '\\MyApp\\Controller\\' . $request->getResourceName();
$controller = new $class($serviceFactory, $view);
/*
* Execute the necessary command on the controller
*/
$command = $request->getCommand();
$controller->{$command}($request);
/*
* Produces the response
*/
echo $view->render();
The $router->import() function takes a json file with the route configuration and creates the routes (Haven't decided if I'm going to keep that). My router is a modified version of Klein.
My Question
Is this a proper implementation of how to check the session data?
I would prefer to check that the user data in the session can be found in the database, but I would need to use a Service for that, and Services should only be accessed by the controller(?). I wouldn't know which controller to send the user to since the route configuration would change if the user was logged in.
For example, if someone was trying to go to www.myapp.com/orders/123, I would send them to the Orders controller if they were logged in, or the Session controller (to render the login page) if they weren't.
I have read the ACL Implementation from this question. But, unless I'm mistaken, that is for controlling access for users who are already logged in, not for users who aren't logged in. If this is not the case, could someone please explain how I would implement my ACL to check this?
I greatly appreciate any help since the search for this answer has given me really mixed solutions, and most of them I don't like or don't seem like clean solutions. Like a Session Manager, which is basically what I'm doing, but pretending not to. =/
UPDATED index.php (my solution)
/**
* Set Timezone
*/
date_default_timezone_set('Zulu');
/**
* Include globals and config files
*/
require_once('env.php');
/*
* Closure for providing lazy initialization of DB connection
*/
$db = new Database();
/*
* Creates basic structures, which will be
* used for interaction with model layer.
*/
$serviceFactory = new ServiceFactory(new MapperFactory($db), new DomainFactory);
$serviceFactory->setDefaultNamespace('\\MyApp\\Service');
include CONFIG_PATH.'routes.php';
$request = new Request();
$router = new Router($routes,$request);
/*
* Find matched route.
*
* If matched route, add resource name
* and command to the request object.
*/
$router->route();
$session = $serviceFactory->create('Session');
/*
* Whitelist Ip address, check if user is
* logged in and session hasn't expired.
*/
$session->authenticate();
/*
* Access Control List
*/
include CONFIG_PATH.'acl_settings.php';
$aclFactory = new AclFactory($roles,$resources,$rules);
$acl = $aclFactory->build();
$user = $session->currentUser();
$role = $user->role();
$resource = $request->getResourceName();
$command = $request->getCommand();
// User trying to access unauthorized page
if (!$acl->isAllowed($role, $resource, $command) {
$request->setResourceName('Session');
$request->setCommand('index');
if ($role === 'blocked') {
$request->setResourceName('Error');
}
}
/*
* Initialization of View
*/
$class = '\\MyApp\\View\\' . $request->getResourceName();
$view = new $class($serviceFactory, $acl);
/*
* Initialization of Controller
*/
$class = '\\MyApp\\Controller\\' . $request->getResourceName();
$controller = new $class($serviceFactory, $view, $acl);
/*
* Execute the necessary command on the controller
*/
$command = $request->getCommand();
$controller->{$command}($request);
/*
* Produces the response
*/
$view->{$command}
$view->render();
I start the session and authorize the user in the Session model. The session's currentUser will have a role of 'guest' if not logged in, or 'blocked' if it's IP address is not in the whitelist. I wanted to implement the Controller wrapper as suggested teresko's previous ACL post, but I needed something that would redirect the user's instead. I send them to their homepage (Session#index) if they try to access a page they aren't allowed to, or to Error#index if they are blocked. Session#index will let the View decide whether or not to display the homepage for a logged in user, or the login page if they aren't logged in (by checking the user's role). Maybe not the best solution, but doesn't seem too terrible.
Single Responsibility
Your session object is doing too many things. Sessions are more or less just for persistence across requests. The session shouldn't be doing any authentication logic. You store an identifier for the logged in user in the session, but the actual validation, logging in/out should be done in an authentication service.
Route Management
Importing different routes based on the users authentication status will not scale well and will be a pain to debug later when you have a lot more routes. It would be better to define all your routes in one place and use the authentication service to redirect if not authorized. I'm not very familiar with that router but looking at the documentation you should be able to so something like
$router->respond(function ($request, $response, $service, $app) {
$app->register('auth', function() {
return new AuthService();
}
});
Then on routes you need to be logged in for you can do something like
$router->respond('GET', '/resource', function ($request, $response, $service, $app) {
if( ! $app->auth->authenticate() )
return $response->redirect('/login', 401);
// ...
});
Related
The built-in controller for resetting the password Auth \ Reset Password Controller has the reset function
public function reset(Request $request)
{
$request->validate($this->rules(), $this->validationErrorMessages());
// Here we will attempt to reset the user's password. If it is successful we
// will update the password on an actual user model and persist it to the
// database. Otherwise we will parse the error and return the response.
$response = $this->broker()->reset(
$this->credentials($request), function ($user, $password) {
$this->resetPassword($user, $password);
}
);
// If the password was successfully reset, we will redirect the user back to
// the application's home authenticated view. If there is an error we can
// redirect them back to where they came from with their error message.
return $response == Password::PASSWORD_RESET
? $this->sendResetResponse($request, $response)
: $this->sendResetFailedResponse($request, $response);
}
Well, here we are working with the user and their incoming data. However, I can't understand where the work with the password_resets table (built-in) is going? After all, after password recovery, entries are added/deleted there. I think (maybe incorrectly) that this is implemented in the broker () method, but I can't find it in the hierarchy of traits, interfaces, and other classes.
Checkout /vendor/laravel/framework/src/Illuminate/Auth/Passwords/DatabaseTokenRepository.php
This is the default class that implements the TokenRepositoryInterface and is used by the /vendor/laravel/framework/src/Illuminate/Auth/Passwords/PasswordBroker.php.
Inside this class you can find all the actual functionality that handles the password resets including the table operations you mention. For example, one method you'll find is:
/**
* Create a new token record.
*
* #param \Illuminate\Contracts\Auth\CanResetPassword $user
* #return string
*/
public function create(CanResetPasswordContract $user)
{
$email = $user->getEmailForPasswordReset();
$this->deleteExisting($user);
// We will create a new, random token for the user so that we can e-mail them
// a safe link to the password reset form. Then we will insert a record in
// the database so that we can verify the token within the actual reset.
$token = $this->createNewToken();
$this->getTable()->insert($this->getPayload($email, $token));
return $token;
}
Currently the logic behind Resetting Password is that user must provide valid/registered e-mail to receive password recovery e-mail.
In my case I don't want to validate if the e-mail is registered or not due to security concerns and I want to just do the check in back-end and tell user that "If he has provided registered e-mail, he should get recovery e-mail shortly".
What I've done to achieve this is edited in vendor\laravel\framework\src\Illuminate\Auth\Passwords\PasswordBroker.php sendResetLink() method from this:
/**
* Send a password reset link to a user.
*
* #param array $credentials
* #return string
*/
public function sendResetLink(array $credentials)
{
// First we will check to see if we found a user at the given credentials and
// if we did not we will redirect back to this current URI with a piece of
// "flash" data in the session to indicate to the developers the errors.
$user = $this->getUser($credentials);
if (is_null($user)) {
return static::INVALID_USER;
}
// Once we have the reset token, we are ready to send the message out to this
// user with a link to reset their password. We will then redirect back to
// the current URI having nothing set in the session to indicate errors.
$user->sendPasswordResetNotification(
$this->tokens->create($user)
);
return static::RESET_LINK_SENT;
}
to this:
/**
* Send a password reset link to a user.
*
* #param array $credentials
* #return string
*/
public function sendResetLink(array $credentials)
{
// First we will check to see if we found a user at the given credentials and
// if we did not we will redirect back to this current URI with a piece of
// "flash" data in the session to indicate to the developers the errors.
$user = $this->getUser($credentials);
// if (is_null($user)) {
// return static::INVALID_USER;
// }
// Once we have the reset token, we are ready to send the message out to this
// user with a link to reset their password. We will then redirect back to
// the current URI having nothing set in the session to indicate errors.
if(!is_null($user)) {
$user->sendPasswordResetNotification(
$this->tokens->create($user)
);
}
return static::RESET_LINK_SENT;
}
This hard-coded option is not the best solution because it will disappear after update.. so I would like to know how can I extend or implement this change within the project scope within App folder to preserve this change at all times?
P.S. I've tried solution mentioned here: Laravel 5.3 Password Broker Customization but it didn't work.. also directory tree differs and I couldn't understand where to put new PasswordBroker.php file.
Thanks in advance!
Here are the steps you need to follow.
Create a new custom PasswordResetsServiceProvider. I have a folder (namespace) called Extensions where I'll place this file:
<?php
namespace App\Extensions\Passwords;
use Illuminate\Auth\Passwords\PasswordResetServiceProvider as BasePasswordResetServiceProvider;
class PasswordResetServiceProvider extends BasePasswordResetServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* #var bool
*/
protected $defer = true;
/**
* Register the service provider.
*
* #return void
*/
public function register()
{
$this->registerPasswordBroker();
}
/**
* Register the password broker instance.
*
* #return void
*/
protected function registerPasswordBroker()
{
$this->app->singleton('auth.password', function ($app) {
return new PasswordBrokerManager($app);
});
$this->app->bind('auth.password.broker', function ($app) {
return $app->make('auth.password')->broker();
});
}
}
As you can see this provider extends the base password reset provider. The only thing that changes is that we are returning a custom PasswordBrokerManager from the registerPasswordBroker method. Let's create a custom Broker manager in the same namespace:
<?php
namespace App\Extensions\Passwords;
use Illuminate\Auth\Passwords\PasswordBrokerManager as BasePasswordBrokerManager;
class PasswordBrokerManager extends BasePasswordBrokerManager
{
/**
* Resolve the given broker.
*
* #param string $name
* #return \Illuminate\Contracts\Auth\PasswordBroker
*
* #throws \InvalidArgumentException
*/
protected function resolve($name)
{
$config = $this->getConfig($name);
if (is_null($config)) {
throw new InvalidArgumentException(
"Password resetter [{$name}] is not defined."
);
}
// The password broker uses a token repository to validate tokens and send user
// password e-mails, as well as validating that password reset process as an
// aggregate service of sorts providing a convenient interface for resets.
return new PasswordBroker(
$this->createTokenRepository($config),
$this->app['auth']->createUserProvider($config['provider'] ?? null)
);
}
}
Again, this PasswordBrokerManager extends the base manager from laravel. The only difference here is the new resolve method which returns a new and custom PasswordBroker from the same namespace. So the last file we'll create a custom PasswordBroker in the same namespace:
<?php
namespace App\Extensions\Passwords;
use Illuminate\Auth\Passwords\PasswordBroker as BasePasswordBroker;
class PasswordBroker extends BasePasswordBroker
{
/**
* Send a password reset link to a user.
*
* #param array $credentials
* #return string
*/
public function sendResetLink(array $credentials)
{
// First we will check to see if we found a user at the given credentials and
// if we did not we will redirect back to this current URI with a piece of
// "flash" data in the session to indicate to the developers the errors.
$user = $this->getUser($credentials);
// if (is_null($user)) {
// return static::INVALID_USER;
// }
// Once we have the reset token, we are ready to send the message out to this
// user with a link to reset their password. We will then redirect back to
// the current URI having nothing set in the session to indicate errors.
if(!is_null($user)) {
$user->sendPasswordResetNotification(
$this->tokens->create($user)
);
}
return static::RESET_LINK_SENT;
}
}
As you can see we extend the default PasswordBroker class from Laravel and only override the method we need to override.
The final step is to simply replace the Laravel Default PasswordReset broker with ours. In the config/app.php file, change the line that registers the provider as such:
'providers' => [
...
// Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
App\Extensions\Passwords\PasswordResetServiceProvider::class,
...
]
That's all you need to register a custom password broker. Hope that helps.
The easiest solution here would be to place your customised code in app\Http\Controllers\Auth\ForgotPasswordController - this is the controller that pulls in the SendsPasswordResetEmails trait.
Your method overrides the one provided by that trait, so it will be called instead of the one in the trait. You could override the whole sendResetLinkEmail method with your code to always return the same response regardless of success.
public function sendResetLinkEmail(Request $request)
{
$this->validateEmail($request);
// We will send the password reset link to this user. Once we have attempted
// to send the link, we will examine the response then see the message we
// need to show to the user. Finally, we'll send out a proper response.
$response = $this->broker()->sendResetLink(
$request->only('email')
);
return back()->with('status', "If you've provided registered e-mail, you should get recovery e-mail shortly.");
}
You can just override the sendResetLinkFailedResponse method in your ForgetPasswordController class.
protected function sendResetLinkFailedResponse(Request $request, $response)
{
return $this->sendResetLinkResponse($request, Password::RESET_LINK_SENT);
}
We'll just send the successful response even if the validation failed.
I try to set up a websocket server via Thruway which can manage multiple groups. Something like a chat application where each client may subscribe to one or multiple ones at the same time and broadcast messages to an entire chat room. I managed to do that with an ancient version of Ratchet but since it doesn't run very smooth, I wanted to switch to Thruway. Sadly I can't find anything to manage groups. So far I have the following as the websocket-manager and the clients are using the current version of Autobahn|js (18.x).
Does anyone have any clue if it is possible to manage subscription groups with something like the following?
<?php
require_once __DIR__.'/../vendor/autoload.php';
use Thruway\Peer\Router;
use Thruway\Transport\RatchetTransportProvider;
$router = new Router();
$router->addTransportProvider(new RatchetTransportProvider("0.0.0.0", 9090));
$router->start();
With ThruWay, things are a little different than old Ratchet. First of all Thruway is not a WAMP Server. It is just a router. So it doesn't have a server instance like old Rathcet has lets you wrap all your server side functionality wrapped up. But it will only get the message packet and will route them to other sessions in same realm depending on their subscriptions. If you ever used socket.io, realm idea is similar to different connections so you can limit your sessions or connections to a single namespace or split functionality of different socket instances like administration, visitors etc.
On client side with autobahn ( latest version ) once you subscribe to a topic, then publish in that topic, thruway will automatically detect topic subscribers and emit message to them in same realm. But in old ratchet you need to handle this manually by keeping an array of available channels, and add users to each channel when they subscribes as well as broadcast message to these users in topic by iterating over them. This was really painful.
If you want to use RPC calls in server side and don't want to include some of your stuff on client side, you can still use a class called internalClient on server side. Conceptually Internal Client is another session connects to your thruway client and handles some functions internally without exposing other clients. It receives message packages and does stuff in it then returns result back to requested client connection. It took a while for me to understand how it works but once I figured out the idea behind made more sense.
so little bit code to explain better,
In your router instance you will need to add a module, ( note that, in voxys/thruway package examples are little confusing about internal client )
server.php
require __DIR__ . "/../bootstrap.php";
require __DIR__ . '/InternalClient.php';
$port = 8080;
$output->writeln([
sprintf('Starting Sockets Service on Port [%s]', $port),
]);
$router = new Router();
$router->registerModule(new RatchetTransportProvider("127.0.0.1", $port)); // use 0.0.0.0 if you want to expose outside world
// common realm ( realm1 )
$router->registerModule(
new InternalClient() // instantiate the Socket class now
);
// administration realm (administration)
// $router->registerModule(new \AdminClient());
$router->start();
This will initialize Thruway router and will attach internalclient instance to it. Now in InternalClient.php file you will be able to access actual route as well as current connected clients. With the example they provided, router is not part of instance so you are stuck with only session id property of new connections.
InternalClient.php
<?php
use Thruway\Module\RouterModuleInterface;
use Thruway\Peer\Client;
use Thruway\Peer\Router;
use Thruway\Peer\RouterInterface;
use Thruway\Logging\Logger;
use React\EventLoop\LoopInterface;
class InternalClient extends Client implements RouterModuleInterface
{
protected $_router;
/**
* Contructor
*/
public function __construct()
{
parent::__construct("realm1");
}
/**
* #param RouterInterface $router
* #param LoopInterface $loop
*/
public function initModule(RouterInterface $router, LoopInterface $loop)
{
$this->_router = $router;
$this->setLoop($loop);
$this->_router->addInternalClient($this);
}
/**
* #param \Thruway\ClientSession $session
* #param \Thruway\Transport\TransportInterface $transport
*/
public function onSessionStart($session, $transport)
{
// TODO: now that the session has started, setup the stuff
echo "--------------- Hello from InternalClient ------------\n";
$session->register('com.example.getphpversion', [$this, 'getPhpVersion']);
$session->subscribe('wamp.metaevent.session.on_join', [$this, 'onSessionJoin']);
$session->subscribe('wamp.metaevent.session.on_leave', [$this, 'onSessionLeave']);
}
/**
* Handle on new session joined.
* This is where session is initially created and client is connected to socket server
*
* #param array $args
* #param array $kwArgs
* #param array $options
* #return void
*/
public function onSessionJoin($args, $kwArgs, $options) {
$sessionId = $args && $args[0];
$connectedClientSession = $this->_router->getSessionBySessionId($sessionId);
Logger::debug($this, 'Client '. $sessionId. ' connected');
}
/**
* Handle on session left.
*
* #param array $args
* #param array $kwArgs
* #param array $options
* #return void
*/
public function onSessionLeave($args, $kwArgs, $options) {
$sessionId = $args && $args[0];
Logger::debug($this, 'Client '. $sessionId. ' left');
// Below won't work because once this event is triggered, client session is already ended
// and cleared from router. If you need to access closed session, you may need to implement
// a cache service such as Redis to access data manually.
//$connectedClientSession = $this->_router->getSessionBySessionId($sessionId);
}
/**
* RPC Call messages
* These methods will run internally when it is called from another client.
*/
private function getPhpVersion() {
// You can emit or broadcast another message in this case
$this->emitMessage('com.example.commonTopic', 'phpVersion', array('msg'=> phpVersion()));
$this->broadcastMessage('com.example.anotherTopic', 'phpVersionRequested', array('msg'=> phpVersion()));
// and return result of your rpc call back to requester
return [phpversion()];
}
/**
* #return Router
*/
public function getRouter()
{
return $this->_router;
}
/**
* #param $topic
* #param $eventName
* #param $msg
* #param null $exclude
*/
protected function broadcastMessage($topic, $eventName, $msg)
{
$this->emitMessage($topic, $eventName, $msg, false);
}
/**
* #param $topic
* #param $eventName
* #param $msg
* #param null $exclude
*/
protected function emitMessage($topic, $eventName, $msg, $exclude = true)
{
$this->session->publish($topic, array($eventName), array('data' => $msg), array('exclude_me' => $exclude));
}
}
Few things to note in above example code,
- In order to receive a message in a topic, in client side you need to be subscribed to that topic.
- Internal client can publish/emit/broadcast any topic without any subscription in same realm.
- broadcast/emit functions are not part of original thruway, something I come up with to make publications little easier on my end. emit will will send message pack to everyone has subscribed to topic, except sender. Broadcast on the other hand won't exclude sender.
I hope this information would help a little to understand the concept.
I'm using Behat in a Symfony2 app.
I have made a reusable action to add a HTTP header on some scenarios
/**
* #Given I am authenticated as admin
*/
public function iAmAuthenticatedAsAdmin()
{
$value = 'Bearer xxxxxxxxxxx';
$response = new Response();
$response->headers->set('Authorization', $value);
$response->send();
return $response;
}
This action is call when I add the I am authenticated as admin step in my scenario but it doesn't add my header. Like this
Scenario: I find all my DNS zones
Given I am authenticated as admin
And I send a GET request to "/api/dns"
Then the response code should be 200
How can I add a HTTP header before my request step in my scenario, using a reusable action ?
Is it possible ?
Thank.
I have find the way to do this.
If you are using WebApiExtension
Just import the WebApiContext in your context class like this
/**
* #param BeforeScenarioScope $scope
*
* #BeforeScenario
*/
public function gatherContexts(BeforeScenarioScope $scope)
{
$environment = $scope->getEnvironment();
$this->webApiContext = $environment->getContext('Behat\WebApiExtension\Context\WebApiContext');
}
And you just have now to use the iSetHeaderWithValue :
/**
* #Given I am authenticated as admin
*/
public function iAmAuthenticatedAsAdmin()
{
$name = 'Authorization';
$value = 'Bearer xxxxxxxx';
$this->webApiContext->iSetHeaderWithValue($name, $value);
}
Why don't you simply store it in session (hint: session should be destroyed at every scenario; take a look to BeforeScenario) and use whenever you need it?
Because I guess it's added but, on next request, it's gone as a brand new pair of request/response are generated (if I understand your needs correctly)
I currently ran into the problem of handling the authentification of a user on the server, using Laravel and RachetPHP.
What I tried so far:
I changed the driver type of the session to database, giving me an id and payload column. Using \Session::getId() returns a 40 character string.
The cookie information, sent by the WebSocket-Connection does contain a XSRF-TOKEN and a laravel_session, both containing > 200 characters string. The database ID of the users session differs from the id, returned by \Session::getId().
I am already sending the current CSRF-token via the websocket message, but I have no clue how to verify it (the built-in verifier uses requests - which I don't have in the websocket server scope).
Generic Use case:
A User posts a comment in thread. The payload of the sent object would then be:
Something to verify the user (an ID or a token).
The comment itself
If you were to send the user ID, anyone could temper the packet and send the message under another ones user.
My use case:
A user can have n-characters. A character has an avatar, an id, a name, etc.
The user is only used to:
authenticate at the server.
access his characters, and thus perform basic CRUD operations on his characters.
I also have a table locations - a "virtual place", a character can be in... so I got a one-to-one relationship between character and location. The user (character) can then send messages in a location via websocket. The message is inserted at the database on the server. At this point, I need to know:
If the user is authenticated (csrf-token ?)
If the user is the owner of the character (it's very simple to spoof the request with another user's character id)
If you need more information, please let me know.
So this is how I solved this a while ago. In my example, I'm working with Socket.IO, but I'm pretty sure you can easily rewrite the Socket.IO part to get it to work with RachetPHP as well.
Socket Server
The socket server depends on the files cookie.js and array.js, and the node modules express, http, socket.io, request and dotenv. I'm not the original author of cookie.js, but there is no author mentioned in the comments, so I'm not able to give any credits for this, sorry.
This is the server.js file which starts the server. It is a simple socket server that tracks who is currently online. The interesting part however is when the server makes a POST request to socket/auth on the Laravel application:
var express = require('express');
var app = express();
var server = require('http').Server(app)
var io = require('socket.io')(server);
var request = require('request');
var co = require('./cookie.js');
var array = require('./array.js');
// This loads the Laravel .env file
require('dotenv').config({path: '../.env'});
server.listen(process.env.SOCKET_SERVER_PORT);
var activeSockets = {};
var disconnectTimeouts = {};
// When a client connects
io.on('connection', function(socket)
{
console.log('Client connected...');
// Read the laravel_session cookie.
var cookieManager = new co.cookie(socket.handshake.headers.cookie);
var sess = cookieManager.get("laravel_session"); // Rename "laravel_session" to whatever you called it
// This is where the socket asks the Laravel app to authenticate the user
request.post('http://' + process.env.SOCKET_SERVER_HOST + '/socket/auth?s=' + sess, function(error, response, body)
{
try {
// Parse the response from the server
body = JSON.parse(body);
}
catch(e)
{
console.log('Error while parsing JSON', e);
error = true;
}
if ( ! error && response.statusCode == 200 && body.authenticated)
{
// Assign users ID to the socket
socket.userId = body.user.id;
if ( ! array.contains(activeSockets, socket.userId))
{
// The client is now 'active'
activeSockets.push(socket.userId);
var message = body.user.firstname + ' is now online!';
console.log(message);
// Tell everyone that the user has joined
socket.broadcast.emit('userJoined', socket.userId);
}
else if (array.hasKey(disconnectTimeouts, 'user_' + socket.userId))
{
clearTimeout(disconnectTimeouts['user_' + socket.userId]);
delete disconnectTimeouts['user_id' + socket.userId];
}
socket.on('disconnect', function()
{
// The client is 'inactive' if he doesn't reastablish the connection within 10 seconds
// For a 'who is online' list, this timeout ensures that the client does not disappear and reappear on each page reload
disconnectTimeouts['user_' + socket.userId] = setTimeout(function()
{
delete disconnectTimeouts['user_' + socket.userId];
array.remove(activeSockets, socket.userId);
var message = body.user.firstname + ' is now offline.';
console.log(message);
socket.broadcast.emit('userLeft', socket.userId);
}, 10000);
});
}
});
});
I added some comments to the code, so it should be pretty self-explanatory. Please note that I added SOCKET_SERVER_HOST and SOCKET_SERVER_PORT to my Laravel .env-file in order to be able to change the host and port without editing the code and run the server on different environments.
SOCKET_SERVER_HOST = localhost
SOCKET_SERVER_PORT = 1337
Authenticating a user by a session cookie with Laravel
This is the SocketController which parses the cookie and responds whether the user could be authenticated or not (JSON response). Its the same mechanism that you described in your answer. It's not the best design to handle the cookie parsing in the controller, but it should be OK in this case, because the controller only handles that one thing and its functionality isn't used at another point in the application.
/app/Http/Controllers/SocketController.php
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Users\UserRepositoryInterface;
use Illuminate\Auth\Guard;
use Illuminate\Database\DatabaseManager;
use Illuminate\Encryption\Encrypter;
use Illuminate\Http\Request;
use Illuminate\Routing\ResponseFactory;
/**
* Class SocketController
* #package App\Http\Controllers
*/
class SocketController extends Controller {
/**
* #var Encrypter
*/
private $encrypter;
/**
* #var DatabaseManager
*/
private $database;
/**
* #var UserRepositoryInterface
*/
private $users;
/**
* Initialize a new SocketController instance.
*
* #param Encrypter $encrypter
* #param DatabaseManager $database
* #param UserRepositoryInterface $users
*/
public function __construct(Encrypter $encrypter, DatabaseManager $database, UserRepositoryInterface $users)
{
parent::__construct();
$this->middleware('internal');
$this->encrypter = $encrypter;
$this->database = $database;
$this->users = $users;
}
/**
* Authorize a user from node.js socket server.
*
* #param Request $request
* #param ResponseFactory $response
* #param Guard $auth
* #return \Symfony\Component\HttpFoundation\Response
*/
public function authenticate(Request $request, ResponseFactory $response, Guard $auth)
{
try
{
$payload = $this->getPayload($request->get('s'));
} catch (\Exception $e)
{
return $response->json([
'authenticated' => false,
'message' => $e->getMessage()
]);
}
$user = $this->users->find($payload->{$auth->getName()});
return $response->json([
'authenticated' => true,
'user' => $user->toArray()
]);
}
/**
* Get session payload from encrypted laravel session.
*
* #param $session
* #return object
* #throws \Exception
*/
private function getPayload($session)
{
$sessionId = $this->encrypter->decrypt($session);
$sessionEntry = $this->getSession($sessionId);
$payload = base64_decode($sessionEntry->payload);
return (object) unserialize($payload);
}
/**
* Fetches base64 encoded session string from the database.
*
* #param $sessionId
* #return mixed
* #throws \Exception
*/
private function getSession($sessionId)
{
$sessionEntry = $this->database->connection()
->table('sessions')->select('*')->whereId($sessionId)->first();
if (is_null($sessionEntry))
{
throw new \Exception('The session could not be found. [Session ID: ' . $sessionId . ']');
}
return $sessionEntry;
}
}
In the constructor you can see that I refer to the internal middleware. I added this middleware to only allow the socket server to make requests to socket/auth.
This is what the middleware looks like:
/app/Http/Middleware/InternalMiddleware.php
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Routing\ResponseFactory;
class InternalMiddleware {
/**
* #var ResponseFactory
*/
private $response;
/**
* #param ResponseFactory $response
*/
public function __construct(ResponseFactory $response)
{
$this->response = $response;
}
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (preg_match(env('INTERNAL_MIDDLEWARE_IP'), $request->ip()))
{
return $next($request);
}
return $this->response->make('Unauthorized', 401);
}
}
To get this middleware to work, register it in the Kernel and add the INTERNAL_MIDDLEWARE_IP property - that is just a regular expression defining which IP addresses are allowed - to your .env-file:
Local testing (any IP):
INTERNAL_MIDDLEWARE_IP = /^.*$/
Production env:
INTERNAL_MIDDLEWARE_IP = /^192\.168\.0\.1$/
I'm sorry I could not help you out with RachetPHP, but I think you get a good idea how this can be solved.
I think I found a solution. Although not very clean, it does what it's supposed to do (I guess...)
The WebSocket-Server gets started by an Artisan Command (by mmochetti#github). I inject these classes into the Command:
Illuminate\Contracts\Encryption\Encrypter
App\Contracts\CsrfTokenVerifier - a custom CsrfTokenVerifier, that simply compares 2 strings (going to put more of the follow logic code in there)
I pass these instances from the command to the server. On the onMessage method, I parse the message sent, containing:
The CSRF-Token of the user
The character-id of the user
I then check if the token is valid, and if the user is the owner of the character.
public function onMessage(ConnectionInterface $from, NetworkMessage $message) {
if (!$this->verifyCsrfToken($from, $message)) {
throw new TokenMismatchException;
}
if (!$this->verifyUser($from, $message)) {
throw new \Exception('test');
}
...
}
private function verifyUser(ConnectionInterface $conn, NetworkMessage $message) {
$cookies = $conn->WebSocket->request->getCookies();
$laravel_session = rawurldecode($cookies['laravel_session']);
$id = $this->encrypter->decrypt($laravel_session);
$session = Session::find($id);
$payload = unserialize(base64_decode($session->payload));
$user_id = $payload['user_id'];
$user = User::find($user_id);
$characters = $this->characterService->allFrom($user);
$character_id = $message->getHeader()['character_id'];
return $characters->contains($character_id);
}
private function verifyCsrfToken($from, NetworkMessage $message) {
$header = $this->getHeaderToken($from);
return $this->verifier->tokensMatch($header, $message->getId());
}
The code could be cleaner for sure, but as a quick hack, it works. I think, instead of using a model for the Session, I should use the Laravel DatabaseSessionHandler.
For Laravel > 5 i use this code:
$cookies = $conn->WebSocket->request->getCookies();
$laravel_session = rawurldecode($cookies['laravel_session']);
$id = $this->encrypter->decrypt($laravel_session);
if(Config::get('session.driver', 'file') == 'file')
{
$session = File::get(storage_path('framework/sessions/' . $id));
}
$session = array_values(unserialize($session));
return $session[4]; // todo: Hack, please think another solution
To get cookies from client through websocket you must change domain in session config and change everywhere websocket host to your domain:
'domain' => 'your.domain.com',