Multiple pages to open based on single route laravel - laravel

I'm very new to Laravel and have a scenario where if a user tries to apply for a job but is not logged in then the user is redirected to an Auth0 login, at this point I want to return the user to a dashboard but also open the job application in a new tab. Is it possible to return two views like this?
I tried to return an array with both redirects in;
public function callback(): RedirectResponse
{
$redirect_to = session('auth_return_to_url', '/');
if (str_contains($redirect_to, '/job/view/')) {
$redirect = [Redirect::intended($redirect_to), Redirect::intended(route('dashboard.dashboard'))];
} else {
$redirect = Redirect::intended(route('dashboard.dashboard'));
}
try {
$this->doLogin();
} catch (Exception $exception) {
Log::error('Auth0 initialization error', [
'message' => $exception->getMessage()
]);
return $redirect;
}
return $redirect;
}
but this understandably fails with the following message.
Return value of App\Http\Controllers\Auth\Auth0CallbackController::callback() must be an instance of Illuminate\Http\RedirectResponse, array returned

why you not add a param to login url. Example
login?redirect=%2Fjob%2Fview
And after logged in, you can redirect user to url you want.

Related

Laravel: How can I return more data from a custom UserProvider?

I have successfully created a custom user provider and have implemented a user interface.
I am trying to save the user object to my local Postgres database that is returned from a third party backend.
Here is what my retrieveByCredentials method looks like:
// MyCustomUserProvider.php
public function retrieveByCredentials(array $credentials) {
if (empty($credentials)) {
return null;
}
try {
$response = Http::asForm()
->retry(3, 100)
->timeout(5)
->post('https://my-custom-auth-endpoint', $credentials)
->json();
if ($response) {
$user = User::firstOrNew([
'foo' => $response['foo'],
]);
$user->save();
return $user;
}
} catch (RequestException $e) {
Log::info('-----------------------------------------------------------');
Log::info(print_r($e->getMessage(), true));
Log::info('-----------------------------------------------------------');
return $e->getMessage();
}
}
...
public function validateCredentials(Authenticatable $user, array $credentials): bool {
return strtoupper($user->foo) === strtoupper($credentials['foo']);
}
So far, everything is working great. I am getting the correct values/booleans for each required method. However, I need to be able to return additional info to my controller than just a boolean value. For example, if a user's password has expired, this information is coming from my 3rd party database. So far, it looks like returning the user results in a true or false response in my LoginController. If I get false back from my CustomProvider I can set a flash message of, "Invalid Credentials". But that may not always be the appropriate error.
Here is how I am calling the CustomUserProvider:
// LoginController.php
$authenticated = Auth::guard('foo')
->attempt([
'userid' => $request->username,
'password' => $request->password,
]);
// $authenticated is the response from CustomUserProvider.
dd($authenticated) // true or false.
It is understood that in my provider I just want to authenticate the user. How can I return the authenticated user back to the controller? Additionally, how can I return the error back to the controller so I can display a proper error message?
The function Auth::guard('foo')->attempt([]) will also return a boolean to tell user if the authentication is successful or not. If you want to get the auth user, just return Auth::user() after the calling that function, like return response()->json(Auth::user())

Laravel socialite, redirect back to page where button was clicked

I have a laravel website where certain news articles are 'gated' meaning they have to login/signup in order to read more than the first paragraph.
I have Laravel Socialite installed, so that users can login with Google. What I would like is for users to login via google, then be redirected back to the page which they were viewing before they clicked the 'Login using google' button.
I'll obviously hide the login area when the user is logged in.
Is this possible?
This is my code, however the redirect()->intended() does not work:
public function redirectToProvider()
{
return Socialite::driver('google')->redirect();
}
public function handleProviderCallback()
{
try {
$user = Socialite::driver('google')->user();
} catch (\Exception $e) {
return redirect('/login');
}
// check if they're an existing user
$existingUser = User::where('email', $user->email)->first();
if($existingUser){
// log them in
auth()->login($existingUser, true);
} else {
// create a new user
$newUser = new User;
$newUser->name = $user->email;
$newUser->email = $user->email;
$newUser->roles_id = 1;
$newUser->save();
auth()->login($newUser, true);
}
return redirect()->intended();
}
Thanks in advance.
M
Save the url in a session and retrieve it in the redirect method of the controller.

Redirect user to homepage if he is not authorized to access page its not working properly

If a user creates a conference with id "2" he should be allowed to access "proj.test/conference/manage/2".
But a user that did not create the conference with id "2" should be redirected to the login page if he is not authenticated. If he is authenticated should be redirected to the homepage.
But its not working properly, if the user created the conference with id 2 he can access "proj.test/conference/manage/2" but other user that did not create this conference if accesses "proj.test/conference/manage/2" it appears an error:
This action is unauthorized.
So instead of redirecting the user to the homepage it shows this error. Do you know why is not working?
I have the store method, after storing the conference the user is redirected to the management area to manage that specific conference, for example, to manage the conference with id 2 the user is redirected to "proj.test/conference/manage/2".
Store method:
public function store(Request $request)
{
$this->validate($request, [
'conference_name' => 'required|max:255|string',
...
]);
$conference = Conference::create([
'name' => $request->conference_name,
...
]);
}
Then in the AuthServiceProvider I add:
public function boot(GateContract $gate)
{
$this->registerPolicies();
$gate->define('access-management-area', function($user, $conference)
{
return $user->id == $conference->conference_creator_id;
});
}
And in the manage method I have:
public function manage($id){
$conference = Conference::findOrFail($id);
if($this->authorize('access-management-area', $conference)){
return view('conferences.manage')->with('myconference',$conference);
}
else{
return redirect('/home');
}
}
Do not use $this->authorize as it does not work the same as Gate::allows()/denies().
The authorize method will throw an exception if it fails, it will not return false for the sake of conditional comparison.
From the docs:
If the action is not authorized, the authorize method will throw an Illuminate\Auth\Access\AuthorizationException, which the default Laravel exception handler will convert to an HTTP response with a 403 status code.
So, instead, use Gate::denies for comparisons.
if(Gate::allows('access-management-area', $conference)) {
return view('conferences.manage')->with('myconference',$conference);
} else {
return redirect('/home');
}

Laravel issue with loginUsingId (Manual Authentication)

I am trying to implement a single signon on multiple domains. The concept is pretty simple i.e to send unique user tokens and then verify these tokens to find the user and then log him in.
Now after verifying the token and then grabbing the user, i do something like this
$loggedInUser = Auth::loginUsingId($user->id, true);
Now i have a custom middleware where it first checks for a logged in user, i.e
Auth::Check()
The above works fine for the first time. But on refresh Auth::check() is not validated. I have also tried using all different session drivers but still doesn't work.
I used a similar code on laravel 5.2, and it did work. But on laravel 5.3 its not validating on persistent requests.
Edit: Let me show you my Code
I have not modified AuthServiceProvider or any other guard. I do have the user model inside a directory but i have modified the path in auth.php.
Here is the route that domain1 points to:
http://domain2.com/{{$role}}/{{$route}}/singlesignon/{{$token}}
This is then picked up by verifySingleSignOn method inside the loginController which takes in the role, route that the user came in from other domain and the token. The user is then redirected to the same routes, but on domain2. Here i can successfully recieve the user id before manually logging in.
public function verifySingleSignOn($role, $route, $token)
{
// Fetch Single Signon
$userRepository = new UserRepository();
$user = $userRepository->checkForSingleSignOnToken($token, ['id']);
// Check if Token Exists
if (isset($user->id) && is_int($user->id) && $user->id != 0) {
// Manually Logging a user (Here is successfully recieve the user id)
$loggedInUser = Auth::loginUsingId($user->id);
if (!$loggedInUser) {
// If User not logged in, then Throw exception
throw new Exception('Single SignOn: User Cannot be Signed In');
}
$redirectTo = $role . '/' . $route;
return redirect($redirectTo);
} else {
return Auth::logout();
}
}
Then i have this GlobalAdminAuth middleware
// Check if logged in
if( Auth::Check() ){
$user = Auth::User();
// Check if user is active and is a globaladmin
if( !$user->isGlobalAdmin() || !$user->isActive() ){
return redirect()->guest('login');
}
}else{
return redirect()->guest('login');
}
return $next($request);
Now the first time everything works fine and the user moves through the middleware successfully . but the second time the else statement is triggered.
Edit: Code for checkForSingleSignOnToken
public function checkForSingleSignOnToken($token, $columns = array('*'))
{
return User::where('single_signon', $token)->first($columns);
}
try
Auth::login($user);
instead of
Auth::loginUsingId($user->id, true);
Cookies are restricted domain-wise. Your application on domain1.com wont be able to grab cookies set by domain2.com.
You should be customizing the guard to use some other mechanism than cookies. Maybe use a token in the query parameters.
add this to your protected $middleware array in app\Http\Kernel.php
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class
I think it has to do with an update in the framework
no using auth:check in middleware
using request->user() or auth::user()
Please review bellow code structure, i had made manual authentication
in laravel 5.0.
routes.php
Route::get('login_user_by_id/{id?}', ['as' => 'login_user_by_id', 'uses' => 'UsersController#login_user_by_id']);
Route::post('user_login_post_for_admin',['as'=>'user_login_post_for_admin','uses'=>'LoginController#user_login_post_for_admin']);
Route::get('user_logout', ['as' => 'user_logout', 'uses' => 'UsersController#user_logout']);
LoginController.php
public function user_login_post_for_admin(){
$this->set_email($_POST['email']);
$this->set_password($_POST['password']);
$this->set_login_requested_role(['Admin','Moderator']);
return $this->user_login_post();
}
public function user_login_post(){
$User = new User();
if(isset($this->email) && !empty($this->email)){
$User->set_email(trim($this->email));
$User->set_password(Hash::make(trim($this->password)));
$user_login_data = $User->check_email_password_for_login();
if(isset($user_login_data) && !empty($user_login_data)){
if (Hash::check(trim($this->password), $user_login_data[0]->password)) {
$response['user_id']=$user_login_data[0]->id;
$response['name']=$user_login_data[0]->name;
$response['surname']=$user_login_data[0]->surname;
$response['profile_picture']=$user_login_data[0]->profile_picture;
$response['SUCCESS']='True';
$response['MESSAGE']='Login Success.';
return Redirect::route('login_user_by_id',[$user_login_data[0]->id]);
}else{
Session::put('SUCCESS','FALSE');
Session::put('MESSAGE', 'Invalid Credential.');
return redirect()->back();
}
}else{
Session::put('SUCCESS','FALSE');
Session::put('MESSAGE', 'Invalid Credential.');
return redirect()->back();
}
}else{
Session::put('SUCCESS','FALSE');
Session::put('MESSAGE', 'Invalid Credential.');
return redirect()->back();
}
}
UsersController.php
public function login_user_by_id($id=''){
if(isset($_GET['id'])&&!empty($_GET['id'])){
$id = $_GET['id'];
}
$User = new User();
$Log=new Log();
$user_for_auth = $User->find($id);
Auth::login($user_for_auth, true);
$User->id=AUTH::user()->id;
$auth_user_role=$User->auth_user_role();
$rl_title=$auth_user_role[0]->rl_title;
return Redirect::route('admin_home');
}
public function user_logout(User $user){
$User=new User();
$login_user_id = AUTH::user()->id;
$User->id=AUTH::user()->id;
$auth_user_role=$User->auth_user_role();
$login_user_role=$auth_user_role[0]->rl_title;
$response['user_id']=$login_user_id;
$response['SUCCESS']='TRUE';
$response['MESSAGE']='Successfully Logout.';
Auth::logout();
return Redirect::route('admin_login');
}

How to redirect index page if user not logged in laravel

Hello i create website in laravel but i facing one problem. The problem is that when user is not log in and user type www.test.com/notifications that time showing error like this
ErrorException (E_UNKNOWN)
Undefined variable: messages (View: /home/test/app/views/message-page.blade.php)
But i want to when user is not log in and enter www.test.com/notifications so user automatic redirect to index page. Please help me i very confuse.
I using the some code in base controller is as follows:
public function checkLoggedIn(){
if(Auth::user()->check()){
return;
}
else {
return Redirect::to("/");
}
}
You should do it this way:
public function checkLoggedIn(){
if (!Auth::check()) {
return Redirect::to("/");
}
return true;
}
However I assume you want to use this function in another controller so then you should do it this way:
$result = $this->checkLoggedIn();
if ($result !== true) {
return $result;
}
to make redirection.
But Laravel have filters so you can easily check if user is logged.
You can just use in your routes.php:
Route::group(
['before' => 'auth'],
function () {
// here you put all paths that requires user authentication
}
);
And you can adjust your filter in app/filters for example:
Route::filter('auth', function()
{
if (Auth::guest())
{
if (Request::ajax())
{
return Response::make('Unauthorized', 401);
}
else
{
return Redirect::to('/');
}
}
});

Resources