laravel8 Undefined variable: errors - laravel

I am working on a Laravel Api with Vue js Front end. I have a problem on verify email and reset password. I am sending email using sendGrid In email of reset password button its redirects me to /api/password/reset and this route showing me exception of Undefined variable: errors (View: Path to/ reset.blade.php same is the case with verify email its redirect route is api/email/verify/ which is showing error exception in Undefined variable: errors (View: Path to/login.blade.php.
api.php
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::get('users/send-email', 'App\Http\Controllers\Api\UsersController#sendEMails');
Route::post('client/search', 'App\Http\Controllers\Api\ClientsController#searchBy');
Auth::routes(['verify' => true]);
Route::apiResource('user', 'App\Http\Controllers\Api\UsersController');
Route::apiResource('freelancer', 'App\Http\Controllers\Api\FreelancersController');
Route::apiResource('client', 'App\Http\Controllers\Api\ClientsController');
Route::apiResource('service', 'App\Http\Controllers\Api\ServicesController');
Route::post('service/{id}', 'App\Http\Controllers\Api\ServicesController#update');
Route::post('client/{id}', 'App\Http\Controllers\Api\ClientsController#update');
Route::post('freelancer/{id}', 'App\Http\Controllers\Api\FreelancersController#update');
Route::apiResource('contact_us', 'App\Http\Controllers\Api\ContactUsController');
Route::post('clients/client-referal', 'App\Http\Controllers\Api\ClientsController#findReferal');
Route::post('freelancers/search', 'App\Http\Controllers\Api\FreelancersController#searchBy');
Route::post('services/search', 'App\Http\Controllers\Api\ServicesController#searchBy');
// getting admin users for admin dashboard
Route::get('users/admins', 'App\Http\Controllers\Api\UsersController#getAdminUsers');
Route::apiResource('sales_methods', 'App\Http\Controllers\Api\SalesMethodsController');
Route::apiResource('industries', 'App\Http\Controllers\Api\IndustriesController');
Route::middleware('auth:sanctum')->group(function () {
Route::apiResource('user_subscribe_client', 'App\Http\Controllers\Api\SubscribedUserClientsController');
Route::apiResource('apply_job', 'App\Http\Controllers\Api\UserAppliedJobController');
Route::get('users/setup-intent', 'App\Http\Controllers\Api\UsersController#getSetupIntent');
Route::post('users/payments', 'App\Http\Controllers\Api\UsersController#postPaymentMethods');
Route::post('clients/payments', 'App\Http\Controllers\Api\ClientsController#showMyPayments');
Route::get('users/payment-methods', 'App\Http\Controllers\Api\UsersController#getPaymentMethods');
Route::post('users/remove-payment', 'App\Http\Controllers\Api\UsersController#removePaymentMethod');
Route::put('users/subscription', 'App\Http\Controllers\Api\UsersController#updateSubscription');
Route::put('users/update-password/{id?}', 'App\Http\Controllers\Api\UsersController#updatePassword');
Route::post('services/status', 'App\Http\Controllers\Api\ServicesController#changeStatus');
});
**Web.php**
<pre>
Route::middleware('auth')->get('/user', function (Request $request) {
return $request->user();
});
Auth::routes(['verify' => true]);
Route::get('/{any?}', function () {
return view('welcome');
})->where('any', '^(?!api\/)[\/\w\.\,-]*');
Vuejs Password reset form action
async resetPassword() {
const post = { email: this.resetEmail };
const response = await axios
.post("/index.php/api/password/email", post).then((){
further logic
}).catch((){
further logic
})

Related

Password Protect a Page after login Laravel

After a user registers and logs in, I have an unlisted page/secret page that I need to protect with another password.
I'm trying to get spatie/laravel-littlegatekeeper to help me do this, but running into issues getting it working.
What I'm doing:
littlegatekeeper .config:
<?php
return [
// Login credentials
'username' => env('GATEKEEPER_USERNAME', 'default_username'),
'password' => env('GATEKEEPER_PASSWORD', 'default_password'),
// The key as which the littlegatekeeper session is stored
'sessionKey' => 'littlegatekeeper.loggedin',
// The route to which the middleware redirects if a user isn't authenticated
// 'authRoute' => url('login'),
];
Routes:
Route::get('/secretapage', ['middleware' => 'littlegatekeeper', function () {
return view('dir.secretapage.index');
}]);
Route::get('/secretapage/login', function () {
return view('dir.secretapage.login');
});
Route::post('/secretapage/login/addCredentials', 'SecretController#addCredentials')->name('addCredentials');
SecretController:
After I log in my user. I then try to access the URL /secretpage I get redirected back to the homepage rather the /secretpage/login
public function index(Request $request)
{
$auth = resolve('littlegatekeeper');
if($auth->isAuthenticated())
{
return view('dir.secretpage.index');
}
return view('dir.secretpage.login');
}
///// FOR LOGING IN
public function addCredentials(Request $request)
{
$auth = resolve('littlegatekeeper');
$loginSuccess = $auth->attempt($request->only([
'username',
'password'
]));
if ($loginSuccess) {
return redirect('/secretapage')->with('success', 'Thank You for authorizing. Please proceed.');
}
else{
return back()->with('error', 'You entered the wrong credentials');
}
}
Blade login file:
<form method="POST" action="{{ route('addCredentials') }}">
...
</form>
If I access secretpage/login 1st, I'm able to add the username and password.
Then I can get into /secretpage with no issues....
But I really need to have the users go to /secretpage 1st then if not logged in with the secret username/pass get redirected to /secretpage/login.
I found some help on Laracasts and this ended up working.
Change the authRoute in the littlegatekeeper config file to the following
'authRoute' => '/secretpage/login',

Signed Route not defined laravel

I am testing Signed route.
im my resources >> views >> web.php i have my route two routes
Route::get('/unsubscribe/{user?}', function ($user='') {
return view('about');
});
Route::get('test', function () {
echo URL::signedRoute('unsubscribe', ['user' => 1]);
});
when i hit http://127.0.0.1:8000/test/ to test my Signed URL i am getting error
Route [unsubscribe] not defined.
Try this: (add name to the route)
Route::get('/unsubscribe/{user?}', function ($user='') {
return view('about');
})->name('unsubscribe');

PUT errors in Vue

I'm trying to update data using laravel. I'm not sure why I can't access the PUT api. I tied so switch the api to store the data vs update and that works. I can't see anything wrong with the code.
Here is the api router
Route::put('product', 'ProductController#update');
here is the controller
public function update(Request $request, $id)
{
$product= Product::findOrFail($id);
$product->update($request->all());
return ['message' => "Success"];
}
Here is the vue.js
methods: {
updateProduct(id){
this.$Progress.start();
this.form.put('api/product/'+this.form.id)
.then(() => {
// success
$('#addNew').modal('hide');
Swal.fire(
'Updated!',
'Information has been updated.',
'success'
)
this.$Progress.finish();
Fire.$emit('AfterCreated');
})
.catch(() => {
this.$Progress.fail();
});
},
In the Vue component I have a modal with a form
<form #submit.prevent ="editmode ? updateProduct() : createProduct()">
The error I'm getting is
405 (Method Not Allowed)
The error I was getting was in the api router.
Route::put('product/{id}', 'ProductController#update');

Voyager Laravel axios get 405

What could be wrong that I get a 405 method not allowed if Im gonna use a POST but if I used GET it gives me 200.
This is my Controller
public function getAnken(Request $request)
{
$from = $request->input('from');
$to = $request->input('to');
echo json_encode($request);
}
This is my Axios in Vuejs
axios.post('/admin/ankens',{
from: '2018/05/28',
to: '2018/05/29'
})
.then(function(response){
console.log(response.data)
});
This is my web.php
Route::group(['prefix' => 'admin'], function () {
Voyager::routes();
Route::get('/ankens', 'AnkensController#getAnken');
});
And I put this in my bootstrap.js too
window.axios = require('axios');
axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
Voyager::routes(); overwrites the below route Route::get('/ankens', to make it read first put it before.
Route::group(['prefix' => 'admin'], function () {
Route::post('/ankens', 'AnkensController#getAnken');
Voyager::routes();
});
Be sure to use URL/admin/slug-name and URL/admin/ankens are identical but different http verb.

CSRF Token Duplication on Vue Router Laravel 5.3 Vue 2 JS

So my problems is that the session token is generated.
and the token that i've sent via AJAX or AXIOS (cause im using vue and vue router for fetching API)
is getting a mismatch
This is the response i got when posting data
The ajax token is equal to the token in the meta tag of the main blade template
using this tag
Meta Tag in app.blade.php
<meta name="csrf-token" content="{{ csrf_token() }}">
<script>
window.Laravel = <?php echo json_encode([
'csrfToken' => csrf_token(),
]); ?>
</script>
Interceptor of Axios (purpose is to inject the csrf_token from the meta Tag)
Vue.axios.interceptors.request.use(function (config) {
config.headers['X-CSRF-TOKEN'] = Laravel.csrfToken;
console.log(config);
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
Response:
array:1 [
"SessionToken" => "JfhmtCaTiQ49BtF2VK3TysvYnEQSE9n5i1uiHegO"
]
array:1 [
"AjaxToken" => "WqKOiaunbvJbxIsnEjetFoCm1mvdUYESRqfXO2lv"
]
VerifyCSRFToken middleware method:
protected function tokensMatch($request)
{
$sessionToken = $request->session()->token();
$token = $request->input('_token') ?: $request->header('X-CSRF-TOKEN');
dd(['SessionToken' => $sessionToken],['AjaxToken' => $token]);
if (! $token && $header = $request->header('X-XSRF-TOKEN')) {
$token = $this->encrypter->decrypt($header);
}
if (! is_string($sessionToken) || ! is_string($token)) {
return false;
}
return hash_equals($sessionToken, $token);
}
So i came up with this idea but its not working because its the token that im getting from the api is null or empty
Here is the method from my RegisterComponent.vue
submitForm() {
this.axios.get('/token')
.then(response => {
this._token = response.data
this.axios.post('/register',this.data)
.then(responseNew => {
console.log(responseNew.data);
})
.catch(responseNew => {
this.errors = responseNew.data;
})
});
}
as you can see im getting a token from my api.php in routes folder
and im also using the authentication api of Laravel and put it on the api routes too
Here is the api.php
Route::group(['middleware' => 'web'], function() {
Auth::routes();
});
Route::get('/token',function() {
dd(csrf_field());
});
Route::get('/user', function (Request $request) {
return $request->user();
})->middleware('auth:api');
Route::resource('/users','UserController');
Route::group(['middleware' => 'auth'], function () {
Route::resource('/stores','StoreController');
Route::resource('/items','ItemController');
Route::resource('/transactions','StoreController');
Route::resource('/managers','ManagerController');
Route::resource('/employees','EmployeeController');
Route::resource('/customers','CustomerController');
Route::resource('/tags','TagController');
});
So how can i prevent it from generating that token that will cause mismatch?
Anyone answering this will surely help the authentication of my SPA ( Single Page App)
and its also giving me response status 302
You seem to have a bit misunderstanding. You have the csrf token configured for axios, so every request will have a header field containing the token, then you just need to make sure every request goes through laravel's csrf token validation function before it reaches your business logic, that's all you need to do to prevent csrf. The get('/token') before post('/register') seems unnecessary.
Also, talking about the /token route itself, csrf_field is not appropriate here, since it generates a hidden form field (another way to send csrf token apart from what we talked about earlier) to be embedded in a .php file like <form>...<?=csrf_field()?>...</form> => <form>...<input type="hidden" name="laravel_csrf_token" value="***">...</form>, which makes it meaningless to request csrf_field's result via xhr.

Resources