Laravel: SetLocale based on value in users table - laravel

Version:
Laravel Version: 5.4.*
PHP Version: 5.6.x
Description:
I have a locale variable stored in the users table. Now I want to change the language of the app based on the user's locale variable (when the user logs in).
Steps To Reproduce:
I created a new middleware file
public function handle($request, Closure $next)
{
App::setLocale(Session::has('lang') ? Session::get('lang') : Config::get('app.locale'));
return $next($request);
}
And called this file in the Kernel.php
In my LoginController I have:
protected function authenticated(Request $request, $user)
{
Session::put('lang', $user->lang);
}
But this does not work. No errors, no different language. Anyone can help me with this?

For me, I use this one it work fine for me.
Session::put('lang', Auth::user()->lang);
or with full path
Session::put('lang', \Illuminate\Support\Facades\Auth::user()->lang);

I was able to fix it using a Event listener. With some help of this topic I managed to set the session variable based on the user's property. If someone needs more help, let me know!

Related

Redirect to custom tool url in a laravel nova application

Laravel Version: 7
Nova Version: 3
PHP Version: 7.4
Database Driver & Version:
Operating System and Version: MacOS
Browser type and version: Chrome
Reproduction Repository: https://github.com/###/###
Description:
I am trying to redirect a user after checking for a condition in a middleware, I have tried to use
return redirect('/admin/paddle-subscription');
But it does not work, it just redirects the page and shows it right in the browser url but show a 404 error in the screen, it looks that as nova uses vue.js it is creating some kind of errors.
I have been reading some post in laracast https://laracasts.com/discuss/channels/nova/nova-resource-route-redirect and it is clearer to me that it requires a special way to redirect.
I have tried
return redirect()->action('\Laravel\Nova\Http\Controllers\RouterController#show', ['resource' => '/admin/paddle-subscription']);
And it does not work, how I am supposed to redirect properly?
Thanks
Detailed steps to reproduce the issue on a fresh Nova installation:
You can do this by creating the route in the backend first so that Laravel knows the page exists. Use Nova's RouterController#show action for the route like in your Laracast example and make sure to apply all the Nova middleware to it.
In app/Providers/NovaServiceProvider.php add a custom route to your routes() method:
protected function routes()
{
Nova::routes()
->withAuthenticationRoutes()
->withPasswordResetRoutes()
->register();
Route::domain(config('nova.domain', null))
->middleware(['web'])
->as('nova.')
->prefix(Nova::path())
->group(function () {
Route::get('/admin/paddle-subscription', [\Laravel\Nova\Http\Controllers\RouterController::class, 'show'])
->middleware(config('nova.middleware', []));
});
}
In your middleware you can now redirect to that route and the page will render properly:
public function handle(Request $request, Closure $next)
{
if ($foo === $bar) {
return new \Illuminate\Http\RedirectResponse('/admin/paddle-subscription');
}
return $next($request);
}
try this:
add in your nova action
public function handleRequest(\Laravel\Nova\Http\Requests\ActionRequest $request)
{
parent::handleRequest($request);
return Action::redirect('/admin/paddle-subscription');
}

Google2FALaravel Authenticator always return True in Laravel 6

There is a problem using the Google-Authenticator Module "PragmaRX\Google2FALaravel" in my Laravel6 project.
I installed it following the manual on the github page. Setting up 2FA-Users via QRcode works like a charm, but the authentication middleware always returns "True" for authenticated, regardless if the user has passed the 2fa challenge or not.
public function handle($request, Closure $next)
{
$authenticator = app(Google2FAAuthenticator::class)->boot($request);
if ($authenticator->isAuthenticated()) { **//always returns true**
return $next($request);
}
return $authenticator->makeRequestOneTimePasswordResponse();
}
I assume it has something to do with the "CARTALYST/Sentinel" package i am using (instead of the built-in laravel "Auth" Manager), someone experienced similar behaviour and knows how to fix this?

Is it possible to force logout using user id in Laravel?

I'm wondering if there is any simple way to force logout different users by their id? For example I need to block currently lodged in user so I want to log out him after I set his status to block.
P.S.
I cant use middleware for this to check on each request.
I do this inside the Authenticate middleware
if (!Auth::user()->isActive()) {
Auth::logout();
return Redirect::home();
}
The user is already loaded there, no additional database query is needed here.
I don't think that's a performance issue, you just do a little if statement and you do it only if the user needs to be authenticated.
It's super easy if you are using database session driver:
DB::table('sessions')->where('user_id', $userId)->delete();
#PerterPan666 thanks, ya i ended up creating a middleware and adding it to the web group.
public function handle($request, Closure $next)
{
if (Auth::check())
{
if (Auth::User()->is_active != 'Y')
{
Auth::logout();
return redirect()->to('/')->with('warning', 'Your session has expired because your account is deactivated.');
}
}
return $next($request);
}
For anyone using later Laravel 5.6+, there's a method available for this built in. Doesn't mention where to call logoutOtherDevices, but LoginController#authenticated looks to work well as you can pass through their password, as required by the method
https://laravel.com/docs/5.8/authentication#invalidating-sessions-on-other-devices
public function authenticated(Request $request, $throttles)
{
\Illuminate\Support\Facades\Auth::logoutOtherDevices($request->get('password'));

Set Locale when using Auth::loginUsingId for phpunit

I have several languages in my Laravel 5.2 app. Each locale is stored in DB in th User Model. So, each time a user log, the locale must update.
Thing is in my Test, I use a lot Auth::loginUsingId, because I need to test function with differents user profiles.
So, I don't want to append to each of those calls with a App::setLocale(Auth::user->locale), nor extract it to a function.
Any Idea how should I do it???
What I did to address this problem is creating a middleware with
public function handle($request, Closure $next)
{
if ($user = Auth::user()) {
App::setLocale($user->locale);
}
return $next($request);
}
By handling all routes through this middleware, you can have the locale set automatically at each request.

Laravel 5.0 pass variable to middleware

At the moment I have to check if job record, which is being edited, belongs to right person. My get job edit route:
/user/job-edit/{slug}
So I created JobEditMiddleware but the problems is I can't access {slug} variable in my middlewar. Is there any way to do it? Thanks.
You can use segment() method to retrieve various segments of your URI.
Try following in your middleware,
\Request::segment(3)
Read More
You can access to your slug parameter easier.
public function handle($request, Closure $next, $role) {
//
}
You have to call your slug parameter like this :
$request->slug;
I think it's a better way than segment if you'll need to change your route later.

Resources