Catching org_internal 403 error via Google's OAUTH? - laravel

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}");
}

Related

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"]);
}
}

Previous session can not destroy in laravel 5.7

I am creating login page & after logout my session value can not destroy. Any problem with code? I am using flush method,forget method to remove previous session value.
public function userLogin(Request $req)
{
$username=$req->input('username');
$password=$req->input('password');
$finduser = Users::where(['email'=>$username,'password'=>$password])
->orwhere(['mobile'=>$username,'password'=>$password])
->first();
Session::put('username', $finduser->name);
Session::put('userid', $finduser->id);
$session_id=Session::get('session_id');
if($username != $finduser->mobile and $username != $finduser->email)
{
Session::put('message','Email or mobile number does not exists');
return redirect::to('/login');
}
else if($password != $finduser->password)
{
Session::put('message','Your Password is incorrect');
return redirect::to('/login');
}
else if($finduser)
{
return redirect::to('/home');
}
}
public function logout(Request $req)
{
Session()->forget(['userid', 'username','session_id']);
Session()->flush();
//Session::flush();
return redirect('/login');
}
Try \Session()->flush(); instead of Session()->flush();

Laravel/Vue refreshing JWT token - The token has been blacklisted exception

I am using tymon jwt auth package in laravel for token authentication and I am trying to refresh a JWT token if it is expired, I have set up a middleware AuthenticateToken, that looks like this:
class AuthenticateToken
{
public function handle($request, Closure $next)
{
try
{
if (! $user = JWTAuth::parseToken()->authenticate() )
{
return response()->json([
'code' => 401,
'response' => null
]);
}
}
catch (TokenExpiredException $e)
{
// If the token is expired, then it will be refreshed and added to the headers
try
{
$refreshed = JWTAuth::refresh(JWTAuth::getToken());
$user = JWTAuth::setToken($refreshed)->toUser();
header('Authorization: Bearer ' . $refreshed);
}
catch (JWTException $e)
{
return response()->json([
'code' => 403,
'response' => null
]);
}
}
catch (JWTException $e)
{
return response()->json([
'code' => 401,
'response' => null
]);
}
// Login the user instance for global usage
Auth::login($user, false);
return $next($request);
}
}
And I am using that middleware on my routes:
Route::group(['prefix' => 'intranet', 'middleware' => ['token']], function () {
Route::get('intranet-post', 'Api\IntranetController#index');
});
And in Vue I have set up the axios and refreshing of the token like this:
// Apply refresh(ing) token
BACKEND.defaults.transformResponse.push((data, headers) => {
if (headers.authorization && store('token', headers.authorization)) {
BACKEND.defaults.headers.common.authorization = headers.authorization;
}
return data;
});
BACKEND.defaults.transformRequest.push((data, headers) => {
headers.authorization = `Bearer ${load('token')}`;
});
Vue.prototype.$http = axios;
Vue.prototype.$backend = BACKEND;
function store(key, value) {
try {
let oldLength = localStorage.length;
localStorage.setItem(key, value);
return !(localStorage.length > oldLength); // Returns true on write error
}
catch (err) {
return true;
}
}
function load(key) {
try {
return localStorage.getItem(key);
}
catch (err) {
return null;
}
}
But, on expiration of the token I still get 403 response. If I do dd($e) in middleware here:
catch (TokenExpiredException $e)
{
// If the token is expired, then it will be refreshed and added to the headers
try
{
$refreshed = JWTAuth::refresh(JWTAuth::getToken());
$user = JWTAuth::setToken($refreshed)->toUser();
header('Authorization: Bearer ' . $refreshed);
}
catch (JWTException $e)
{
dd($e);
return response()->json([
'code' => 103,
'response' => null
]);
}
}
I get:
The token has been blacklisted exception
How can I fix this?
Try my middleware:
<?php
namespace App\Http\Middleware;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Tymon\JWTAuth\Exceptions\JWTException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
class RefreshToken extends BaseMiddleware {
public function handle($request, \Closure $next) {
$this->checkForToken($request); // Check presence of a token.
try {
if (!$this->auth->parseToken()->authenticate()) { // Check user not found. Check token has expired.
throw new UnauthorizedHttpException('jwt-auth', 'User not found');
}
$payload = $this->auth->manager()->getPayloadFactory()->buildClaimsCollection()->toPlainArray();
return $next($request); // Token is valid. User logged. Response without any token.
} catch (TokenExpiredException $t) { // Token expired. User not logged.
$payload = $this->auth->manager()->getPayloadFactory()->buildClaimsCollection()->toPlainArray();
$key = 'block_refresh_token_for_user_' . $payload['sub'];
$cachedBefore = (int) Cache::has($key);
if ($cachedBefore) { // If a token alredy was refreshed and sent to the client in the last JWT_BLACKLIST_GRACE_PERIOD seconds.
\Auth::onceUsingId($payload['sub']); // Log the user using id.
return $next($request); // Token expired. Response without any token because in grace period.
}
try {
$newtoken = $this->auth->refresh(); // Get new token.
$gracePeriod = $this->auth->manager()->getBlacklist()->getGracePeriod();
$expiresAt = Carbon::now()->addSeconds($gracePeriod);
Cache::put($key, $newtoken, $expiresAt);
} catch (JWTException $e) {
throw new UnauthorizedHttpException('jwt-auth', $e->getMessage(), $e, $e->getCode());
}
}
$response = $next($request); // Token refreshed and continue.
return $this->setAuthenticationHeader($response, $newtoken); // Response with new token on header Authorization.
}
}
For more details see this post.
You can edit your config/jwt.php about line 224.
<?php
.......
'blacklist_enabled' => env('JWT_BLACKLIST_ENABLED', false),

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('/');
}
}
});

laravel auth and session not persisting

The laravel session and auth I use have some problem in server, but working really fine in localhost . I will show.
Route
Route::get('/signin', 'PageController#signin');
Route::get('/signup', 'PageController#signup');
Route::get('/terms', 'PageController#terms');
Route::resource('/', 'PageController');
Route::controller('user', 'UserController');
PageController
public function index() {
if (Auth::check()) {
return View::make('user.index');
} else {
return View::make('landing');
}
}
UserController
public function postLogin() {
$data = array();
$secured = ['user_email' => $_POST['email'], 'password' => $_POST['password']];
if (Auth::attempt($secured, isset($_POST['remember']))) {
if (Auth::user()->user_status == 1 ) {
return Redirect::to('/');
} else {
$data['success'] = false;
}
} else {
$data['success'] = false;
}
return $data;
}
Auth::check() fails in pagecontoller even after login succeds. But if I change the code to
UserController
public function postLogin() {
$data = array();
$secured = ['user_email' => $_POST['email'], 'password' => $_POST['password']];
if (Auth::attempt($secured, isset($_POST['remember']))) {
if (Auth::user()->user_status == 1 ) {
return Return View::make(user.index);
} else {
$data['success'] = false;
}
} else {
$data['success'] = false;
}
return $data;
}
I get the index page and if I click the link of the home I get the landing page not the index page.
I guess I clarify my problem, I have gone through may solution replied earlier in same manner question nothing working.
I don't think its the server problem because another laravel application is working fine in same server.
Please help.
Your query seems to be incomplete, from what i understand you are able to get the index page after passing the authentication check only once, and that is by using this method:
public function postLogin() {
$data = array();
$secured = ['user_email' => $_POST['email'], 'password' => $_POST['password']];
if (Auth::attempt($secured, isset($_POST['remember']))) {
if (Auth::user()->user_status == 1 ) {
return Return View::make(user.index);
}
else {
$data['success'] = false;
}
}
else {
$data['success'] = false;
}
return $data;
}
try using a different browser to make sure there is no cookie storage restrictions in the client side and check the app/config/session.php file and see if you have configured the HTTPS Only Cookies according to your needs.
and just on an additional note this line "return Return View::make(user.index);" looks vague.

Resources