use laravel Authentication in pure php scripts - php

I am working on a laravel App. a part of that is written pure php that is a html form and form submission script that stores data to Database.
Suppose form.php page is like :
<?php
require('config.php');
?>
<form action="process.php" method="post">
<input type="text" name="username">
<input type="submit" value="Send">
</form>
And process.php page is :
<?php
require ('config.php');
?>
if (isset($_POST['submit_edu'])) {
$username = trim($_POST['username']);
// other codes to store data to DB
}
Now I want just Authenticated Users in main laravel app can access to those pages and send their info.
To access Auth laravel Object, I added below codes to beginning of config.php file that holds connection settings and required by those two page:
require __DIR__ . '/../../bootstrap/autoload.php';
$app = require_once __DIR__ . '/../../bootstrap/app.php';
$app->make('Illuminate\Contracts\Http\Kernel')->handle(Illuminate\Http\Request::capture());
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$response = $kernel->handle(
$request = Illuminate\Http\Request::capture()
);
if (!Auth::check()) {
exit('Only authorized Users can access to this page');
}
As you can see if an unAuthorized user want to pages Encounters an error.
Now when an Authenticated user want to open form.php page (in face via GET method) Auth::check() works correctly but when clicks on submit form button and data sent to process.php (via POST method) , it always returns false.
While if I open same process.php via GET method Auth::check() works correctly again.
Means in this case Auth::check() can not work properly.
What is problem in your idea. can anyone help me to solve this problem?
Update :
Even I used EventServiceProvider and authentication events to create a session. first I added this to provider :
'Illuminate\Auth\Events\Login' => [
'App\Listeners\SessionLoginEnable',
],
And in SessionLoginEnable:
public function handle (Login $event)
{
session(['user_is_logged_in' => true]);
}
then I added:
'Illuminate\Auth\Events\Logout' => [
'App\Listeners\SessionLoginDisable',
],
And in that :
public function handle (Logout $event)
{
session(['user_is_logged_in' => false]);
}
And in the other hand to check and user created session first I tried in config.php :
require __DIR__ . '/../../bootstrap/autoload.php';
$app = require_once __DIR__ . '/../../bootstrap/app.php';
$app->make('Illuminate\Contracts\Http\Kernel')->handle(Illuminate\Http\Request::capture());
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$response = $kernel->handle(
$request = Illuminate\Http\Request::capture()
);
$is_logged = session('user_is_logged_in');*
if ( !is_logged ) {
exit('Only authorized Users can access to this page');
}
This solution did not work.
Then I tried this :
session_start();
if ( !isset($_SESSION['user_is_logged_in']) or $_SESSION['user_is_logged_in'] != true) {
exit('Only authorized Users can access to this page');
}
But in this case again, the answer not receive and It seems $_SESSION['user_is_logged_in'] could not be recognized.
Another solution remains?

Related

How to implement an external payment gateway with Prestashop?

I need to implement an external payment gateway in Prestashop. I have to send an HTTP request as below:
<form method="post" name="payment" action="url">
blah blah....
<input name="ResponseURL" value="{$response}">
</form>
The ResponseURL is the URL provided by me to retrieve the response from the API. This is where I need to perform validation checking and redirect to the order confirmation page. (similarly to the validation front controller from ps_checkpayment module)
I have also added the hookPaymentOption
public function hookPaymentOptions($params)
{
if (!$this->active) {
return;
}
//some code here
$response = 'http://' . $_SERVER['SERVER_NAME'] . $this->_path . '/classes/response.php';
$formAction = $this->context->link->getModuleLink($this->name, 'validation', array(), true);
$this->smarty->assign([
//some code here
'response' => $response
]);
$paymentForm = $this->fetch('module:easypaymentoption/views/templates/hook/payment_options.tpl');
$newOption = new PaymentOption();
$newOption->setModuleName($this->displayName)
->setCallToActionText($this->displayName)
->setAction($formAction)
->setForm($paymentForm);
$payment_options = array(
$newOption
);
return $payment_options;
}
I'm just really clueless as to how to proceed. I've tried to link my $response to a front module controller class, but I get an error that says
Fatal error: Uncaught Error: Class 'ModuleFrontController' not found in C:\xampp\htdocs\prestashop\modules\easypaymentoption\classes\response.php:3 .
I have also tried to link to an empty php file, but by doing this I can't get the necessary information to do validation checking and redirect to the order confirmation page that I would otherwise would get by using a class that extends ModuleFrontController.
Any help is appreciated, as I've been stuck here for almost 3 days.

spotify api php show user details in redirect

I am using the spotify api and this php library.
I have created an app in the spotify dev portal, with a redirect url. This is all working fine.
My Spotify API code looks like this:
<?php
require 'vendor/autoload.php';
$session = new SpotifyWebAPI\Session(
'CLIENT_ID',
'CLIENT_SECRET',
'index.html'
);
$api = new SpotifyWebAPI\SpotifyWebAPI();
if (isset($_GET['code'])) {
$session->requestAccessToken($_GET['code']);
$api->setAccessToken($session->getAccessToken());
print_r($api->me());
} else {
$options = [
'scope' => [
'user-read-email',
],
];
header('Location: ' . $session->getAuthorizeUrl($options));
die();
}
?>
The code above should redirect to index.html (which it does) and then on the index.html page I want to show these user details but I am unsure of how to do this.
Does anyone know how to achieve this?
My index.html file looks like this:
<h1>Want to see the user info here!</h1>

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
}

Basic auth with Slim no response

I am implementing a basic auth with Slim and REST. I have installed the basic auth via Composer and used the below code.
<?php
require 'confing.php';
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim;
$app->add(new \Slim\Middleware\HttpBasicAuthentication([
"path" => "/admin", /* or ["/admin", "/api"] */
"realm" => "Protected",
"users" => [
"root" => "t00r",
"user" => "passw0rd"
],
"callback" => function ($request, $response, $arguments) {
print_r($arguments);
}
]));
$app->get('/getLaboorState/:laboor_id', function($laboor_id) use ($app) {
$db =getDB();
$sql="SELECT status FROM laboor WHERE laboor_id='".$laboor_id."'";
$stmt = $db->query($sql);
$items = $stmt->fetchAll();
echo json_encode($items);
});
$app->run();
?>
When I am trying now to connect the /getLaboorState with Postman it returns nothing. I used same username and password in postman and nothing shows, but when I take the basic auth it works fine.
Other questions is, after implement the basic auth, how can I restrict all slim api to go throw each api before run the query?
This is a pic from Postman:
Note: then I want to use the API with AJAX.
you need to use $authenticate($app) to restrict all slim api to go throw each api before run the query
$app->get('/profile(/)(:id)', $authenticate($app), function($laboor_id) use ($app) {
//Your logic here
})->name('profile');
$authenticate = function ($app) {
return function () use ($app) {
//your logic here
if (!isset($_SESSION['ID'])) {
$app->redirect($app->urlFor('loginpage'));
}
};
};
Use bellow code to display the exact error coming while calling Ajax request
header('Access-Control-Allow-Origin: *');
ini_set('display_errors', 1);
error_reporting(E_ALL);
Hope this helps, Accept the answer if it works.. or comment
You have configured two users:
Username root with password t00r
Username user with password passw0rd
According to your screenshot you are trying to use username t00r with password passw0rd. This does not exist in your configuration. Use one of the username password combinations mentioned above.

Handling user authorization with Instagram API

I am building a pretty simple web application. I'm having trouble handling the code return after a user logs in with Instagram. I'm also using another API to assist me you can find it here: https://github.com/cosenary/Instagram-PHP-API.
My homepage logs the user in you can see the php code below
<?php
require 'Instagram.php';
use MetzWeb\Instagram\Instagram;
// initialize class
$instagram = new Instagram(array(
'apiKey' => 'YOUR_APP_KEY',
'apiSecret' => 'YOUR_APP_SECRET',
'apiCallback' => 'YOUR_APP_CALLBACK' // must point to success.php
));
// create login URL
$loginUrl = $instagram->getLoginUrl();
?>
Users are successfully sent to the Instagram login page but when they authorize my app and Instagram responds with a http://your-redirect-uri?code=CODE The next page fails to render.
You can see the code for the "success" page that is supposed to be displayed below.
/**
* Instagram PHP API
*
* #link https://github.com/cosenary/Instagram-PHP-API
* #author Christian Metz
* #since 01.10.2013
*/
require_once 'Instagram.php';
use MetzWeb\Instagram\Instagram;
// initialize class
$instagram = new Instagram(array(
'apiKey' => 'YOUR_APP_KEY',
'apiSecret' => 'YOUR_APP_SECRET',
'apiCallback' => 'YOUR_APP_CALLBACK' // must point to success.php
));
// receive OAuth code parameter
$code = $_GET['code'];
// check whether the user has granted access
if (isset($code)) {
// receive OAuth token object
$data = $instagram->getOAuthToken($code);
$username = $username = $data->user->username;
// store user access token
$instagram->setAccessToken($data);
// now you have access to all authenticated user methods
$result = $instagram->getUserMedia();
} else {
// check whether an error occurred
if (isset($_GET['error'])) {
echo 'An error occurred: ' . $_GET['error_description'];
}
}
?>
If users cancel the authorization request the "success" page properly renders and displays the correct error message. So I believe my issue is in the handling of the code parameter that Instagram returns to my web app. Thanks for the help.
Check that YOUR_APP_CALLBACK redirect url is correct - it should be the same here as it is in your Instagram App. Check out their guidelines for acceptable redirect urls here: http://instagram.com/developer/authentication/
As long as $_GET['code']; is set then the plugin should take care of the rest so I would check that this is being set too.
If you haven't done this already have a look at the plugin example here.
That should get you started.

Categories