Slim Framework 3 session - php

Could you please help me,
My code is not saving SESSION between requests.
when i Login, it always returns null in session.
Thank you in advance.
$app->get('/session', function($request, $response, $args) {
$session = new \SlimSession\Helper;
$reponse["uid"] = $session->uid;
$reponse["email"] = $session->email;
$reponse["name"] = $session->name;
echo json_encode($reponse);
});
$app->post('/connexion', function ($request, $response, $args) {
$reponse['status'] = "success";
$reponse['message'] = 'Vous êtes connecté.';
$reponse['name'] = "wassim boukadida";
$reponse['uid'] = "123456";
$reponse['email'] = "test#test.com";
$reponse['createdAt'] = "date_exmple";
//session saving
$session = new \SlimSession\Helper;
$session->uid = "123456";
$session->email = "test#test.com";
$session->name = "wassim boukadida";
echo json_encode($reponse);
});

You need to start the session, bryanjhv/slim-session has already middleware for that, which you just need to add:
$app = new \Slim\App;
// add the middleware
$app->add(new \Slim\Middleware\Session());
// add routes
$app->run();
For settings look at the readme file of bryanjhv/slim-session as this helper is currently in development

Related

Class 'Silex\Application' not found

I’ve done with google sign-up, I want to ask regarding google token_id authentication. Google issues a token-id to every user which changes on every sign-in, I am getting that token-id when the user sign-in, I want to authenticate that token-id from google to verify if the sign-in was original or fake. I am using this php api provided by google, but it is continuously giving this error:
Uncaught Error: Class 'Silex\Application' not found in C:\xampp\htdocs\final\gplus-verifytoken-php-master\verify.php:23
Stack trace: #0 {main} thrown in C:\xampp\htdocs\final\gplus-verifytoken-php-master\verify.php on line 23
require_once __DIR__.'/vendor/autoload.php';
require_once __DIR__.'/google-api-php-client/src/Google_Client.php';
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
const CLIENT_ID = 'xyz';
const CLIENT_SECRET = 'xyz';
const APPLICATION_NAME = "xyz";
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$app = new Silex\Application();
$app['debug'] = true;
$app->register(new Silex\Provider\TwigServiceProvider(), array(
'twig.path' => __DIR__,
));
$app->register(new Silex\Provider\SessionServiceProvider());
// Initialize a session for the current user, and render index.html.
$app->get('/', function () use ($app) {
return $app['twig']->render('index.html', array(
'CLIENT_ID' => CLIENT_ID,
'APPLICATION_NAME' => APPLICATION_NAME
));
});
// Verify an ID Token or an Access Token.
// Example URI: /verify?id_token=...&access_token=...
$app->post('/verify', function (Request $request) use($app, $client) {
$id_token = "eyJhbGciOiJSUzI1NiIsImtpZCI6ImE0MzY0YjVmYjliODYxYzNhYTRkYTg5NWExMjk5NzZjMjgyZGJmYzIifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwiaWF0IjoxNDg1NDEyMjQ1LCJleHAiOjE0ODU0MTU4NDUsImF0X2hhc2giOiJMSV9DTWxzeG1lSTdvQm9lSUxoSjZRIiwiYXVkIjoiNDY4MzU1OTM0NzMzLXZqNnRkdDJtazEwZ3R0OHJvZGY2bG84MHM4czdtdTRrLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwic3ViIjoiMTEyNjE1NTE5MDY0MTc3ODI0NTgzIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImF6cCI6IjQ2ODM1NTkzNDczMy12ajZ0ZHQybWsxMGd0dDhyb2RmNmxvODBzOHM3bXU0ay5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbSIsImVtYWlsIjoibWdoYXphbmZhcmFsaWtoYW4wOUBnbWFpbC5jb20ifQ.Bpa2_zeVebQ7xtKXvuEell50bvUtKOGb5ZertUZGvzGWXnlA-c2kw4Mvko9Xd4JI_R4wbFoyBtrGCiK0jAlJMgaIH8p3wJbzNKPZ-gPFJdX8mv4v42v8-9urGM7rRUCDylz16WEcR1A2qOmEcNCpCf0_FGNpChl8sc8q8zvTnIb_zYYHp_V7ebR2RlUuO2z9G5YzBN3hZDnmen1xLStmNmYKsIiP5ypMqbWaLjnXJjre6bjTuIGymg_phDYDmwWMVTJyx88zmKAfwQTCh2u3qe_fkCDxxm0MO2wC29__q4uc0BfUNdH62GOrNTBJXmPTUZuT1vdUhzz4CLu1KUohWg";
/*$id_token = $request->get("id_token");*/
$access_token = $request->get("access_token");
$token_status = Array();
$id_status = Array();
if (!empty($id_token)) {
// Check that the ID Token is valid.
try {
// Client library can verify the ID token.
$jwt = $client->verifyIdToken($id_token, CLIENT_ID)->getAttributes();
$gplus_id = $jwt["payload"]["sub"];
$id_status["valid"] = true;
$id_status["gplus_id"] = $gplus_id;
$id_status["message"] = "ID Token is valid.";
} catch (Google_AuthException $e) {
$id_status["valid"] = false;
$id_status["gplus_id"] = NULL;
$id_status["message"] = "Invalid ID Token.";
}
$token_status["id_token_status"] = $id_status;
}
$access_status = Array();
if (!empty($access_token)) {
$access_status["valid"] = false;
$access_status["gplus_id"] = NULL;
// Check that the Access Token is valid.
$reqUrl = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=' .
$access_token;
$req = new Google_HttpRequest($reqUrl);
$tokenInfo = json_decode(
$client::getIo()->authenticatedRequest($req)
->getResponseBody());
if ($tokenInfo->error) {
// This is not a valid token.
$access_status["message"] = "Invalid Access Token.";
} else if ($tokenInfo->audience != CLIENT_ID) {
// This is not meant for this app. It is VERY important to check
// the client ID in order to prevent man-in-the-middle attacks.
$access_status["message"] = "Access Token not meant for this app.";
} else {
$access_status["valid"] = true;
$access_status["gplus_id"] = $tokenInfo->user_id;
$access_status["message"] = "Access Token is valid.";
}
$token_status["access_token_status"] = $access_status;
}
return $app->json($token_status, 200);
});
$app->run();
I did like this
composer install (after that run this command)
composer dump-autoload
it is working for me
If your Framework don't work after migration.
or see Class 'Silex\Application' not found.
Delete "vendor" folder after composer install.
Working for me

Notice: Undefined offset: 0 in C:\wamp64\www\lynda2\src\Chatter\Middleware\Authentication.php on line 12

Hi i'm created a web service with Slim from a course of lynda "Building APIs in PHP Using the Slim Micro Framework" but when i want login, this error Occurs
Notice: Undefined offset: 0 in C:\wamp64\www\lynda2\src\Chatter\Middleware\Authentication.php on line 12
Authentication
namespace Chatter\Middleware;
use Chatter\Models\User;
class Authentication
{
public function __invoke($request, $response, $next)
{
$auth = $request->getHeader('Authorization');
$_apikey = $auth[0];
$apikey = substr($_apikey, strpos($_apikey, ' ') + 1);
$user = new User();
if (!$user->authenticate($apikey)) {
$response->withStatus(401);
return $response;
}
$response = $next($request, $response);
return $response;
}
}
User.php
<pre><code>
namespace Chatter\Models;
class User extends \Illuminate\Database\Eloquent\Model
{
public function authenticate($apikey)
{
$user = User::where('apikey', '=', $apikey)->take(1)->get();
$this->details = $user[0];
return ($user[0]->exists) ? true : false;
}
}
</code></pre>
index.php
<pre><code>
require 'vendor/autoload.php';
include 'bootstrap.php';
use Chatter\Models\Message;
use Chatter\Middleware\Logging as ChatterLogging;
use Chatter\Middleware\Authentication as ChatterAuth;
$app = new \Slim\App();
$app->add(new ChatterAuth());
$app->add(new ChatterLogging());
$app->get('/messages', function ($request, $response, $args) {
$_message = new Message();
$messages = $_message->all();
$payload = [];
foreach($messages as $_msg) {
$payload[$_msg->id] = ['body' => $_msg->body, 'user_id' => $_msg->user_id, 'created_at' => $_msg->created_at];
}
return $response->withStatus(200)->withJson($payload);
});
$app->get('/', function ($request, $response, $args) {
return "This is a catch all route for the root that doesn't do anything useful.";
});
// Run app
$app->run();
</code></pre>
The error is stating that when you "login" there is no Authorization header present.
$request->getHeader('Authorization') returns an empty array, so when you attempting to access the first element of the array, you get your error:
$_apikey = $auth[0]; // Will trigger error, since there are no elements in the array
Thus to aviod this error, get $apikey like this:
public function __invoke($request, $response, $next)
{
$auth = $request->getHeader('Authorization');
$_apikey = array_shift($auth);
if ($_apikey) {
$apikey = substr($_apikey, strpos($_apikey, ' ') + 1);
$user = new User();
if (!$user->authenticate($apikey)) {
return $response->withStatus(401);
} else {
return $next($request, $response);
}
} else {
// Authorization header is missing, therefore unauthorized access
return $response->withStatus(401);
}
}
This is an older thread, but in case anyone else is following this tutorial ... the code the OP posted was supposed to do exactly what it does - to fail if there is no authorization header present.
Looks like the OP missed one step: adding the bearer token to the request. In Postman, go to Authorization > Type > Bearer Token and paste a valid token in the input field. I believe that it was clearly stated in the tutorial. Afterward, everything works as expected.

How to get current instance in laravel 4.2

So i'm working on this Laravel application which uses ratchet for the websockets, and I want to get the current users session in my websocket controller. Previously I was working with Laravel 5.2 and this code worked great
public function onOpen(ConnectionInterface $conn) {
$session = (new SessionManager(App::getInstance()))->driver();
$cookies = $conn->WebSocket->request->getCookies();
if(!empty($cookies)){
$laravelCookie = urldecode(isset($cookies[Config::get('session.cookie')]) ? $cookies[Config::get('session.cookie')] : '');
if(!empty($laravelCookie)){
$idSession = Crypt::decrypt($laravelCookie);
$session->setId($idSession);
$conn->session = $session;
}
}
$newConnection = new \stdClass();
$newConnection->resourceId = $conn->resourceId;
$newConnection->conn = $conn;
$this->clients[] = $newConnection;
$newConnection->conn->send(json_encode(['status' => 'success', 'message' => 'Response from server, successful']));
}
After the user has connected, I just load the current session when ever the user sends a message
public function onMessage(ConnectionInterface $from, $msg) {
$user = [];
$request = json_decode($msg);
if(isset($from->session)){
$from->session->start();
$idUser = $from->session->get(Auth::getName());
QLog::info($idUser);
if (isset($idUser)) {
$user = User::find($idUser);
}
$from->session->save();
}
if($request->action == 'get-user' && $user){
$this->clients[0]->conn->send(json_encode(['username' => $user->getFullName()]));
} else {
$this->clients[0]->conn->send(json_encode(['username' => 'not found']));
}
}
But now I need to do the same thing in Laravel 4.2, but as it turns out, that in Laravel 4.2 there is no method getInstance(). What would be the best alternative to use in my situation?
This seems to work:
$app = App::getFacadeApplication();
I couldn't find any references to doing this, but figured it out via the Facade interface. So I don't know if this is good practise or not. I'm using it because I use Illuminate outside of Laravel.

How to check auth user in laravel subdomain?

I have a project it's Backend is built in Laravel 5.2 and Frontend is built in PHP. Please check the folder structure below it's in localhost.
Backend : http://crm.test.dev This is the root folder, laravel5.2 -> public ->index.php
Frontend: http://test.dev This url is point to laravel5.2 -> public -> frontend -> index.php
My purpose is, If a user(admin) is logged in Backend(http://crm.test.dev) and not signed out. The same user is accessing Frontend(http://test.dev") at that time I need to show an alert you are logged in Backend(http://crm.test.dev).
frontend->index.php
require __DIR__.'/../../bootstrap/autoload.php';
$app = require_once __DIR__.'/../../bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$response = $kernel->handle(
$request = Illuminate\Http\Request::capture()
);
$isAuthorized = Auth::check();
$user = Auth::user();
echo $user;
Actually issue is from config -> session.php {'domain' => null,}. I updated this line to { 'domain' => '.test.dev', } . Now a user is logged in backend and accessing frontend (subdomain: http://test.dev) "Your are logged in" message shows.
require __DIR__.'/../../bootstrap/autoload.php';
$app = require_once __DIR__.'/../../bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$response = $kernel->handle(
$request = Illuminate\Http\Request::capture()
);
$isAuthorized = Auth::check();
$user = Auth::user();
if(Auth::check()) {
echo "Your are logged in";
}
else {
echo "Sorry";
}
I don't have access to the sites you've posted. But you can check if the users logged in with Auth::check() as you already do. Then you can do it e.g. like this:
if(Auth::check()) {
echo "You're locked in";
//do some action
else {
//do normal action
}

Zend_Auth - When I set a custom storage namespace it does not exist when I redirect to a new controller

In my entry controller I set:
This works:
$authadapter = new Test_Auth_Adapter_DbTable($db);
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($authadapter);
$data = $authadapter->getResultRowObject(null, 'password');
$auth->getStorage()->write($data);
$this->_redirector->gotoUrl('/main');
This does not:
$authadapter = new Test_Auth_Adapter_DbTable($db);
$auth = Zend_Auth::getInstance();
$auth->setStorage(new Zend_Auth_Storage_Session('Test_User')); //the only difference
$result = $auth->authenticate($authadapter);
$data = $authadapter->getResultRowObject(null, 'password');
$auth->getStorage()->write($data);
$this->_redirector->gotoUrl('/main');
I can see it set in the $_SESSION var with all of the correct data when I use a debugger but after the data is set and I redirect to the desired destination the $_SESSION var is no longer set thus I cannot access things!
The page being redirected to checks auth with:
$this->auth = Zend_Auth::getInstance();
if (!$this->auth->hasIdentity()) {
$this->_redirector->gotoUrl('/entry');
}
Why doesn't this work?
Try this:
$this->auth = Zend_Auth::getInstance();
$this->auth->setStorage(new Zend_Auth_Storage_Session('Test_User'));
if (!$this->auth->hasIdentity()) {
$this->_redirector->gotoUrl('/entry');
}
the problem is if you don't set a storage class, it will default to using Zend_Auth_Storage_Session with the Zend_Auth namespace. And because your session data isn't in that namespace, Zend_Auth doesn't see it and behaves as if the user is not logged in.
Depending on how your application is structured (and how big a part of it the auth is), you might want to do this in a bootstrap method instead so you only have to do it once:
protected function _initAuth()
{
$auth = Zend_Auth::getInstance();
$auth->setStorage(new Zend_Auth_Storage_Session('Test_User'));
return $auth;
}

Categories