Laravel 8, trying to check if user has been verified during login returns an error - laravel

I am using laravel 8 in combination with vue and I am trying show an message when a user that tries to login before this user has verified his/her emailaddress.
// loginController.php
if (Auth::attempt($credentials)) {
if (Auth::client()->verified != 1) {
//good
}else{
// bad, message users needs to verify email first
}
}else{
//login not correct try again
}
Now I am getting this error
Access to XMLHttpRequest at 'http://localhost:8000/home' (redirected from 'http://localhost:8000/api/login') from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Related

Axios get request with web.php in laravel 8

I am new to Axios and API. I was trying to get data from a table with laravel 8 and React js and it works fine with
const res = await axios.get('http://127.0.0.1:8081/api/students');
When I try to do the same with
const res = await axios.get('http://127.0.0.1:8081/web/students');
with web.php access, it shows the error in the console
Access to XMLHttpRequest at 'http://127.0.0.1:8081/web/students' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. GET http://127.0.0.1:8081/web/students net::ERR_FAILED 404.
Thanks.
As specified in boot() method in app/Providers/RouteServiceProvider.php, web routes have no prefix.
https://github.com/laravel/laravel/blob/8.x/app/Providers/RouteServiceProvider.php
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
So your endpoint should be http://127.0.0.1:8081/students instead of http://127.0.0.1:8081/web/students

Laravel - Vue Axios CORS policy

The request
axios.get("https://maps.googleapis.com/maps/api/geocode/json?latlng="+this.currentLocation.lat+","+this.currentLocation.lng+"&key="+this.apiKey).then((response) => {
if (this.town === response.data.results[0].address_components[2].long_name){
return
}
else{
this.town = response.data.results[0].address_components[2].long_name
this.getSuggested();
this.getAllEvents();
}
}).catch(er => {
console.log(er)
})
When i'm trying to get the town of a location i get this error
Access to XMLHttpRequest at 'API Route' from origin 'http://localhost:8000' has been blocked by CORS policy: Request header field x-requested-with is not allowed by Access-Control-Allow-Headers in preflight response.
When i remove
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
from bootstrap.js, the request works just fine.
What exactly is the problem here?
Any server you’re sending a request to will, usually by default, reject it if it contains headers which are not CORS-safelisted.
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
This code tells axios to attach a custom header to every request. Ergo, your request is being sent with a non safelisted header, which the server won’t permit, so you receive the error.
To permit the request, the server must be configured to allow the custom header.

Laravel - How to catch "HttpExceptions", because of POST request when CSFR is wrong?

So the User logs out on one tab and on the other tab he is "visually" still logged in.
Now, for example, the user sends a Chat message via POST route, but the server responds with:
Request Method: POST
Status Code: 419
exception: "Symfony\Component\HttpKernel\Exception\HttpException"
The reason is that the CSFR Value is false, because the User is logged out.
My wish is to have the same response like in GET Request Methods.
There I get:
Request Method: GET
Status Code: 401
message: "Unauthenticated."
Because the User is not authenticated anymore. (Middleware is set to 'auth')
Why do I need this?
I want to catch failures with axios and check if the user is unauthenticated. If so the page is reloaded.
But right now I don't know if the user is unauthenticated or if he tries to exploit my page, but has a wrong csrf token.
Current solution in Handler.php
if ($exception instanceof TokenMismatchException){
return $request->expectsJson()
? response()->json(['message' => 'Invalid CSRF.'], 400)
: abort(400);
}

Laravel socialite 400 Bad Request response

i have created a laravel socialte setup .and it was working before perfectly now its showing error(below).
1)i have changed client_secret
2)created a new oauth credentials
still not working
public function redirectToGoogle()
{
return Socialite::driver('google')->redirect();
}
public function handleGoogleCallback()
{
$user = Socialite::driver('google')->stateless()->user();
$user->getId(); // 1472352
$user->getNickname(); // "overtrue"
$name= $user->getName(); // "安正超"
$emailid= $user->getEmail();
$pic= $user->getAvatar(); // "anzhengchao#gmail.com"
return->redirect('welcome');
}
i have created env file with client_secret and client id
"""
Client error: `POST https://accounts.google.com/o/oauth2/token` resulted in a `400 Bad Request` response:\n
{\n
"error" : "invalid_grant",\n
"error_description" : "Code was already redeemed."\n
}\n
"""
When Google return the Authentication Code code to your Socialite, it can only be used to exchange to Access Token once. Doing more than once will result in the error Code was already redeemed.
The flow should be:
User click the login button on your website
You redirect user to Google and Google is asking user to login/grant you access
If successful, Google redirects back to you with a one-time-use Authentication Code?code=.....
Socialite use the ?code and exchange it with Google to get user's Access Token. This can only be done once per flow.
You can now request user details using the access token requested in step 4.
Read similar answer: https://stackoverflow.com/a/32710034/534862

No 'Access-Control-Allow-Origin' header is present on the requested resource - Mollie payment ajax

I'm trying to create a mollie payment with the following 2 libraries:
https://github.com/barryvdh/laravel-omnipay
https://github.com/thephpleague/omnipay-mollie
When the client fills in the form and submits an ajax request will be made to a function in my laravel application.
In my Laravel function I'm trying to do the following:
$gateway = Omnipay\Omnipay::create('Mollie');
$gateway->setApiKey('test_gSDS4xNA96AfNmmdwB3fAA47zS84KN');
$params = [
'amount' => $ticket_order['order_total'] + $ticket_order['organiser_booking_fee'],
'description' => 'Kapelhoek wijkfeesten',
'returnUrl' => URL::action('EventCheckoutController#fallback'),
];
$response = $gateway->purchase($params)->send();
if ($response->isSuccessful()) {
// payment was successful: update database
print_r($response); die;
} elseif ($response->isRedirect()) {
// redirect to offsite payment gateway
return $response->getRedirectResponse(); die;
} else {
// payment failed: display message to customer
echo $response->getMessage(); die;
}
But I'm getting this response:
XMLHttpRequest cannot load https://www.mollie.com/payscreen/select-method/PRMtm6qnWG. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://kapelhoektickets.dev' is therefore not allowed access.
How can I fix this?
The line return $response->getRedirectResponse() is doing a redirect to the payment URL where the consumer should be sent to. However, this redirect is not allowed in an AJAX call.
Instead, your script should print this payment URL with $response->getRedirectUrl() and your webpage should redirect the consumer with javascript.
I think issue is with Api Dashboard. You have to whitelist your domain before making POST request
If you are requesting your API from a different domain, you have to implement CORS - I prefer this package https://github.com/barryvdh/laravel-cors.

Resources