Laravel 5 - can not reset password on production server 404 - Not Found - laravel

Anyone knows why the route '/password/email' returns 404 Not Found error on production server, but works on local?
When user is trying to reset his password by email (https://compariimobiliare.ro/password/reset), the POST URL https://compariimobiliare.ro/password/email gives 404 Not Found error. Same URL works fine on local server, but not on production.
The route is there, I can see it when I run the command:
php artisan route:list
POST | password/email | | App\Http\Controllers\Auth\ForgotPasswordController#sendResetLinkEmail | web,guest
Laravel default implementation:
public function sendResetLinkEmail(Request $request)
{
$this->validate($request, ['email' => 'required|email']);
// We will send the password reset link to this user. Once we have attempted
// to send the link, we will examine the response then see the message we
// need to show to the user. Finally, we'll send out a proper response.
$response = $this->broker()->sendResetLink(
$request->only('email')
);
if ($response === Password::RESET_LINK_SENT) {
return back()->with('status', trans($response));
}
// If an error was returned by the password broker, we will get this message
// translated so we can notify a user of the problem. We'll redirect back
// to where the users came from so they can attempt this process again.
return back()->withErrors(
['email' => trans($response)]
);
}

I can see you have POST route for password/email.
Do you have a GET route for password/email as well?
You are getting 404 because it is trying to access GET route.

Related

Can not get laravel cookie laravel_token while consuming own API

Cookie is avaiable in browser but can not get it even can not check if it exists .
working on laravel and vuejs app where I am using passport for authentication.
I am consuming own api with vuejs so I have added CreateFreshApiToken middleware in kernel.php
vuejs is creating and sending laravel_token cookie successfully but I can not read it using vuejs or javascript.
since I can not check if cookie is available or not I can not check if user is logged in or not.
How I will tell vuejs that user is logged in and take to intended route ?
For now I am saving access_token in localStorage and sending it with each request but I am looking for a solution which can help to use laravel builtin laravel_token cookie to authenticate and authorize the users.
More Details
If i run this command in console then I get response
document.cookie.match('XSRF-TOKEN')
But
document.cookie.match('laravel_token')
returns null
I think the tick icon in the shown image at top is sign of making it private or something that makes it inaccessible.
Update
I found something from internet
But I still want to know how I can tell vuejs app that user is logged in or not ??
Update 2
For now I am sending access_token in header manually from vuejs and it is working fine.
if(localStorage.getItem('laravel_token') !== 'undefined' && !! localStorage.getItem('laravel_token') == true){
window.axios.defaults.headers.common['Authorization'] = 'Bearer '+ localStorage.getItem('laravel_token')
}
A little work around will be for you to implement the authenticated method in your LoginController, and return a json success code. You can then receive this code and store.
public function authenticated(Request $request, $user)
{
// return redirect()->intended($this->redirectPath());
return json_encode(['authenticated' => true]);
}
Using axios...
axios.post('/login', {
email: user.username,
password: user.password
}).then(response => {
.then(response => {
console.log(response)
//response.data.authenticated will return true if user has been authenticated
})
}).catch(err => {
console.log(err)
})

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

How to construct a private sever-to-client-side API? Laravel Passport?

I'm not sure if I'm using the correct method for my problem.
I would like to get Infos via Axios. For example: calling: /api/user with Axios gets me the user, but I don't want to see the information when I go on domain.test/api/user.
I even want to use API calls to get Results of Functions even if the User is a Guest.
I installed everything there is on the Laravel Documentation for API, but still I'm not sure how the user gets the Token.
So if I call:
axios.get('/api/user')
.then(response => {
console.log(response.data);
});
I get from the network tab {"message":"Unauthenticated."}. (I didn't forget to set: ...Middleware\CreateFreshApiToken::class and everything there is).
I think my problem is that I didn't register the User correctly. I got my two keys what should I do with it?
And then it's weird, reading the blog https://laravelcode.com/post/laravel-passport-create-rest-api-with-authentication, they use
$success['token'] = $user->createToken('MyApp')->accessToken;
But I don't get it. Where do I save it? I'm super confused, because every blog about shows Laravel Passport completely differently.
Or am I doing it wrong?
Passport is an OAuth2 server implementation which offers several different authorization strategies. While it is certainly possible to use Passport for authentication, it's primary purpose is authorization. This is done via token scopes. The type of token you choose to issue depends on your intended purpose with the API and whom your intended target is to be consuming your api.
Let's start with the following:
$success['token'] = $user->createToken('MyApp')->accessToken;
Here they are creating Personal Access Tokens. This is the simplest means of consuming your api, since clients are able to create the token themselves as needed and are long lived.
The Password Grant strategy is also a good option. A common approach when using this strategy is proxying authentications to Passport internally and merging the client id and secret into the request in a middleware.
public function handle($request, $next) {
return $next(tap($request, function($request) {
$request->merge([
'client_id' => config('services.passport.client.id'),
'client_secret' => config('services.passport.client.secret')
]);
// do any other pre-request work needed here
}));
}
Setup
To get started with Passport, run the command:
php artisan passport:install
This will create the encryption keys as well as a personal access and password grant client types, which will be stored in your database in the oauth_clients table.
Guard and Middleware
API routes need to be using the api guard, done by setting auth:api middleware on the route group(s) or Controller constructor.
// using via constructor
public function __construct()
{
$this->middleware('auth:api');
}
// via a route group
Route::group(['middleware' => ['auth:api'], function() {
// your api routes
});
Passport Routes
Your user model needs to be using the trait HasApiTokens and within the AuthServiceProvider call Passport::routes() in the boot method.
public function boot()
{
$this->registerPolicies();
Passport::routes();
// this is also an ideal time to set some token expiration values
Passport::tokensExpireIn(now()->addDays(15));
Passport::refreshTokensExpireIn(now()->addDays(30));
}
To use the personal access token strategy for authentication, you need to create your own login and logout routes instead of using the builtin Laravel auth mechanisms.
Referring to the tutorial in your question, they have defined the following routes:
Route::post('login', 'API\PassportController#login');
Route::post('register', 'API\PassportController#register');
and the login method implemented as:
public function login(){
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')->accessToken;
return response()->json(['success' => $success], $this->successStatus);
}
else{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
This is expecting a ajax request with an email and password to be posted to login and if successful it responds with an access token.
Storing/Using the Token
This token must be stored client side, either in a cookie or local storage, for example, and then added to every request from the client there after. You'll add the token to the Authorization header in client requests.
// Use a response interceptor to check for a token and put it in storage
axios.interceptors.response.use(response => {
// store the token client side (cookie, localStorage, etc)
if (response.data.token) {
localStorage.setItem('token', token)
}
return response
}, error => {
// Do something with response error
return Promise.reject(error);
});
// Use a request interceptor to add the Authorization header
axios.interceptors.request.use(config => {
// Get the token from storage (cookie, localStorage, etc.)
token = localStorage.getItem('token')
config.headers.common['Authorization'] = `Bearer ${token}`
return config;
}, error => {
// Do something with request error
return Promise.reject(error);
});
Accessing the Authenticated User
In order to get the user, pass the 'api' parameter to the auth() helper, Auth facade, or through the request:
$user = auth('api')->user();
$user = Auth::user('api');
$user = request()->user('api');
Keep in mind personal access tokens are long lived, so it's up to you to decide when and how they should expire.
Any http client can be used to make api requests, axios is a very common option and included with each Laravel installation.

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.

SoundCloud API 401 error in Codeigniter

I'm trying to get Soundcloud to return a track ID, but can't get it to work. Documentation here (PHP tab): https://developers.soundcloud.com/docs/api/guide#errors
I've triple checked my credentials from soundcloud that I'm adding as args.
Function in my controller:
function formprocessor()
{
require_once (APPPATH.'third_party/Services/Soundcloud.php');
// create a client object with your app credentials
$client = new Services_Soundcloud('my client id', 'my client secret', 'http://127.0.0.1:8888/index.php/welcome/');
try {
$me = json_decode($client->get('me'), true);
}
catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
}
What would cause this to fail? I keep getting a 401
Here's a reference to the API: https://developers.soundcloud.com/docs/api/reference
you need to authenticate by sending the user (even if thats you) to "authorizeurl":
$authURL = $client->getAuthorizeUrl();
then set the access token with:
$accessToken = $client->accessToken($_GET['code']);
$client->setAccessToken($_SESSION['token']); //if you saved token in a session
Then you should at least be able to "get me" this part is working for me however i cannot access things such as /me/tracks/ or /me/followings/ at the moment.

Resources