OpenID With Slim Framework - php

I am trying to use Steam's Login With Slim Framework!
For this I am trying to use steamauth library (https://github.com/SmItH197/SteamAuthentication)
I am able to successfully require the files to slim via that start.php but how do I call the steamlogin() and logout functions?
Please help me!

You will need to add a middleware for the auth step.
Here's a simple example, assuming you are using Slim 3:
$middleware = function (Request $request, Response $response, $next) {
$this->user = null;
if(!isset($_SESSION['steamid'])) {
//don't interfere with unmatched routes
$route = $request->getAttribute('route');
if ($route && !in_array($route->getName(), ['login'])) {
return $response->withStatus(403)->withHeader('Location', $this->router->pathFor('login'));
}
} else {
include ('steamauth/userInfo.php'); //To access the $steamprofile array
//Protected content
}
return $next($request, $response);
};
$app->add($middleware);
In your /login route just include a view with steamlogin(). You can use the basic php-view template for this.

Related

Laravel Middleware - Skip Passport Auth

We have 2 auth middlewares applied to specific routes, 'external_token' and 'auth:api'. When an external bearer token is presented we inspect it, and if all the values are good we consider the user authorized to access the requested url.
How do we process all other middlewares except passport auth?
public function handle(Request $request, Closure $next)
{
$token = $request->header('Bearer');
try {
list($JWTHeader, $JWTPayload) = JWT::verify($token, JWT::TYPE_ID_EXTERNAL);
$this->user = User::where('external_id', $JWTPayload['external_id'])->first();
// Can we just set $this->user and process all other middlewares except auth?
} catch (Exception $e) {
Log::debug($e);
}
$response = $next($request);
return $response;
}
Well, one thing you could do would be to set the user on the api guard, so when the auth middleware runs, it'll find the user you provided. You would have to ensure that your external_token middleware runs first.
auth()->guard('api')->setUser($this->user);
Another option would be to convert your external_token middleware into a Laravel auth guard so that you can use the built-in auth functionality. Then, you can protect your route with auth:api,external_token, and the auth will pass if any one of the specified guards is successful.
The simplest example would be a closure request guard.
In your AuthServiceProvider::boot() method:
// don't forget your "use" statements for all these classes
public function boot()
{
// ...
Auth::viaRequest('external_token_driver', function ($request) {
$token = $request->header('Bearer');
try {
list($JWTHeader, $JWTPayload) = JWT::verify($token, JWT::TYPE_ID_EXTERNAL);
return User::where('external_id', $JWTPayload['external_id'])->first();
} catch (Exception $e) {
Log::debug($e);
}
return null;
});
}
In your auth.php config:
'guards' => [
// web, api, etc...
'external_token' => [
'driver' => 'external_token_driver',
],
],
NB: all untested.

How to redirect to a previous URL in Laravel 5.6 and intended

In my Laravel application I have a middleware for specific routes, in this middleware I validate to redirect to a url.
public function handle($request, Closure $next)
{
$isValidated= ....
if ($isValidated) {
session()->put('url.intended', URL::full());
return redirect()->route('routeone')
}
return $next($request);
}
in the store method of that table when you register I do a redirect in the following way, but it turns out that when I do it, it redirects me to domain/img/favicon.png and I did not do the previous route
public function store(Request $request)
{
....
return redirect()->intended(session('url.intended') ?? '/admin');
}
What is the problem here or how could I address this detail to redirect to the url before the middleware redirects. ?
Try to use this code :
$referrer = $this->request->headers->get('referer');
$url = $referrer ? $this->to($referrer) : $this->getPreviousUrlFromSession();
or directly :
$url = request()->headers->get('referer');
and
session()->put('url.intended', $url);
Could you not just do this
return back();
From the docs https://laravel.com/docs/5.7/redirects#creating-redirects

POST data from android using Volley to Laravel5

I'm having problems on what URL to be used to link to the php scripts in Laravel5 which I'm running at localhost at the moment. I have created a function in my controller to handle the request. Here is the function:
public function mobile_validator(Request $request) {
$method = $request->method();
if($method == 'POST') {
$username = $request->username;
$password = $request->password;
$user = DB::table('users')->get();
foreach($user as $i) {
if($username == $i->email and $password == $i->password) {
return 'success';
}
else {
return 'failure';
}
}
}
I have also created a route in my route.php.
Route::get('/mobilevalidator', 'AuthController#mobile_validator');
This is my URL in android:
private static final String LOGIN_URL = "http://10.0.2.2:8000/mobilevalidator/";
Now when I login in my app it displays the error com.android.volley.timeouterror
Is the URL correct in defining the php script in Laravel?
In your routes you defined a
Route::get
That means that this route is listening to the GET method. In your controller you specify
$method = $request->method();
if($method == 'POST') {
Which means your controller is actually only returning stuff you have a POST which will ofcourse never happen since your route calling your controller is only listening to GET
You can complety remove the check of the method. A controller method can only be called if you map the route to it. If you want to also support POST simply add
Route::post( ... )
A little hint:
Try to use PostMan or any other RestClient to test your Routes before using them in your app. Also don't forget to remove the web middleware in laravel - otherwise you will also need to add the csrf token to your request.

Slim framework 3 php-view variable

I would like to have a variable from request ($request->getUri()->getBasePath();) always available on the templates. How can I do this e.g. with a middleware without having to pass the above as parameter to renderer->render on all routes each time ?
$app->get(...
...
$args['basepath']=$request->getUri()->getBasePath();
return $this->renderer->render($response, 'test.php', $args);
});
UPDATE:
This can be done after php-view 2.1.0 as so:
dependencies.php:
$container['renderer'] = function ($c) {
$settings = $c->get('settings')['renderer'];
return new Slim\Views\PhpRenderer($settings['template_path']);
};
middleware.php:
$app->add(function (Request $request, Response $response, callable $next) {
$uri = $request->getUri();
$renderer = $this->get('renderer');
$renderer->addAttribute('uri', $request->getUri());
return $next($request, $response);
});
Then, inside the template:
<?php
$basePath=$uri->getBasePath();
$rpath=$uri->getPath();
?>
Version 2.1.0 of PHP-View now supports setting template variables before you render. See https://github.com/slimphp/PHP-View#template-variables.
While looking into the Code of the PhpRenderer you will see currently there is no way to specify data outside of the render() function.
You could create an issue and/or make a pull request to support that functionality.

Slim framework flash and middleware

I'm learning how to use Slim Framework and I have a problem using flash message inside a custom middleware.
The problem is quite simple: I use the $app->flash('error', 'my message'); in the middleware and there is no message in the next page.
The middleware works great by the way
Here is my code:
Middleware
class SessionMiddleware extends \Slim\Middleware {
public function call() {
$app = $this->app;
$req = $app->request;
if(!preg_match('#^(/public)#', $req->getPath())) {
if(isset($_SESSION['user']) && !empty($_SESSION['user'])) {
//Do something
} else {
$app->flash('error', 'You must be logged');
if($req->getPath() != '/login') {
$app->redirect('/login');
}
}
}
$this->next->call();
}
}
Login
<?php
if(isset($_SESSION['slim.flash']['error'])) {
echo '<p class="alert alert-danger"><strong>Error</strong>: '.$_SESSION['slim.flash']['error'].'</p>';
}
?>
App
$app = new \Slim\Slim(array(
'mode' => 'development',
'debug' => true,
'templates.path' => './templates'
));
$app->add(new \SessionMiddleware());
$app->get('/login', function() use($app) {
$app->render('login.php');
});
Any ideas how to fix that ?
Thank you
Try to use flashNow instead of flash method.
I also saw that 'flash' and 'flashNow' methods are not working in middleware. To add flash message, I decided to do it manually. It's working, but I know that's not the best approach.
$_SESSION['slim.flash']['error'] = 'message';
Running into this issue myself.
Since Flash is an app middleware component and is added by default, and before you add any custom app middleware components, it won't actually be initialised when your middleware is called.
Doing what #kkochanski has done is hacky, but is probably the only option, short of removing/unsetting Flash and adding it as the final app middleware component.
I'm facing with the same problem and resolve it. You can achieve that with call another method in authenticated route and flashing inside it for example
class AuthController
{
public function flashError($request, $response)
{
// flash
// redirect
}
}
It works well for me. So you can just redirect to and make sure this method handle it. So you can flashing message outside middleware.

Categories