Laravel 5.2.* Laravel/socialite catch when facebook deny access - laravel-5

I'm using Laravel 5.2.* and laravel/socialite 2.0.14 and everything is fine when when trying login to facebook and in Facebook click "Okay".
But if I try to login with Facebook for the very first time and if I Click "Cancel" on Facebook to deny access, it redirect to the callback URI and triggers and error.
Here is my Controller code,
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Socialite;
class SocialiteController extends Controller
{
public function __construct()
{
}
public function facebook()
{
return Socialite::driver('facebook')->redirect();
}
public function facebookCallback()
{
$user = Socialite::driver('facebook')->user();
// $user->token;
dd($user);
}
}
Does anyone know how to catch the error or solve it?
Thanks

You can use try catch to catch exceptions. Like this:
try {
$user = Socialite::driver('facebook')->user();
}
catch (\Exception $e) {
do something.....
}

you should use try catch method for deny catch
try {
if (!$request->has('code') || $request->has('denied')) {
return redirect('/'); // redirect url
}
$user = Socialite::driver('facebook')->user();
}
catch (\InvalidArgumentException $e) {
return redirect()->to('/'); // redirect url
}

Related

Laravel 7.0 - tymon/jwt-auth - check if token is valid

Trying to achieve a login endpoint at a laravel installation by using tymon/jwt-auth (JWT). The login, logout, get userdata is working fine. I would like to have a endpoint for checking the Bearer Token. There is a short way to achieve this via:
Route::get('/valid', function () {
return 1;
})->middleware('auth:api');
If the token is valid, the the HTTP return code == 200 but if not, a 401 code is returned. Since the endpoint is checking a token and not the authenticated communication, I would like to rather have a controller returning true/false regarding valid token with 200 - OK.
I had a look "under the hood" of the modules and that is how far I get (not working):
$tokenKey = $request->bearerToken();
$jws = \Namshi\JOSE\JWS::load($tokenKey);
$jwsSimple = new SimpleJWS($jws->getHeader());
$jwsSimple::load($tokenKey);
$jwsSimple->setPayload($jws->getPayload());
$jwsSimple->setEncodedSignature(explode('.', $tokenKey)[2]);
$tmpVal = $jwsSimple->isValid($tokenKey);
Is there any better approach to achieve this? I assume that there should be a Service Provider for that but could not figure out how to implement this. Thank you in advance.
You could remove the auth:api middleware and then have something like:
return response()->json([ 'valid' => auth()->check() ]);
Maybe this method need you:
public function getAuthenticatedUser()
{
try {
if (! $user = JWTAuth::parseToken()->authenticate()) {
return response()->json(['user_not_found'], 404);
}
} catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
return response()->json(['token_expired'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
return response()->json(['token_invalid'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\JWTException $e) {
return response()->json(['token_absent'], $e->getStatusCode());
}
return response()->json(compact('user'));
}
Here is the mixed output to achieve status based token validation with laravel and tymon/jwt-auth:
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class ValidTokenController extends Controller
{
public function __invoke(Request $request)
{
$response = (int) auth('api')->check();
$responseCode = 200;
try {
if (!app(\Tymon\JWTAuth\JWTAuth::class)->parseToken()->authenticate()) {
$response = 0;
}
} catch (\Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
$response = -1;
} catch (\Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
$response = -2;
} catch (\Tymon\JWTAuth\Exceptions\JWTException $e) {
$response = -3;
}
return response()->json($response, $responseCode);
}
}
// Validate Token Controller:
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class ValidTokenController extends Controller
{
public function __invoke(Request $request)
{
$response = auth('api')->check();
$responseCode = 200;
if(!$response) {
try {
if (!app(\Tymon\JWTAuth\JWTAuth::class)->parseToken()->authenticate()) {
$response = 0;
}
} catch (\Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
$response = -1;
} catch (\Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
$response = -2;
} catch (\Tymon\JWTAuth\Exceptions\JWTException $e) {
$response = -3;
}
} else {
$response = (int) $response;
}
return response()->json($response, $responseCode);
}
}

How to verifiy JWT on a single route in Laravel

I have a single route in Laravel on which I need to verify the JWT on header if it is authorized and not expired. How can I do that?
In Javascript its really easy, but don`t know how in Laravel.
Here's the code:
public function update(Request $request){
$header = $request->header('Authorization');
$token = $request->bearerToken();
$secret = env('EXAMPLE_SECRETE');
$verified = here i want to verify the jtw /$token
if (!verified)
return 'something here'
else
>>code here after verified
}
First of install below package
composer require firebase/php-jwt
And then you can create a middleware in order to verify Token or expired, below is a complete code of middlware
namespace App\Http\Middleware;
use Closure;
use Exception;
use App\User;
use Firebase\JWT\JWT;
use Firebase\JWT\ExpiredException;
class JwtTokenMiddleware
{
public function handle($request, Closure $next, $guard = null)
{
$token = $request->bearerToken();
if (!$token) {
// Unauthorized response if token not there\
}
try {
$credentials = JWT::decode($token, env('JWT_SECRET'), ['HS256']);
//You can get credentials that you have set up while generating token
$user = User::findOrFail($credentials->sub)->setAuthUser();
$request->auth = $user;
} catch (ExpiredException $e) {
// Token expired response
} catch (Exception $e) {
// Handle unknow error while decoding token
return response()->json([
}
return $next($request);
}
}

Laravel fails to redirect when specifying URL

I want Laravel to redirect to '/dashboard' instead, Laravel keeps taking me to '/' after login.
LoginController.php
public function redirectPath()
{
return '/dasboard';
}
Middleware
if (Auth::guard($guard)->check())
{
return redirect()->intended('/dashboard');
}
protected function authenticated()
{
return redirect('/home');
}

i cant use method store in laravel framework

i am learning to myself laravel framework, and now i am trying to save data in a table, However it does but it gives me the error
Fatal error-Use of undefined constant users - assumed 'users'
Sending the form:
<form method="post" action="{{route('users.store')}}">
and in the method store:
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use App\Http\Requests;
use Exception;
class UserController extends Controller
{
public function index()
{
$data=User::all();
return view ('index',compact('data'));
}
public function create()
{
return view('create');
}
public function store(Request $request)
{
try{
$user=new User();
$user->name=$request->name;
$user->email=$request->email;
$user->password= bcrypt($request->password);
$user->save();
return redirect()->route(users.index);
} catch (Exception $e) {
return "Fatal error-" .$e->getMessage();
}
}
This is incorrect, you're missing the quotes:
return redirect()->route(users.index);
change to
return redirect()->route('users.index');

How do i make a page unaccessible when a session is set with middleware laravel 5.4

I'm trying to make a page unaccessible when a session is set in laravel
The middleware i tried is App\Http\Middleware\TwoStep.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class TwoStep
{
public function handle($request, Closure $next)
{
if (Auth::user()) {
if (session('validate') === 'true') {
back();
} else {
return redirect('/auth');
}
} else {
return redirect('/login');
}
}
}
the way i tried to use the middleware :
Route::get('/auth', 'AuthController#index')->middleware('twostep');
This gave me a redirect loop though.
Unless back() is a helper you have created, it should be:
return redirect()->back();

Resources