function to get user IP address in Yii - yii

I'm trying to create a s shortcut to get user IP address, I created this function below in protected/helpers/shortcut.php
echo getIP();
function getIP()
{
return CHttpRequest::getUserHostAddress();
}
i get this error because i set my php.ini to strict. and getUserHostAddress() is not a static function
Strict Standards: Non-static method CHttpRequest::getUserHostAddress() should not be called statically in /Applications/XAMPP/xamppfiles/htdocs/dev/protected/helpers/shortcuts.php on line 97
::1
i tried
Yii::app()->request->userHostAddress;
but i get this error
Notice: Trying to get property of non-object in /Applications/XAMPP/xamppfiles/htdocs/dev/protected/helpers/shortcuts.php on line 97
any idea what i'm doing wrong? Thanks

In Yii2, use Yii::$app->getRequest()->getUserIP()

try this:
Yii::app()->request->getUserHostAddress()
instead
Yii::app()->request->getUserHostAddress
with "()" it should work

This is related to Yii2 (but may work in Yii 1.1 too). If you need the "X-Forwarded-For" IP instead of the Proxy, if your server is behind a reserve proxy, make the change the 'request' configuration on config/main.php as below:
'request' => [
'csrfParam' => '_csrf-frontend',
'trustedHosts' => [
'192.168.1.10', // The IP of the reverse proxy server
],
'secureHeaders' => [ // The headers coming from reserve proxy
'X-Forwarded-For',
'X-Forwarded-Proto',
'Front-End-Https',
],
],

Related

Getting 401 unauthorized for Laravel sanctum

I am using Laravel Sanctum with Vuejs SPA. Both reside on same top level domain
Laravel backend : app.demo.localhost
Vue SPA : app-spa.demo.localhost
Login and logout (endpoints) are working correctly when called from VueJS SPA using axios and XSRF-TOKEN is succesfully set, but when I call other api end points it gives me 401 unauthorized.
In axios this is being set
axios.defaults.withCredentials = true;
I have the below configurations
In Laravel .env
SESSION_DRIVER=cookie
SESSION_DOMAIN=.demo.localhost
SANCTUM_STATEFUL_DOMAINS=app-spa.demo.localhost
In Routes/Api.php
Route::middleware('auth:sanctum')->get('api/user', function (Request $request) {
return $request->user();
});
In cors.php
'paths' => ['api/*', 'sanctum/csrf-cookie', 'login', 'logout'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
Could someone help me out please?
If you are using php artisan serve add the port number to SANCTUM_STATEFUL_DOMAINS. So if your port number is 8000:
SESSION_DRIVER=cookie
SESSION_DOMAIN=.demo.localhost
SANCTUM_STATEFUL_DOMAINS=app-spa.demo.localhost:8000
Your SANCTUM_STATEFUL_DOMAINS must match the url in your browser. The port number should not be on the SESSION_DOMAIN.
Following are the 8 steps that I follow while setting up Laravel sanctum check if you missed anything
Step1 composer require laravel/sanctum
Step2 php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider
Step3 php artisan migrate (you can ignore this if you're using spa)
Step4 uncomment this line from app/http/kernel.php \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
Step5 In config/cors.php update 'supports_credentials' => true,
Step6 In .env file update SESSION_DRIVER=cookie & add new line of SESSION_DOMAIN=localhost (even if your using any port like 8080 just mention localhost in session_domain)
Step7 In config/sanctum.php add your client domain along with port(if local) in stateful as follows, in my case for vue CLI it's usually localhost:8080 & for nuxt its localhost:3000 , code is as follows
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:8000,localhost:8080,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
env('APP_URL') ? ','.parse_url(env('APP_URL'), PHP_URL_HOST) : ''
))),
Mostly if your stateful (step7) is not setup properly you will get 401 unauthorized or it will try to redirect you to the home page along with cors policy error
Step8 Do not forget to await until sanctum/csrf-cookie promise is resolved
async login() {
await axios.get("http://localhost:8000/sanctum/csrf-cookie");
await axios.post("http://localhost:8000/login", {
email: "kunal#gmail.com",
password: "password",
});
let response = await axios.get("http://localhost:8000/api/user");
console.log(response.data);
},
For anyone dealing with localhost:
SESSION_DRIVER=cookie
SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=localhost:8080(port number you use)
I just encountered the same problem. I configured all the options according to the official documentation, but I couldn't get the authorization.
Then I use routes/web.php instead of routes/api.php, so I can use sanctum middleware very well.
Now the problem seems obvious,Axios withCredentials maybe need to place in the correct way.
const http = axios.create({
baseURL: API_URL,
withCredentials: true
})
maybe not work. So I add {withCredentials: true} like
http.get('/api/whoami', {withCredentials: true})
.then(res => {
console.log(res.data)
})
Then it works.
But the very strange thing is that it is normal now, no matter whether I clear the browser cache, cookies or Laravel's various caches, there is no previous situation
For me i just had to place the host with port number:
SANCTUM_STATEFUL_DOMAINS=127.0.0.1:5173
and it started working.
Maybe this helps someone.
My problema was.... (no read with attention)
If your SPA needs to authenticate with private / presence broadcast channels, you should place the Broadcast::routes method call within your routes/api.php file:
Hi i found a solution.
My SPA is Vue v3 working on 3000 port.
Also my backend is working on 80 port. (laravel 8.1)
Make Stateful Domains in config/sanctum.php like that
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost:3000',
env('APP_URL') ? ','.parse_url(env('APP_URL'), PHP_URL_HOST) : ''
))),
Adding only one and correct domain on their, worked for me magically. I wrote before there whole possible variant of ports, it made me crazy and cost a couple days and nights.
My issue was I setup the domain in the wrong place.
I thought was an array of domains, in config/sanctum.php, but not, needs to be placed within the string:
OK:
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1,myownlocaldomain.test,myownlocaldomain.test:8080', <-------- OK
env('APP_URL') ? ','.parse_url(env('APP_URL'), PHP_URL_HOST) : ''
))),
BAD:
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
env('APP_URL') ? ','.parse_url(env('APP_URL'), PHP_URL_HOST) : '',
'myownlocaldomain.test', <----- BAD
'myownlocaldomain.test:8080', <---- BAD
))),
I hope I save days of work to someone else...

AspectMock test::double doesn't work in Yii2 tests

When I try to mock anything like so:
Test::double(MyService::class, [
'accept' => true
]);
It throws error:
Call to a member function registerClass() on null
I could not find anything in the internet to help me with this one. Any ideas?
EDIT
One step further. I had to update Test/_bootstrap.php with following:
$kernel = Kernel::getInstance();
$kernel->init([
'debug' => true,
'includePaths' => [__DIR__ . '/../service/'],
'excludePaths' => [__DIR__],
'cacheDir' => '/tmp/aopcache',
]);
It still does not work, but at least throws no errors. Any idea how to make AspectMock actually mock stuff?
SOLUTION
I figured it out. In your test/_bootstrap.php you must load yii AFTER you configured kernel:
$kernel->loadFile(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
This can be closed.
I figured it out. In your test/_bootstrap.php you must load yii AFTER you configured kernel:
$kernel->loadFile(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');

Paypal REST API invalid credentials

I use the REST api in my nodejs application.
All is working good with sandbox but when i update with live credentials i get:
{ [Error: Response Status : 401]
response:
{ error: 'invalid_client',
error_description: 'The client credentials are invalid',
httpStatusCode: 401 },
httpStatusCode: 401 }
I updated my account to buisness but still not working, i use the live endpoint and Live credentials.
What should i do in order to make this work?
I had the same issue using PayPalSDK/rest-sdk-nodejs and solved passing with the configuration parameters (host, client_id, client_secret, ...) also the parameter 'mode' set to 'live'. Otherwise the default mode used by the library is 'sandbox' and hence the impossibility to use the live credentials.
As matteo said, if you switch from dev to live environment, only updateing the client id and secret isn't enough. You need to set the ApiContext-Mode to "live".
PayPals PHP REST-API-SDK comes with some great samples. Take a look at the bootstrap.php in /vendor/paypal/rest-api-sdk-php/sample/ in line 84. There are some configurations happening, after getting the api context.
<?php
$apiContext = new ApiContext(
new OAuthTokenCredential(
$clientId,
$clientSecret
)
);
// Comment this line out and uncomment the PP_CONFIG_PATH
// 'define' block if you want to use static file
// based configuration
$apiContext->setConfig(
array(
'mode' => 'sandbox',
'log.LogEnabled' => true,
'log.FileName' => '../PayPal.log',
'log.LogLevel' => 'DEBUG', // PLEASE USE `INFO` LEVEL FOR LOGGING IN LIVE ENVIRONMENTS
'cache.enabled' => true,
// 'http.CURLOPT_CONNECTTIMEOUT' => 30
// 'http.headers.PayPal-Partner-Attribution-Id' => '123123123'
//'log.AdapterFactory' => '\PayPal\Log\DefaultLogFactory' // Factory class implementing \PayPal\Log\PayPalLogFactory
)
);

Error using Laravel resource controller update method within a grouped route

I have a Laravel app which I'm using to create a RESTful API.
I'm having some issues with the edit/update methods in my resource controller when using a grouped route.
WHen I remove the route grouping the controller works as expected.
My routes look like:
Route::group(array('prefix' => 'api/v1'), function()
{
Route::resource('/trip', 'TripController');
});
So using this my RESTFul endpoints should look like:
GET /api/v1/trip/{resource}
GET /api/v1/trip/{resource}/edit
PUT /api/v1/trip/update/{resource}
GET /api/v1/trip/create
POST /api/v1/trip/store/{resource}
etc.
All work except the Edit and Update endpoints.
When I hit /api/v1/trip/{resource}/edit I get the following error
Unable to generate a URL for the named route "trip.update" as such route does not exist.
My Controller Edit method is just a quick form for testing. It looks like:
public function edit($id)
{
$oTrip = new Trip;
$oTrip = $oTrip->find($id);
echo Form::model($oTrip, array(
'route' => array('trip.update', $oTrip->id),
'method' => 'PUT'
));
echo Form::text('headline');
echo Form::text('description');
echo Form::submit('Click Me!');
echo Form::close();
}
Laravel seems to be unable to find trip.update when in the grouped route.
I think there is a problem with the Group prefix api/v1
When I comment out the group code just to read:
Route::resource('/trip', 'TripController');
...and access the uri just as /trip/{resource}/edit without the api/v1 prefix everything works fine as expected.
Is there something I'm missing?
I would really like to get this working with the grouping and api/v1 prefix.

DNS Lookup for localhsot failed. No such host is known

i did a break point on the method but it never goes there and also if paste the url in the web browser and hit enter and this is what i get in Firebug:
ReadResponse() failed: The server did not return a response for this request.
EDIT:
indeed that was typo, after correcting it and i still have no response, in FF i see the response
GET GetCustomer?method=jsonp1299253547713
http://localhost:2344/service1.svc/GetCustomer?method=jsonp1299253547713
Aborted
localhost:2344
?
what may be wrong ?
END EDIT
i have a created wcf services using json with padding (http://msdn.microsoft.com/en-us/library/cc716898(v=vs.90).aspx)
i have the code below that i am using to call the service, and this code is in html page withint th same project that i have created the wcf service.
$("#btn").click(function (event) {
$.getJSON('http://localhsot:2344/Service1.svc/GetCurrentUser?method=?', { },
function (data) {
debugger
alert(data);
});
//return false;
});
getting this error:
DNS Lookup for localhsot failed. No such host is known
Try renaming:
localhsot => localhost
You spelled localhost wrong. Look at your url and fix the spelling error.