Getting a Forbidden when trying to access my controller - laravel

I've created a form that when submitted it needs to go to a controller function.
At the moment when I'm submitting my form I keep getting
Forbidden
You don't have permission to access /client_area/shop/payment-gateway on this server.
Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.
I've done forms before but this is the first time this has happened to me and it has me stumped.
my form
<div class="payment-form">
<form action="{{ route('payment.gateway') }}" method="POST">
#csrf
<input type="hidden" name="return_url" value="{{ route('payment.success') }}">
<input type="hidden" name="cancel_url" value="{{ route('payment.cancel') }}">
<input type="hidden" name="m_payment_id" value="{{ $invoice_number }}">
<input type="hidden" name="amount" class="completePrice" value="">
<input type="hidden" name="item_name" value="Test Item">
<input type="hidden" name="item_description" value="A test product">
<input type="hidden" name="delivery_collection" class="delivery_collection" value="">
<input type="hidden" name="delivery_fee" class="delivery_fee" value="{{ $delivery }}">
<input type="hidden" name="delivery_address" class="delivery_address" value="{{ $address }}">
<button type="submit" class="btn btn-success float-right confirm-order">
Confirm Order
</button>
</form>
</div>
my routes
Route::group(['middleware' => ['web', 'auth']], function(){
Route::get('/account/dashboard', 'UsersController#accountDashboard')->name('account.dashboard');
Route::get('/account/details', 'UsersController#personalDetails')->name('account.details');
Route::get('/account/track-orders', 'UsersController#trackOrders')->name('account.track-orders');
Route::get('/account/invoices', 'UsersController#invoices')->name('account.invoices');
Route::get('/account/address', 'UsersController#addressesIndex')->name('account.addresses.index');
Route::get('/account/sort-orders', 'UsersController#sortOrders')->name('account.sort-orders');
Route::get('/account/order-details/{invoice_number}', 'UsersController#orderDetails')->name('account.order-details');
Route::get('/account/invoice-pdf/{id}', 'UsersController#invoicesPdf')->name('account.invoices.pdf');
Route::get('/account/create-address', 'UsersController#createAddress')->name('account.create.address');
Route::get('/account/edit-address/{id}', 'UsersController#editAddress')->name('account.edit.address');
Route::get('/delivery-confirmation', 'PublicController#deliveryConfirmation')->name('cart.deliveryConfirmation');
Route::get('/account/edit-delivery-address/{id}', 'UsersController#editDeliveryAddress')->name('account.edit.delivery.address');
Route::get('/payment-success', 'PublicController#successPayment')->name('payment.success');
Route::get('/payment-cancel', 'PublicController#cancelPayment')->name('payment.cancel');
Route::post('/account/personal-details', 'UsersController#postPersonalDetails')->name('post.personal-details');
Route::post('/account/business-details', 'UsersController#postBusinessDetails')->name('post.business-details');
Route::post('/account/addresses-radio/{id}', 'UsersController#postAddressesRadio')->name('account.post.addresses.radio');
Route::post('/account/create-address', 'UsersController#postAddress')->name('account.post.address');
Route::post('/account/edit-address/{id}', 'UsersController#updateAddress')->name('account.update.address');
Route::post('/payment-gateway', 'PublicController#paymentGateway')->name('payment.gateway');
Route::delete('/account/delete-delivery-address/{id}', 'UsersController#deleteDeliveryAddress')->name('account.delete.delivery.address');
});
I've only done a dd() to make sure I hit the right function
public function paymentGateway()
{
dd('this is a payment gateway');
}
My Auth Middleware
<?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* #param \Illuminate\Http\Request $request
* #return string
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
}
This is what I see when I go through the network tab. Because it's alot of images I thought it would be better to have it as a link then just pasting the images here.
Image 1
Image 2
Image 3
Image 4
Image 5
Image 6
Image 7
Image 8

Laravel comes with Cross Site Request Forgery protection. You need to also pass a field named csrf-token as stated here in the documentation.
https://laravel.com/docs/5.8/csrf#csrf-x-csrf-token
If you do not want this protection you must include the route in the VerifyCsrfToken Middleware to exclude the checking.
https://laravel.com/docs/5.8/csrf#csrf-excluding-uris
Try this to see if that solves your issue.

Related

Laravel - CSRF Token Mismatch - Header Token gets regenerated

I'm struggeling the last 2 weeks on the following problem:
First of all my problem only occours when I try to deploy my current Laravel (6.11) project on the live server. On my Localhost everything works fine.
In every FORM I used the #csrf tag to set the token as well as the meta tag in the head section of my page. If I search into the developer tool in Chrome the tokens in head and form match perfectly. When the POST request gets sent I get an 419 Page Expired error. I figured out that the HEAD token gets recreated on each request so a token mismatch occours.
I already tried the following things:
Diffrent syntax of the csrf tag
I excepted all FORMS in the VerifyCsrfToken.php - these ended up in a redirect to my index.php without submited form
I checked all Laravel config settings which were recommended in diffrent Forum Posts
I tried a empty laravel installation with a basic login setup on my server - This worked
I currently work with git. On the a previous commit version (16th of december) which I uploaded to my server on that exact Date I had no problem at all but when I tried to reupload the exact same git commit date, the same problem happens.
Greatings Max
If you need any code I'll upload here.
Controller:
function fakeAuthentifizierung(Request $request){
$username = $request->input('benutzernameLogin');
$password = $request->input('passwortLogin');
session(['key' => 'mt171043']);
session(['eingeloggt' => true]);
/*****
* ABFRAGE ADMINRECHTE
* BITTE DIESEN TEIL SPÄTER IN ECHTE AUTHENTIFIZIERUNG ÜBERNEHMEN
*
*/
$admin = false;
// SPÄTER BENUTZERID AUS LOGIN SESSION ÜBERGEBEN
// astmedin5 als TESTZWECK
$rechte = Benutzer::getBenutzerBerechtigung("astmedin5");
//Berechtigung Abfragen
if($rechte->name != 'Student' && 'Lehrbeauftragter'){
session(['admin' => true]);
}else{
session(['admin' => false]);
}
/***
*
* ABFRAGE ENDE
*/
return redirect(route('index',app()->getlocale()));
}
View:
<form method="POST" action="{{ action('LoginController#FakeAuthentifizierung', app()->getLocale()) }}">
#csrf
<h1>{{ __('Login') }}</h1>
<label class="col" for="benutzernameLogin">{{ __('Benutzername') }}</label>
<input name="benutzernameLogin" id="benutzernameLogin" class="inputLogin col mb-4" type="text"
aria-label="Text input with checkbox" placeholder="{{ __('Benutzername') }}" required>
<label class="col" for="passwortLogin">{{ __('Passwort') }}</label>
<input name="passwortLogin" id="passwortLogin" class="inputLogin col mb-4" type="password"
aria-label="Text input with checkbox" placeholder="{{ __('Passwort') }}" required>
<div class="col-8 float-left">
<input id="checkboxPasswortAnzeigen" type="checkbox">
<label for="checkboxPasswortAnzeigen">{{ __('Passwort anzeigen') }}</label>
</div>
<button type="submit" class="btn-slash col-3 inverted fontLight float-right">{{ __('Login') }}</button>
</form>

Laravel Get Method Not Supported Exception (While the form method is already POST)

I am working on a Laravel project in which I have a form to write styled text, inside the form I used WYSIWYG editor, and the method of the form is POST. Sometimes when I submit the form it gives me (The GET method is not supported for this route. Supported methods: POST). This usually occurs when I give some styling to my text e.g. adding background color or inserting Arabic Characters. but when I insert plain text English words It works as expected and every things ok.
I added the header("Content-Type: text/html;charset=UTF-8"); at the top of index.php file but the result was not changed
Note: the application works in my local xampp server, but when I upload online I get the problem.
Here is form.blade.php (view)
<form method="POST" action="{{action('MainController#Insert')}}" accept-charset="utf-8">
{{csrf_field()}}
#method('post')
<input type="text" name="title" class="form-control" placeholder="Title"/>
<textarea name="details" id="myeditor"></textarea>
<input type="submit" value="Save"/>
</form>
<script>
CKEDITOR.replace('myeditor');
</script>
Here is my web.php (Routes)
Route::get('/', function () { return view('welcome'); });
Route::get('/form','MainController#LoadForm');
Route::post('/save','MainController#Insert');
And the is my controller
public function LoadForm(Request $req){
return view('form');
}
public function Insert(Request $req){
DB::table('notes')->insert(["title"=>$req->title,"details"=>$req->details]);
return redirect()->back()->with(["message"=>"Note Saved Successfully!"]);
}
Where is the problem?
to simplify it
<form method="POST" action="/save" accept-charset="utf-8">
{{csrf_field()}}
<input type="text" name="title" class="form-control" placeholder="Title"/>
<textarea name="details" id="myeditor"></textarea>
<input type="submit" value="Save"/>
</form>

Laravel custom login is failing for the first time with "route [login] not defined" error. Working fine in second attempt

I'm setting up my custom authentication system in my Laravel app. I've deleted all the default auth controllers and not using make::auth. And my auth is working properly. My main problem is that when I tried to log in for the first time, it's failing with "Route [login] not defined" error, but in second attempt, it's working properly. And if I repeat the process, it's continuing again and again like the first two attempt. Actually, I've never used login route anywhere.
Here is my form:
<form action="{{ url('/log-in') }}" method="POST">
#csrf
<input type="text" name="phone" placeholder="Telefon" class="form-control input-phone">
<input type="password" name="password" placeholder="Parol" class="form-control">
<button type="submit" class="btn">Kirish</button>
</form>
Here is my route:
Route::post('/log-in', 'AuthController#login');
Here is my controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use App\User;
class AuthController extends Controller
{
public function login(Request $request) {
// Get current user.
$user = User::where('phone', $request->phone)
->first();
if ( Hash::check($request->password, $user['password']) ) {
Auth::login($user, true);
Auth::logoutOtherDevices($request->password);
return redirect()->back();
}
}
}
Use for route.
Route::post('/log-in', 'AuthController#login')->name('login');
Use your form.
<form action="{{ route('login') }}" method="POST">
#csrf
<input type="text" name="phone" placeholder="Telefon" class="form-control input-phone">
<input type="password" name="password" placeholder="Parol" class="form-control">
<button type="submit" class="btn">Kirish</button>
</form>
This is a tricky and annoying problem. you need to change your return from return redirect()->back(); to loading 1 known blade or a known redirect. Sometimes at login your route fails to set a back redirect. so you can try to set a return view() or a return to a known url. So for example if the login is success return to index , if not load error page.
Hope this helps

Confusion regarding action in the form

I am fairly new to Laravel and I am trying CRUD operations using Resource Controller. The problem I am facing is regarding what should be the action in create a task form. Let me give you an overview, how the application is designed. I have created separate directories for MVC as listed below:
Todo_Model\todo_model.php
Todo_Controller\todo_controller.php
Todo_View\home.blade.php
Todo_View\create.blade.php
Route: Route::resource('todo','Todo_Controller\todo_controller');
route:list
Controller:
public function index()
{
return view('Todo_View\home');
}
public function create()
{
return view('Todo_View\create');
}
public function store(Request $request)
{
$todo= new todo_model();
$todo->title=$request->title;
$todo->body=$request->body;
$todo->save();
return redirect('todo');
}
create.blade.php
<form method="POST" action="../todo">
{{csrf_field()}}
<tr><td><input type="text" name="title" value="" placeholder="Title"></td></tr>
<tr><td><input type="text" name="body" value="" placeholder="Body"></td></tr>
<tr><td><input type="submit" name="submit" value="Submit"></td></tr>
</form>
Now the problem is that the action of the form should be todo as can be seen in the route:list but when I hit submit with that I get MethodNotAllowedHttpException and the URL shown is http://localhost/laravel-7/blog/public/todo/todo. But during the hit and trial I figured out I should use form action as ../todo. I am highly confused as to why do I have to use that action as it doesn't make any sense because in the route list, URI is clearly mentioned as todo
Another point, when I hit index page, URI is http://localhost/laravel-7/blog/public/todo and when I get redirected from home page to create page, the URI is http://localhost/laravel-7/blog/public/todo/create
You are confusing action with native php in laravel.
Replace your action="../todo" with action="{{url('todo')}}"
<form method="POST" action="{{url('todo')}}">
{{csrf_field()}}
<tr><td><input type="text" name="title" value="" placeholder="Title"></td></tr>
<tr><td><input type="text" name="body" value="" placeholder="Body"></td></tr>
<tr><td><input type="submit" name="submit" value="Submit"></td></tr>
</form>
You just need to specify the route exactly no need for saying where the file is actually located so action="/todo" would work fine

Laravel - Upload to Existing Model Record

Maybe it's because I'm tired, but I can't seem to get a simple upload working for one of my models.
On the show details page of my customers (who are NOT users) model, I have a simple form where a user can upload the logo of the customer.
The form:
<form enctype="multipart/form-data" action="/customers/i/{{$customer->url_string}}" method="POST">
<input type="file" name="logoUpload">
<input type="hidden" name="_token" value="{{csrf_token()}}">
<input type="submit" class="pull-right btn btn-sm btn-primary" value="Upload">
</form>
The Controller:
public function logoUpload(Request $request){
if($request->hasFile('logoUpload')){
$path = Storage::putFile('public/customer/uploads', new File(request('logoUpload')));
$customer->car_logo = $path;
$customer->save();
return back();
}
}
I know the issue is that I haven't defined $customer in the controller since the file does actually store itself in the correct folder after I click submit, but it does not hit the database at all.
Update
The current customer details url:
http://localhost:8000/customers/i/dsdado9a98w78721
The web definition for the post route:
Route::post('/customers/i/{customer}', 'CustomerController#logoUpload');
You have to create a hidden field in your form that contains the customer id and then use it in your controller to update it with the new file path, here is an example:
View
<form enctype="multipart/form-data" action="/customers/i/{{$customer->url_string}}" method="POST">
<input type="file" name="logoUpload">
<input type="hidden" name="_token" value="{{csrf_token()}}">
<!-- customer_id field -->
<input type="hidden" name="customer_id" value="{{$customer->id}}">
<input type="submit" class="pull-right btn btn-sm btn-primary" value="Upload">
</form>
Controller
public function logoUpload(Request $request){
if($request->hasFile('logoUpload')){
$path = Storage::putFile('public/customer/uploads', new File(request('logoUpload')));
// get customer
$customer = Customer::find($request->customer_id);
$customer->car_logo = $path;
$customer->save();
return back();
}
}
You have some options, here is a simple one, with only adjusting that controller method:
public function logoUpload(Request $request, $customer)
{
$customer = Customer::where('url_string', $customer)->firstOrFail();
if($request->hasFile('logoUpload')){
$path = Storage::putFile('public/customer/uploads', new File(request('logoUpload')));
$customer->car_logo = $path;
$customer->save();
return back();
}
...
}
We have added a parameter to the method signature to accept the route parameter. We then find the model via url_string matching that parameter.
You also could setup route model binding as well to do the resolving of that model based on the route parameter for you.

Resources