Laravel 8.6 login using url parameters through middleware - laravel

My page in the application is embeded in another application. To get to the embeded page username and password are passed using the URL like &user=foo&password=bar. The route to this page goes through a middleware('loginViaApp'). I want this middleware to login using the parameters, but i don't know how to login this way. I would expect something like this, but i don't know how to login using middleware.
class LoginViaApp:
{
if(Auth::login(['username'=>'foo','password'=>'bar'])){
return $next($request);
}else{
return error('403');
}
}
Can somebody please help me figure out how to login using middleware with parameters in the url?
Kind regards,
Jeff

You can use this logic for that, just modify it according to your need and use it in middleware
$user = User::where('username',$username)->first();
if(null === $user ){
return redirect()->route('login');
}
$passwordPass = Hash::check($password, $user->password);
if($passwordPass){
auth()->loginUsingId($user->id);
return $next($request);
}
return;

Related

Auth facade doesn't work without Sanctum api as middleware in Laravel 8

I'm creating an api through which anybody can view a page, however only admin can see all posts, while users are restricted to approved only. This is implemented via is_verified boolean variable where admin is given value of 1 and user the value of 0. I want to create a function like this
public function show(){
if(Auth::check()){
$showAllDetails = Events::all();
echo $showAllDetails;
}else {
$showUserDetails = Events:all()->where('is_verified',1);
echo $showUserDetails;
}
}
However Auth:check only works if I have sanctum api in my route
Route::middleware('auth:sanctum')->group(function () {
Route::get('view', [ViewController::class, 'show']);
});
If I run this code on Hoppscotch, it only shows if the admin is logged in (User don't require login). So a user can't see any post. If I remove the auth:sanctum middleware, only the else part of the code runs and no auth check or any stuff can run .
I need a way to incorporate both in a single function so that I can create a single route instead of creating two routes for different persons. Any way of doing such things?
public function show(){
if(Auth::check()){
$showAllDetails = Events::all();
echo $showAllDetails;
}else {
$showUserDetails = Events::where('is_verified',1)->get();
echo $showUserDetails;
}
}
I guess your else part is incorrect query, change your else part like above

Pin Verification In Laravel

I'm a beginner. I have a pin field in my user database. I want users to verify the pin before they can access there profile. how can I do this any logic?
in livewire components
public function verify (){
$user = User::select('id')->where('pin',$pin)->first();
Auth::loginUsingId($user->id);
return redirect()->intended('/user');
}
in my livewire blade I will call the verify method in the form will this work
laravel login using pincode :check the following code example may be you get the hint how to implement that, in this example code pin authentication is done using JWT and then user is allowed to access to those specific routes.
$user = User::find($uid);
try {
if (!$token = JWTAuth::fromUser($user)) {
return $this->onUnauthorized();
}
} catch (JWTException $e) {
return $this->onJwtGenerationError();
}
For somereason if you dont want to use the above JWT method you can use this one. i'm sharing the code for an example from by program which may help you
$user = User::select('id')->where('pin',$pin)->first();
Auth::loginUsingId($user->id);
return redirect()->intended('/user');

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'));

Laravel middleware one time authorization for route groups

I am designing some part of system in Laravel 5. It is expected to behavior as described below.
User gets unique url. It could be provided in email, but that will not matter.
He clicks it, and gets logged in with some temporary token (for a session lifetime), that gives him possibility to access all the urls in allowed route group, ex. account/*, but if he wants to reach other restricted urls, then he is asked to authorize with his username/password.
If he is already authorized, token login makes no effect for him.
My question is about possibility to do something like that in Laravel out of box. I know there are some middleware services, but I'm not sure if default Guard behavior will not need to be changed to work as I expect.
I used to work with Symfony before, and there it is solved by firewalls by default, so maybe also in Laravel there is prebuilt solution?
you can absolutely doing this use laravel, here is an example code not tested,
public function handle($request, Closure $next)
{
if ($this->auth->guest()) {
if (preg_match('account', $request->route()->getName()) { //if url is under account, you can get route info from $request->route();
if (!session()->get($token)) { // if not have valid token
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->route('admin.login.index',['referrer'=>urlencode($request->url())]);
}
}
} else {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->route('admin.login.index',['referrer'=>urlencode($request->url())]);
}
}
}
return $next($request);
}
then from your route just add middleware auth to your group, this is a way to define you request in on middleware, laravel 5.2 support mutiple middleware.

Laravel - Redirect after login

Im a bit of a newbie when it comes to Laravel so i was hoping someone could help out.
Im using the standard authentication and login stuff that ships with Laravel so theres nothing fancy going on, but what i want to do is check in the DB to see if a few fields are completed ( name, address, postcode ) .... If they are, then the user gets redirected to the dashboard, but if they aren't, the user will get redirected to the profile page to fill out the rest of their information.
Im guessing i should put something in my routes.php file in the
Route::post('login', function
part, but how do i check for the fields?
Any help would be greatly appreciated.
Cheers,
Once you have authenticated the user using Auth::check you'll be able to grab the authenticated user with Auth::user.
if (Auth::attempt($credentials))
{
$user = Auth::user();
if ($user->email == '' || $user->address == '')
{
return Redirect::to('user/profile');
}
return Redirect::to('home');
}
You just need to check the fields you want on the user to make sure they are there. If they're not then redirect them to the profile page. If they are redirect them to the home page or somewhere else.
You can also do it this way
if (Auth::attempt(array('email'=>Input::get('email'), 'password'=>Input::get('password')))) {
return Redirect::to('users/dashboard');
} else {
return Redirect::to('users/profile');
}
You can use this code
if (Auth::guest())
{
//user is not authenticated or logged in;
return Redirect::to('login');
}else{
//user is authenticated and logged in;
return Redirect::to('profile');
}

Resources