laravel 4 hybridauth on multiple routes - laravel

I'm just currently trying to switch from CodeIgniter to Laravel.
I have implemented the hybridouth method successful, but it seems to be only working for that route it's specified on.
I've tried searching for tutorials and examples but even they only show the auth is working on 1 route.
How can I give some function along to every route to check if a user is logged in?
Group for which the auth is needed.
Route::group(array('before' => 'auth'), function()
{
// ALL ROUTES WITH AUTH NEEDED
});
This seems to call the normal auth and i'm using the hybridauth
Route::get('social/{action?}', array("as" => "hybridauth", function($action = "")
{
if ($action == "auth") {
try {
Hybrid_Endpoint::process();
}
catch (Exception $e) {
return Redirect::route('hybridauth');
}
return;
}
try {
$socialAuth = new Hybrid_Auth(app_path() . '/config/hybridauth.php');
$provider = $socialAuth->authenticate("facebook");
$userProfile = $provider->getUserProfile();
}
catch(Exception $e) {
return $e->getMessage();
}
echo "<pre>" . print_r( $userProfile, true ) . "</pre><br />";
}));

If you are going to run the request at every route, use a filter
App::before(function($request)
{
//check if user logged in here
});
or create filter and group your routes
Route::group(array('before' => 'auth'), function()
{
});

Related

Catching org_internal 403 error via Google's OAUTH?

I have google OATH setup via socialite (only for within our organisation) and everything is working fine.
One thing I'd like to try and do is catch this "error" and get redirected back to our login page with a custom message telling the user that they do not belong to our organisation.
In principle this works fine, they can just hit the back button... but for fluidity and design, I'd like to catch this and redirect back to our home page.
Is this even possible? If so, how would you recommend I go about it?
public function show()
{
return view('auth.login');
}
public function redirectToProvider($driver)
{
if( ! $this->isProviderAllowed($driver) ) {
return $this->sendFailedResponse("{$driver} is not currently supported");
}
try {
return Socialite::driver($driver)->redirect();
} catch (Exception $e) {
return $this->sendFailedResponse($e->getMessage());
}
}
public function handleProviderCallback( $driver )
{
try {
$user = Socialite::driver($driver)->user();
} catch (Exception $e) {
return $this->sendFailedResponse($e->getMessage());
}
// check for email in returned user
return empty( $user->email )
? redirect()->intended('/login?failed=1')
: $this->loginOrCreateAccount($user, $driver);
}
protected function sendSuccessResponse()
{
return redirect()->intended('/');
}
protected function sendFailedResponse($msg = null)
{
return redirect()->intended('/login?failedResponse='.$msg);
}
protected function loginOrCreateAccount($providerUser, $driver)
{
// check for already has account
$user = User::where('email', $providerUser->getEmail())->first();
// if user
if( $user ) {
// update the avatar and provider that might have changed
$user->update([
'avatar' => $providerUser->avatar,
'provider' => $driver,
'provider_id' => $providerUser->id,
'access_token' => $providerUser->token
]);
} else {
return redirect()->intended('/login?noUser=1');
}
// login the user
Auth::login($user, true);
return $this->sendSuccessResponse();
}
private function isProviderAllowed($driver)
{
return in_array($driver, $this->providers) && config()->has("services.{$driver}");
}

Multiple pages to open based on single route 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.

give only authenticated user ability to fetch his own data with Laravel API and Sanctum

i have this function for get orders for only authenticated user:
function show($uid) {
try {
$user = User::findOrFail($uid);
$orders = $user->orders;
return $orders;
}catch (\Exception $e) {
return response()->json(['messsage' => "cannot show order for this user"]);
}
}
it is a end point for API in this route:
Route::group(['middleware' => ['auth:sanctum']], function () {
Route::get('/order/{id}', [OrdersController::class, 'show']);
});
but now if anyone just add any uid, he can display all orders...
my question is how can i protect this function so just auth user can fetch data: and i have used Sanctum in my project
in laravel with blade i just do like this:
function show() {
$uid = auth()->id();
try {
$user = User::findOrFail($uid);
$orders = $user->orders;
return $orders;
}catch (\Exception $e) {
return response()->json(['messsage' => "cannot show order for this user"]);
}
}
Thank you all...... I have found the solution, i could find the id of Authenticated user simply by this since i use the guard (sanctum):
auth('sanctum')->user()->id
this will give me the id for auth user depending on the token.
and the solution will be like this:
function show(Request $request) {
try {
$uid = auth('sanctum')->user()->id;
$user = User::findOrFail($uid);
$orders = $user->orders;
return $orders;
}catch (\Exception $e) {
return response()->json(['messsage' => "cannot show order for this user"]);
}
}

Laravel authentication and filters

I need help, can someone tell me if my work is correct with the authentication users profiles? I have the next files:
file routes.php (I used only two groups for this example)
<?php
//home
Route::get('/',function()
{
return Redirect::to('login');
});
//login get
Route::get('login','AuthController#showLogin');
//login for form
Route::post('login','AuthController#postLogin');
//routes for admin
Route::group(array('before' => 'adminFilter'),function()
{
Route::get('/adminHomePage',function()
{
return View::make('adminHome');
});
});
//route for common user
Route::group(array('before' => 'commonUserFilter'),function()
{
Route::get('/commonUserPage',function()
{
return View::make('commonPage');
});
});
Route::get('logout','AuthController#logout');
?>
file filters.php
<?php
Route::filter('adminFilter', function($route, $request)
{
if (Auth::user()->profile != 1)
{
return Redirect::to('/logout');
}
});
Route::filter('commonUserFilter',function($route, $request)
{
if (Auth::user()->profile != 2)
{
return Redirect::to('/logout');
}
});
?>
file AuthController.php
<?php
public function showLogin()
{
return View::make('login');
}
public function postLogin()
{
//Get user data from login form
$user = array(
'user' => Input::get('username'),
'password' => Input::get('password'));
if(Auth::attempt($user,true))
{
switch (Auth::user()->profile)
{
case 1:
//home admin
return Redirect::to('/adminHomePage');
break;
case 2:
//home common user
return Redirect::to('/commonUserPage');
break;
}
}
else
{
return Redirect::to('login')
->with('mensaje_error','Incorrect data.')
->withInput();
}
}
public function logOut()
{
Auth::logout();
return Redirect::to('/login')
->with('mensaje_error', 'Your session was closed.');
}
?>
One security issue (If you are using Laravel 4 +)
In routes.php:
Route::post('name', Controller#class);
Change it to:
Route::group(array('before' => 'csrf'), function() {
Route::post('name', Controller#class);
});
In your form, you have to add this: {{ Form::token() }}.
One little tip: I prefer to give all your routes a unique names.. How this works can you find here.

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