How to get user in Laravel by XSRF-TOKEN cookie? - php

I can't get the authenticated user in Laravel app. I have this codes:
config/auth.php
return [
'defaults' => [
'guard' => 'sanctum',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'members',
],
'api' => [
'driver' => 'session',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'members' => [
'driver' => 'eloquent',
'model' => Domain\Customer\Models\Member::class,
]
],
];
config/sanctum.php
return [
'stateful' => // ...
'guard' => null,
'expiration' => null,
'middleware' => [
'verify_csrf_token' => App\Http\Middleware\VerifyCsrfToken::class,
'encrypt_cookies' => App\Http\Middleware\EncryptCookies::class,
],
];
routes/web.php
Route::prefix('auth')->group(function ($router) {
Route::post('login', [AuthController::class, 'loginAsMember']);
// ...
});
Route::middleware('lang')->group(function ($router) {
// ...
Route::prefix('{locale}')->group(function () {
Route::middleware('auth')->group(function () {
Route::get('webshop/basket', [PublicBasketController::class, 'show'])->name(RouteName::BASKET);
});
});
// ...
});
I have an Authenticate middleware where I try to catch the user and if it's not logged in I redirect to the custom login url.
class Authenticate extends Middleware
{
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route(RouteName::LOGIN, ['local' => App::getLocale()]);
}
}
}
In here if I dd(Auth::user()) it receives null.
But if I dd($request) I see this:
+cookies: Symfony\Component\HttpFoundation\InputBag {#46 ▼
#parameters: array:4 [ ▼
"XSRF-TOKEN" => "MbJcRadlrAJ2mDhECvWwMFyIe0fyqrQUO83K2U1K"
"laravel_session" => "mqWuCqTRD074TOvOPMGRfIIgP0jxKLyoD8VyyWCS"
]
}
+headers: Symfony\Component\HttpFoundation\HeaderBag {#49 ▼
#headers: array:13 [▼
"cookie" => array:1 [▼
0 => "_ga=... ▶"
]
"accept-language" => array:1 [▶]
"accept-encoding" => array:1 [▶]
"referer" => array:1 [▶]
"accept" => array:1 [▶]
"user-agent" => array:1 [▶]
"upgrade-insecure-requests" => array:1 [▶]
"cache-control" => array:1 [▶]
"pragma" => array:1 [▶]
"connection" => array:1 [▶]
"host" => array:1 [▶]
"content-length" => array:1 [▶]
"content-type" => array:1 [▶]
]
#cacheControl: array:1 [▼
"no-cache" => true
]
}
So there is an valid XSRF-TOKEN cookie, but Laravel did not identify the user.
How can I get user by XSRF-TOKEN cookie?

Try using dd($request->user) or dd(auth('sanctum')->user().

Related

Can't send mail on server using Laravel and mailjet

I am working on a Laravel project and try to send emails using mailjet. Sending mails local works fine, but using the same settings on my centos 7 webserver gives me an error which I can't resolve for days now.
.env settings
MAIL_MAILER=smtp
MAIL_DRIVER=smtp
MAIL_HOST=in-v3.mailjet.com
MAIL_PORT=587
MAIL_USERNAME=***
MAIL_PASSWORD=***
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=no-reply#***.com
MAIL_FROM_NAME="${APP_NAME}"
Sending the email
Mail::send('emails.auth.verify-email', ['token' => $token, 'user' => $user], function($message) use($user){
$message->to($user->email);
$message->subject('Email Verification Mail');
});
Error on CentOS 7 Server
Swift_TransportException
Connection could not be established with host in-v3.mailjet.com :stream_socket_client(): unable to connect to tcp://in-v3.mailjet.com:587 (Permission denied)
I already tried
restarting apache
sudo reboot
php artisan cache:clear
php artisan config:clear
I have also tried mailgun instead of mailjet, got me the same error (only on the server, worked fine local)
hard coding the connection credentials in config/mail.php instead of loading them from the .env file
as requested in the comments, here is the output of: dd(Config::get('mail'))
array:4 [▼
"default" => "smtp"
"mailers" => array:8 [▼
"smtp" => array:8 [▼
"transport" => "smtp"
"host" => "in-v3.mailjet.com"
"port" => 587
"encryption" => "tls"
"username" => "***"
"password" => "***"
"timeout" => null
"auth_mode" => null
]
"ses" => array:1 [▼
"transport" => "ses"
]
"mailgun" => array:1 [▼
"transport" => "mailgun"
]
"postmark" => array:1 [▼
"transport" => "postmark"
]
"sendmail" => array:2 [▼
"transport" => "sendmail"
"path" => "/usr/sbin/sendmail -t -i"
]
"log" => array:2 [▼
"transport" => "log"
"channel" => null
]
"array" => array:1 [▼
"transport" => "array"
]
"failover" => array:2 [▼
"transport" => "failover"
"mailers" => array:2 [▼
0 => "smtp"
1 => "log"
]
]
]
"from" => array:2 [▼
"address" => "no-reply#pokeshares.com"
"name" => "PokeShares"
]
"markdown" => array:2 [▼
"theme" => "default"
"paths" => array:1 [▼
0 => "/var/www/pokeshares/resources/views/vendor/mail"
]
]
]
These look like the correct settings.
Any help is appreciated!

Cant use multi auth middleware with guard in route

im using two auth table in my application
organizer and admin.
my config/auth.php file is here
return [
'defaults' => [
'guard' => 'manager'
],
'guards' => [
'manager' => [
'driver' => 'session',
'provider' => 'managers',
],
'organizer' => [
'driver' => 'session',
'provider' => 'organizers',
],
],
'providers' => [
'managers' => [
'driver' => 'eloquent',
'model' => App\Models\Manager::class,
],
'organizers' => [
'driver' => 'eloquent',
'model' => App\Models\Organizer::class,
],
],
'passwords' => [
],
'password_timeout' => 10800,
]
here is my problem on web.php (route)
Route::middleware('auth:manager')->prefix('/account')->group(function()
{
Route::get('/desk',function()
{
echo 1;
});
});
Route::middleware('auth:organizer')->prefix('/account')->group(function()
{
Route::get('/desk',function()
{
echo 2;
});
});
there is any problem here? because when i login into manager or organizer and set auth for theme its not working on middlware.
can someone solve my problem?

Laravel Passport: Provider for API Guard returning null

I have an API using Laravel 5.7 and Passport. I'm trying to get the User Provider from the Guard when calling the API but it's returning null ONLY for the API Guard.
When I use dd(auth()) I get the following:
#guards: array:2 [▼
"web" => SessionGuard {#489 ▼
#name: "web"
#lastAttempted: null
#viaRemember: false
#session: Store {#492 ▶}
#cookie: CookieJar {#493 ▶}
#request: Request {#55 ▶}
#events: Dispatcher {#35 ▶}
#loggedOut: false
#recallAttempted: false
#user: null
#provider: EloquentUserProvider {#483 ▼
#hasher: HashManager {#488 ▶}
#model: "App\User"
}
}
"api" => RequestGuard {#526 ▼
#callback: Closure {#527 ▶}
#request: Request {#55 ▶}
#user: User {#655 ▶}
#provider: null
}
]
On my config/auth.php file:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
],
Is there any other configuration I have to set to make this work?

Yii2 always log application category with $_COOKIE, $_SESSION and $_SERVER (category filter not working properly)

I am new to Yii2 and I need some manual logging to Data Base after some actions has happened. The thing that seems best for me is to filter by category. The problem is that Yii2 always add extra line with information $_COOKIE, $_SESSION and $_SERVER.
Is this normal? How can I disable the extra log line?
This is the fronted configuration
return [
'id' => 'app-frontend',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'frontend\controllers',
'components' => [
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\DbTarget',
'categories' => ['manual'],
]
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
],
'params' => $params,
];
And this is the action code:
public function actionTest()
{
$logger = Yii::getLogger();
\Yii::info('catalog info', 'manual');
$logger->flush();
Yii::$app->end();
}
And this is the result:
Thanks to rkm answer this configuration now works:
[
'id' => 'app-frontend',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'frontend\controllers',
'components' => [
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'except' => [
'manual',
],
'class' => 'yii\log\FileTarget',
'categories' => ['application'],
],
[
'class' => 'yii\log\DbTarget',
'categories' => ['manual'],
'logVars' => [],
]
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
],
'params' => $params,
];
Add 'logVars' => [], in your config to log component like this if you don't need any global variables.
'components' => [
...
'log' => [
...
'targets' => [
[
'class' => 'yii\log\FileTarget',
'logVars' => [],
]
]
...
]
...
]
More info about configuring logging in the docs

Yii2 disable Bootstrap Js, JQuery and CSS

Same as title, i don't want using bootstrap.css and bootstrap.js. I try using:
'assetManager' => [
'bundles' => [
'yii\bootstrap\BootstrapAsset' => [
'css' => [],
],
],
],
It remove bootstrap.css but can't remove bootstrap.js. Somebody can help me?
In web.php config file add the following code into components array:
'assetManager' => [
'bundles' => [
'yii\bootstrap\BootstrapPluginAsset' => [
'js'=>[]
],
],
],
To be more comprehensive:
in order to disable Css (bootstrap.css):
'assetManager' => [
'bundles' => [
'yii\bootstrap\BootstrapAsset' => [
'css' => [],
],
],
],
in order to disable JS (bootstrap.js):
'assetManager' => [
'bundles' => [
'yii\bootstrap\BootstrapPluginAsset' => [
'js'=>[]
],
],
],
in order to disable JQuery (jquery.js)
'assetManager' => [
'bundles' => [
'yii\web\JqueryAsset' => [
'js'=>[]
],
],
],
In order to have all of them disabled:
'assetManager' => [
'bundles' => [
'yii\web\JqueryAsset' => [
'js'=>[]
],
'yii\bootstrap\BootstrapPluginAsset' => [
'js'=>[]
],
'yii\bootstrap\BootstrapAsset' => [
'css' => [],
],
],
],
UPDATE
As Soju mentioned in comments, another alternative way would be disabling these files in AppAsset class, which is located in ./assets/, then remove the following lines:
public $depends = [
'yii\web\YiiAsset', #REMOVE
'yii\bootstrap\BootstrapAsset', #REMOVE
];
On AppAsset.php file add this:
public function init()
{
parent::init();
// resetting BootstrapAsset to not load own css files
\Yii::$app->assetManager->bundles['yii\\bootstrap\\BootstrapAsset'] = [
'css' => [],
'js' => []
];
}
For anyone that gets "Invalid Call" errors you have to add Ali's answer to 'components' in $config variable in app/config/web.php E.g.
'components' => [
'assetManager' => [
'bundles' => [
'yii\web\JqueryAsset' => [
'js'=>[]
],
'yii\bootstrap\BootstrapPluginAsset' => [
'js'=>[]
],
'yii\bootstrap\BootstrapAsset' => [
'css' => []
]
]
],
...
],

Categories