I am switching users in laravel and I succeeded in that as well but the thing is when I redirect the user to the dashboard after successful login it redirects to login form instead I don't know what am I doing wrong. Here is the code I am using.
public function user_reauthenticate(Request $request) {
$input = Input::all();
$data = User::where('email', $input['email'])->first();
if ($data) {
if (Hash::check($input['password'], $data->password)) {
Session::put('email', $input['email']);
$newuser = Student::find($input['new_user']);
session(['orig_user' => $data->id]);
Auth::login($newuser);
return Redirect::back();
} else {
$response = 'Wrong Credentials';
}
} else {
$response = 'User does not exist';
}
}
Can anyone help me find out the issue?
Edited
You can log in with
Auth::loginUsingId(1);
New edited
// If you have the guard student and multiple auth
$auth = auth()->guard('student');
$objAuth = $auth->loginUsingId($input['new_user']);
//Single Auth
$objAuth = Auth::loginUsingId($input['new_user']);
Add this to your top of the file:- use Illuminate\Foundation\Auth\AuthenticatesUsers;
Afterwards add a if function like below in your already completed code:-
public function user_reauthenticate(Request $request)
{
use AuthenticatesUsers;
$input = Input::all();
$data = User::where('email', $input['email'])->first();
if ($data) {
if (Hash::check($input['password'], $data->password))
{
Session::put('email', $input['email']);
$newuser = Student::find($input['new_user']);
session(['orig_user' => $data->id]);
Auth::login($newuser);
if ($this->attemptLogin($request))
{
return $this->sendLoginResponse($request);
}
}
else
{
$response = 'Wrong Credentials';
}
}
else
{
$response = 'User does not exist';
}
}
After this method override this method as follows:-
protected function authenticated(Request $request, $user)
{
return redirect()->route('dashboard');
}
Check whether your dashboard route is named dashboard or if not name it.
Related
I've been stuck with Broadcasting on private channel in authentication part. What I have done is, I made custom authEndpoint in Echo server
"authEndpoint": "/broadcastAuth",
Controller:
public function broadcastAuth(Request $request){
$channel = $this->normalizeChannelName($request->channel_name);
$broadcaster = new CustomBroadcaster();
$channelAuth = $broadcaster->verifyUserCanAccessChannel($request, $channel);
if($channelAuth){
return true;
}
return response()->json([
'message' => 'Not allowed'
], 403);
}
I have made a custom broadcaster class that extends Illuminate\Broadcasting\Broadcasters\Broadcaster
so that I can override verifyUserCanAccessChannel method
My verifyUserCanAccessChannel method:
public function verifyUserCanAccessChannel($request, $channel)
{
Log::info($this->channels);
foreach ($this->channels as $pattern => $callback) {
if (! $this->channelNameMatchesPattern($channel, $pattern)) {
continue;
}
$parameters = $this->extractAuthParameters($pattern, $channel, $callback);
$handler = $this->normalizeChannelHandlerToCallable($callback);
if ($result = $handler($request->user(), ...$parameters)) {
return $this->validAuthenticationResponse($request, $result);
}
}
throw new AccessDeniedHttpException;
}
Here I have logged $this->channels to get the registered channels from routes/channel.php
But the result is empty.
Here is my BroadcastServiceProvider:
public function boot()
{
require base_path('routes/channels.php');
}
Here is my channel.php:
Broadcast::channel('App.User.{id}', function ($user, $id) {
return (int) $user->id === (int) $id;
});
Broadcast::channel('post-comment.{id}', function ($user, $id){
\Illuminate\Support\Facades\Log::info($user);
return true;
});
And I have uncommented both in config/app.php
Illuminate\Broadcasting\BroadcastServiceProvider::class,
App\Providers\BroadcastServiceProvider::class,
What could be the mistake here. Please help me figure this out.
Thank you in advance.
I have a multiauth project. I have the default authentication and a custom guard. At the login controller, when I make the login attempt, it authenticates as expected. However, when it gets to the homepage, the custom guard is not logged in anymore.
Users that use the custom guard already log in through an external API, so i don't want them on my users table. I just need a couple of fields to show them some content.
LoginController.php (Up to the return, attempt method returns TRUE)
...irrelevant code...
Auth::guard('ivao')->attempt(array('vid' => $user_array->vid, 'name' => $user_array->name, 'surname' => $user_array->surname), true);
Cookie::queue(Cookie::forever($this->cookie_name, $_COOKIE['ivao_token']));
Cookie::queue(Cookie::forever('vid', $user_array->vid));
return redirect('/');
...irrelevant code...
CustomProvider.php
class CustomUserProvider extends ServiceProvider implements UserProvider
{
public function retrieveById($identifier)
{
}
public function retrieveByToken($identifier, $token)
{
if(Cookie::get('rememberToken') == $token)
{
$user = new ApiUser();
$user->vid = Cookie::get('vid');
$user->name = Cookie::get('name');
$user->surname = Cookie::get('surname');
return $user;
}
else return NULL;
}
public function updateRememberToken(UserContract $user, $token)
{
if(Cookie::get('rememberToken') == $token)
{
Cookie::queue(Cookie::forever('vid', $user->vid));
Cookie::queue(Cookie::forever('name', $user->name));
Cookie::queue(Cookie::forever('surname', $user->surname));
Cookie::queue(Cookie::forever('rememberToken'), $token);
return TRUE;
}
else return FALSE;
}
public function retrieveByCredentials(array $credentials)
{
$user = new ApiUser();
$user->vid = $credentials['vid'];
$user->name = $credentials['name'];
$user->surname = $credentials['surname'];
return $user;
}
public function validateCredentials(UserContract $user, array $credentials)
{
return TRUE; //already validated at the API
}
}
Homepage Controller (Here both check methods return FALSE)
class PagesController extends Controller
{
public function index($folder= '', $page= 'inicio')
{
if( !(Auth::check() || Auth::guard('ivao')->check()) ) return redirect('/login');
...irrelevant code...
Please let me know if you need further information. Hope someone can help. I'm stuck. Thanks.
I have used laravel auth facade for user authentication. When I try to login using wrong credentials Validation Exception is generated displaying The given data is invalid.
LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function redirectTo()
{
if(auth()->user()->role_id == 3)
return 'home';
else if (auth()->user()->role_id==2)
return 'expert';
return redirect('/logout')->with('error','You dont have User access');
}
}
I want it to redirect to login page displaying the error "Invalid Credentials". What should I do ?
In redirectTo method you must response string.
public function redirectTo()
{
if(auth()->user()->role_id == 3)
return 'home';
else if (auth()->user()->role_id==2)
return 'expert';
session()->flash('errors', 'Your message')
return 'logout';
}
Tested on Laravel 7. It's possible to do using function redirectTo() or without it's usage.
public function redirectTo()
{
$user = auth()->user();
if($user->role_id == 3) {
return 'home';
} else if ($user->role_id == 2) {
return 'expert';
}
$this->guard()->logout();
throw ValidationException::withMessages([$this->username() => __('You dont have User access.')]);
}
If you don't want to use that function, you can do it for example in function validateLogin:
protected function validateLogin(Request $request)
{
$user = User::where('email', $request->email)->first();
if ($user && $user->role_id == 3) {
$this->redirectTo = 'home';
} elseif ($user && $user->role_id == 2) {
$this->redirectTo = 'expert';
} elseif ($user) {
throw ValidationException::withMessages([$this->username() => __('You dont have User access.')]);
}
return $request->validate([
$this->username() => 'required|string',
'password' => 'required|string',
]);
}
or in function attemptLogin:
protected function attemptLogin(Request $request)
{
$attempt = $this->guard()->attempt(
$this->credentials($request), $request->filled('remember')
);
if (!$attempt) {
return false;
}
$user = $this->guard()->getLastAttempted();
if ($user->role_id == 3) {
$this->redirectTo = 'home';
} elseif ($user->role_id == 2) {
$this->redirectTo = 'expert';
} else {
$this->guard()->logout();
throw ValidationException::withMessages([$this->username() => __('You dont have User access.')]);
}
return true;
}
In LoginController I override the credentials method, like this:
protected function credentials(Request $request)
{
$credentials = $request->only($this->username(), 'password');
$credentials['status'] = User::STATUS_ACTIVE;
return $credentials;
}
And this work pretty fine. But when a try to add a parameter which is not a column of the Users table I don't know how to check there. Some like this:
protected function credentials(Request $request)
{
$credentials = $request->only($this->username(), 'password');
$credentials['status'] = User::STATUS_ACTIVE;
$credentials['customer-status'] = Customer::STATUS_ACTIVE;
return $credentials;
}
Where can I check if the value is correct? I tried to make an event listener to attempt login, but it doesn't work. My idea is to make an Eloquent query to return an account of customers activities. If more then one, customer-status for this user is true.
If anyone is interested in knowing how I solved it, the explanation is as follows:
Based on this code I found in github: https://gist.github.com/joseluisq/fb84779ea54eaebf54a9d8367117463e
In LoginController.php I override 2 methods(login and sendFailedLoginResponse):
public function login(Request $request)
{
$this->validateLogin($request);
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
$this->incrementLoginAttempts($request);
$user = User::where('email', $request->email)->first();
if (!$user) {
return $this->sendFailedLoginResponse($request);
}
$customers = Customer::join('users_customers', 'users_customers.customer_id', 'customers.id')
->where([
['users_customers.user_id', '=', $user->id],
['customers.status', '=', Customer::STATUS_ACTIVE]
])
->count();
if ($customers === 0) {
return $this->sendFailedLoginResponse($request, 'auth.inactive');
}
if ($this->attemptLogin($request)) {
return $this->sendLoginResponse($request);
}
return $this->sendFailedLoginResponse($request);
}
protected function sendFailedLoginResponse(Request $request, $trans = 'auth.failed')
{
$errors = ['email' => trans($trans)];
if ($request->expectsJson()) {
return response()->json($errors, 422);
}
return redirect()
->back()
->withErrors($errors);
}
Remember yourself to define message on auth.php and set uses needed.
Ps.: I don't use $credentials['customer-status'] = Customer::STATUS_ACTIVE;,
as I thought I would.
I created a website with Register SMS functionality that the contact was sent for to him when registering an identity code and he is also stored in the file name table.
Now what do I need to do to controllerverify until user the contact with his code and activate his account?
code verifyControlller ::
public function activeUser(Request $request, $phone)
{
$code = $request->code;
$user = User::where('phone', $phone)->whereHas('activitionCode', function ($query , $request) {
$query->where('code', $request->code)->where('expire', '<', Carbon::now());
})->first();
if ($user) {
$user->active = 1;
$user->save();
} else {
return back()->withErrors(['code', 'code invalide']);
}
}
}