Check Laravel 5.7 login from external script - laravel

I have a Laravel app and I need to check if a user is logged and who from a external script. I'm using the following lines to load Laravel and try to check it.
require_once __DIR__.'/../../../vendor/autoload.php';
$app = require_once __DIR__.'/../../../bootstrap/app.php';
$app->make('Illuminate\Contracts\Http\Kernel')
->handle(Illuminate\Http\Request::capture());
/*if (Cookie::get(config('session.cookie')) != "") {
$id = Cookie::get(config('session.cookie'));
Session::driver()->setId($pericod);
Session::driver()->start();
}*/
$isAuthorized = Auth::check();
if(!$isAuthorized){
echo "NO AUTORIZADO";
exit();
}
With this lines I can access any Laravel function and I can check the login if I made GET request to the external scripts, but when the request is POST it always fails. I'm unable to check the login and I see that the session changes because can't get the existing session.
I have made many tests and I think that somethings of Laravel are not working fine, like routes or middlewares. I can made it work if I disable all encryption of the cookies and the session, but I want to use this security functions.
I'm using updated Laravel 5.7 and I had this code working in Laravel 5.4
Thank you for your help.

I discovered the problem,
The trick is that the route is external to laravel so laravel's route resolver identifies the current route as /.
It was working on GET requests because in my routes file I have the / route only as get. If I set the / route as any, everything works.
I wasn't seeing the problem because I was not terminating Laravel's execution. If I change the logged user verification to this, it shows the error:
$isAuthorized = Auth::check();
if(!$isAuthorized){
echo "NO AUTORIZADO";
$response->send();
$kernel->terminate($request, $response);
exit();
}
This two lines ends laravel execution and returns the error "405 Method Not Allowed".
$response->send();
$kernel->terminate($request, $response);
Thank you for your help.

Related

login automatically a user from Wordpress in Laravel

I'm trying to use Wordpress as a frontend CMS/Shop and Laravel as a platform that provide more advanced services to users that acquire them from WP frontend shop. After logging to Wordpress they'll have in account a link to Laravel dashboard where they have all they're acquired services. For extracting data from WP I'm using Corcel but I need users already logged in to be automatically authenticated in Laravel.
All discussions I found are related to using same users, or login the other way, from Laravel to WP. Wp and laravel are on same domain, wp in root and laravel in a /laravel dir and they;re working ok. I tried a hook on login to call laravel inside wp but this would run a parallel instance of Laravel.
this in WP as a hook in funtions.php not working:
include $_SERVER['DOCUMENT_ROOT'].'/wplaravel/vendor/autoload.php';$app = include $_SERVER['DOCUMENT_ROOT'].'/wplaravel/bootstrap/app.php';$kernel = $app->make('Illuminate\Contracts\Http\Kernel');$kernel->handle($request = Illuminate\Http\Request::capture());
$id = (isset($_COOKIE[$app['config']['session.cookie']]) ? $app['encrypter']->decrypt($_COOKIE[$app['config']['session.cookie']], false) : null);
if ($id) {
$app['session']->driver()->setId(explode('|', $id)[1]);
$app['session']->driver()->start();
// Session::all();
// $app['auth']->getSession(); // Illuminate\Session\Store
// Auth::user();
// $app['auth']->user();
// $user = App\User::find(1);
$userl = App\Models\User::where('email',$user->data->user_email)->first();
Auth::login($userl);
//session()->put('wpuser', $user->data->user_email);
//print_r(session()->all());
}
I need to have a user that login to Wordpress to be able to be authorized in Laravel without logging in there also.
If your WordPress users also have a mobile number, this might be a good option for you.
It works like this in Laravel :
$user = User::query()->where(('mobile',$requset->mobile)->first();
Auth::login($user);
First of all your idea is completely wrong if you are trying login from wp to laravel.
Here you need to do following
1.Redirect the user to laravel application with a wp session or verified secret
wp_redirect( "laravelapp.com?secure=secretcodes );
2.Verify the secret from laravel with the given secret
$verify = $request->secure;
if($verify == "secretcodes"){
//verify your own logic here
}
3.Find the desired user and use this code bellow in any controller that you redirect from wp to laravel
$user = User::find(1);
Auth::login($user);
Then it will be logged in into laravel applicaiton

Route [x] not defined when using auth middleware

I am making a website with laravel but i am getting an error while using middleware auth. it says Route[x] not defined.
i am using laravel 5.8 please some one help me
The route you have written that has no named route so you need to specify name for that route like this
Route::get('x', function() {
//
})->name('x')->middleware('auth');
for more information you can check here https://laravel.com/docs/7.x/urls#urls-for-named-routes

Laravel 5.7 email verification throws 403

I implemented email verification in a Laravel 5.7 project I'm working on. I get the email, but whenever I click on the confirm button or even the url provided in the email, I get a 403 forbidden error.
I have searched for several solutions, but haven't been able to find one to this problem. The only reasonable pointers to this error is this github issue https://github.com/laravel/framework/issues/25716 which has been merged and closed by Taylor Otwell by still this problem persists.
Here's the email I get:
Here's the error it throws when I click on the button or the actionUrl at the email footer: and here's the url shown when the 403 page is displayed https://www.mywebsite.com/email/verify/1?expires=1540140119&signature=fd7dc72b05da6f387b2f52a27bceee533b2256436f211930c1319c7a544067da
Please help me. Thank you
Edits: This problem occurs only in production app. On local, this email verification works but throws 403 on production(live) server. My email service is mailgun, and I can access every other email contents relating to the app except completing email verification.
I need help please. Thanks in anticipation
One of the reasons that was in my case can be that you are already logged in with a normal verified user, and you have clicked on the verification email link. In that case it will shoot 403 . Which is not normal in my opinion, but whatever.
For me because manually create verification route. which in laravel 6.x or 7.x The route path for verifying emails has changed. from /email/verify/{id} to /email/verify/{id}/{hash} This probably only happens because I use the rules manually, and not Auth::routes(['verify' => true])
for more information laravel upgrade guide upgrade#email-verification-route-change
This typically occurs if your application is running behind some proxies and probably doesn't handle SSL termination itself.
The solution is to add
protected $proxies = '*';
to the TrustProxies middleware.
Reference: https://laracasts.com/discuss/channels/laravel/hitting-403-page-when-clicking-verify-link-in-email-using-new-laravel-verification-57?page=1
Turns out, this often happens when you have your laravel app running behind a proxy (apache, nginx etc.) We therefore end up replacing laravel's default 'signed' middleware with our own middleware that checks for https:// links. This StackOverFlow answer here was able to fix this problem for me:
Signed route for email verification does not pass signature validation
To use Laravel email verification you must first add the proper routes.
If you take a look at Illuminate/Routing/Router.php you'll see that by default the verify route is disabled.
if($options['verify'] ?? false)
{
$this->emailVerification();
}
To enable your verification routes add the following to your web.php
Auth::routes(['verify'=>true]);
Then run
php artisan route:list
to make sure that it's working.
Check the verify method inside the VerifiesEmails trait,
there they have:
if (! hash_equals((string) $request->route('hash'), sha1($request->user()->getEmailForVerification()))) {
throw new AuthorizationException;
}
I have dumped this variable $request->route('hash') and it was null, so I overrided it in the VerificationController:
/**
* Mark the authenticated user's email address as verified.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
* #throws \Illuminate\Auth\Access\AuthorizationException
*/
public function verify(Request $request)
{
if (! hash_equals((string) $request->route('id'), (string) $request->user()->getKey())) {
throw new AuthorizationException;
}
if (! hash_equals((string) $request->query('hash'), sha1($request->user()->getEmailForVerification()))) {
throw new AuthorizationException;
}
if ($request->user()->hasVerifiedEmail()) {
return redirect($this->redirectPath());
}
if ($request->user()->markEmailAsVerified()) {
event(new Verified($request->user()));
}
return redirect($this->redirectPath())->with('verified', true);
}
And now it works!
The problem for me was my APP_URL had a protocol of http and when I clicked on the verification link NGINX automatically redirected the url from http to https that's why the signature validation failed. I updated the APP_URL to have a protocol of https and that resolved my problem.
My personal experience with this problem was that I set MAIL_DRIVER to log in the .env file, and Laravel escaped special characters (such as &) when it stored the activation link in the log.
So NEVER use the log for MAIL_DRIVER when you have verification email.
(my Laravel version was 5.8).

Laravel & PHPUnit: Getting 500 when unit testing "Passport" restricted route

I have a Laravel 5.3 app.
Inside my api.php file, there's a route for posting an answer within a poll.
Route::group(['middleware' => 'auth:api'], function () {
Route::post('/poll/answer', 'API\PollsController#createAnswer');
});
The route is part of a group, restricted by the auth:api middleware, using Laravel's Passport engine.
When calling this route from Postman or any other tool to test APIs, I get 401 which is ok because I'm not attaching the token.
But when unit testing this call using PHPUnit, it returns 500. I have no idea why.
$this->postJson('api/poll/answer');
I'm probably missing a configuration or setup instruction.
Any ideas?
The 500 error was occurring because I forgot to add an app key to the .env.testing file.
It got solved after adding that.

User Authentication in CodeIgniter

Securing a CodeIgniter Site
I am trying to use the authentication method suggested on the Tuts+ site at http://code.tutsplus.com/tutorials/easy-authentication-with-codeigniter--net-20248.
After validating the user I create a session variable as follows:
$_SESSION['username'] = $this->input->post('email_address');
Tuts+ then suggests the following be placed in all controllers:
public function __construct() {
session_start();
parent::__construct();
if(!ISSET($_SESSION['username'])){
redirect('admin_controller');
}
}
This works without any problems when I place it in my main_controller, but when I add the code to other controllers I get:
A PHP Error was encountered
Severity: Warning
Message: session_start() [function.session-start]: Cannot send session cache limiter - > > headers already sent (output started at /………….../application/controllers> /contact_controller.php:146)
This is probably a really dumb question but how do I check for the session variable in the other controllers?
This is not about session it's about redirect function; it must be called without any output before it, please check the file /contact_controller.php at line 146 if it's echoing anything before redirect.
Further information about header.

Resources