Way to redirect login page if user not login - redirect

I want to redirect user to login page if he is not logged on page. But i have actionLogin in my registrationController
So when I use in my common/main:
'as beforeRequest' => [ //if guest user access site so, redirect to login page.
'class' => 'yii\filters\AccessControl',
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'allow' => true,
'roles' => ['#'],
],
],
],
It always redirect me to index.php?r=site%2Flogin
Is it possible to change main login redirect to index.php?r=registration%2Flogin?
If it possible where I should overwrite code or change something..
'user' => [ 'loginUrl' => ['registration/login'], ],
resolve problem but when I want to go to registration/index to signup user it redirect me to registration/login.
Is it possible to rule out this url from being enforced? I Want to make index.php?r=registration the only available path.
And here is my facebook login; I want to enable this too
public function oAuthSuccess($client) {
// get user data from client
$userAttributes = $client->getUserAttributes();
$user = User::find()->where(['Email' => $userAttributes['email']])->one();
if (!$user) {
$newuser = New SignupForm();
$newuser->oAuthSuccess($client);
$user = User::find()->where(['Email' => $userAttributes['email']])->one();
if ($newuser->validate() && Yii::$app->getUser()->login($user)) {
Yii::$app->session->setFlash('success', Yii::t('app', 'Udało się poprawnie zalogować. Prosimy dokonać zmian w ustawianiach profilu.'));
return $this->redirect('index.php?r=content/news');
}
}
Yii::$app->user->login($user);
}

In your app/config/web.php (for basic template) or
app/frontend/config/main.php (for advance template) - reference
return [
// ...
'components' => [
// ...
'user' => [
'identityClass' => 'common\models\UserIdentity',
'enableAutoLogin' => true,
'loginUrl'=>['registration/login']
],
// ...
and in your controller for eg RegistrationController.php
// ...
class RegistrationController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['login', 'signup'], // those action only which guest (?) user can access
'allow' => true,
'roles' => ['?'],
],
[
'actions' => ['home', 'update'], // those action only which authorized (#) user can access
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
// ...

The simple way is using index.php from backend web or public directory
<?php
// comment out the following two lines when deployed to production
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
require __DIR__ . '/../../vendor/autoload.php';
require __DIR__ . '/../../vendor/yiisoft/yii2/Yii.php';
$config = require __DIR__ . '/../../config/web.php';
$config["controllerNamespace"]='app\controllers\backend';
(new yii\web\Application($config))->run();
if(Yii::$app->user->isGuest){
$request_headers = apache_request_headers();
$srv=$request_headers['Host'];
header("Location: https://".$srv);
die();
}

Related

Request timeout - integrate third party library with codeigniter 3

Im working on API integration InPost API Create shippment. I try integrate third party library inpost with codeigniter 3 from GitHub.
https://github.com/imper86/php-inpost-api
I install this library via composer.
View:
<?php echo form_open('inpost_controller/inpost_shippment_post'); ?>
<div class="form-group">
</div>
</div>
<?php echo form_close(); ?><!-- form end -->
Then I call in controller:
require FCPATH . 'vendor/autoload.php';
Full code file Controller:
<?php
defined('BASEPATH') or exit('No direct script access allowed');
require FCPATH . 'vendor/autoload.php';
use Imper86\PhpInpostApi\Enum\ServiceType;
use Imper86\PhpInpostApi\InpostApi;
class Inpost_controller extends Admin_Core_Controller
{
public function __construct()
{
parent::__construct();
}
/**
* Create shippment Inpost Post
*/
public function inpost_shippment_post()
{
$token = 'xxxxx';
$organizationId = 'xxxxx';
$isSandbox = true;
$api = new InpostApi($token, $isSandbox);
$response = $api->organizations()->shipments()->post($organizationId, [
'receiver' => [
'name' => 'Marek Kowalczyk',
'company_name' => 'Company name',
'first_name' => 'Jan',
'last_name' => 'Kowalski',
'email' => 'test#inpost.pl',
'phone' => '888888888',
'address' => [
'street' => 'Malborska',
'building_number' => '130',
'city' => 'Kraków',
'post_code' => '30-624',
'country_code' => 'PL',
],
],
'sender' => [
'name' => 'Marek Kowalczyk',
'company_name' => 'Company name',
'first_name' => 'Jan',
'last_name' => 'Kowalski',
'email' => 'test#inpost.pl',
'phone' => '888888888',
],
'parcels' => [
['template' => 'small'],
],
'insurance' => [
'amount' => 25,
'currency' => 'PLN',
],
'cod' => [
'amount' => 12.50,
'currency' => 'PLN',
],
'custom_attributes' => [
'sending_method' => 'parcel_locker',
'target_point' => 'KRA012',
],
'service' => ServiceType::INPOST_LOCKER_STANDARD,
'reference' => 'Test',
'external_customer_id' => '8877xxx',
]);
$shipmentData = json_decode($response->getBody()->__toString(), true);
while ($shipmentData['status'] !== 'confirmed') {
sleep(1);
$response = $api->shipments()->get($shipmentData['id']);
$shipmentData = json_decode($response->getBody()->__toString(), true);
}
$labelResponse = $api->shipments()->label()->get($shipmentData['id'], [
'format' => 'Pdf',
'type' => 'A6',
]);
file_put_contents('/tmp/inpost_label.pdf', $labelResponse->getBody()->__toString());
}
}
When I post form, after 30 sec I get error 500 Internar Error Server Request timout.
And now im not sure how to debug now. I enable error log in CI3 application/logs/ I open this file but I not see any error related to this.
Could be a defect, or missing http2 setup/cfg.
Since the header in https2 protocol has shorter header on packs.
Not sure doe
https://caniuse.com/http2 < short http2 (TLS, HTTPS) overview
https://factoryhr.medium.com/http-2-the-difference-between-http-1-1-benefits-and-how-to-use-it-38094fa0e95b < http2 as protocol overview in 5 min

OPTION verb is not working for a list of all records in Yii 2 app

I have created a blank Yii 2 project that have created a REST UserController for already existing User model:
namespace app\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController
{
public $modelClass = 'app\models\User';
}
I have modified the model to have all fields safe:
public function rules()
{
return [
['status', 'default', 'value' => self::STATUS_INACTIVE],
['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_INACTIVE, self::STATUS_DELETED]],
[['username', 'email'], 'required'],
[['username', 'email'], 'unique'],
['email', 'email'],
[['password_hash', 'password_reset_token', 'verification_token', 'auth_key', 'status,created_at', 'updated_at', 'password'], 'safe'],
];
}
I have configured URL rules to have both pluralized and non-pluralized paths:
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'user',
'pluralize' => false,
'except' => ['index'],
],
[
'class' => 'yii\rest\UrlRule',
'controller' => 'user',
'patterns' => [
'GET,HEAD,OPTIONS' => 'index',
],
],
],
I have enabled JSON input, if that matters:
'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
]
All the verbs are processed correctly except for OPTIONS /users:
When I execute OPTIONS /user/20 then I am getting:
200 OK
Empty content
List of allowed methods
But, when I execute OPTIONS users then I am getting 405 Method not Allowed.
What can be wrong or what am I missing?
You are getting 405 Method Not Allowed not because of routing but because of yii\filters\VerbFilter.
The yii\rest\Controller uses verbs() method to set up VerbFilter.
The yii\rest\ActiveController overrides verbs() method and sets VerbFilter to only allow GET and HEAD requests for index action.
It uses options action for OPTIONS method.
If you really want to use index action for OPTIONS method. You have to override verbs() method yourself and add OPTIONS as allowed method for that action. For example like this:
protected function verbs()
{
$verbs = parent::verbs();
$verbs['index'][] = 'OPTIONS';
return $verbs;
}
Or if you want to use options action you have to modify patterns settings as suggested by #Bizley in comments.

Yii2 advanced change views default path (theming)

I would like for my application to automatically change template
so i created this structure frontend/web/themes/myTheme
following http://www.yiiframework.com/doc-2.0/guide-output-theming.html i added this code in frontend/config/main.php
'components' => [
'view' => [
'theme' => [
'basePath' => '#app/themes/myTheme',
'baseUrl' => '#web/themes/myTheme',
'pathMap' => [
'#app/views' => '#app/themes/myTheme',
],
],
],
],
however i kept getting the error that " /var/www/html/myProject/app/frontend/views/site/index.php" The view file does not exist???
i also tried to put this function inside the controller based on How to change default view path in Yii2?
public function getViewPath()
{
return Yii::getAlias('#web/themes/myTheme/site');
}
so my question is:
1. how can I change the views default path?
2. how can i do it automatically since i can not change the common/config/main.php settings during a session?
site controller
class SiteController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['index'],
'allow' => true,
'roles' => ['?'],
],
[
'actions' => ['index'],
'allow' => true,
'roles' => ['#'],
],
],
],
];
}
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
/**
* Displays homepage.
*
* #return mixed
*/
public function actionIndex()
{
$searchModel = new ProductSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
}
I think you are configuring the wrong file.Don't configure themes in the common/config
Try this:
in frontend/config/main.php
'components' => [
'view' => [
'theme' => [
'pathMap' => [
'#frontend/views'=>'#frontend/themes/myTheme',
],
],
],
],
if you need to configure the backend then in the backend/config/main.php
'components' => [
'view' => [
'theme' => [
'pathMap' => [
'#backend/views'=>'#backend/themes/myTheme',
],
],
],
],
The common folder is has to contain the files that are required by both
frontend and backend.
Hope this helps.
First question:
I think than you have a common mistake in yii when used advanced app: the alias #app references root directory of frontend, backend, or common depending on where you access it from View documentation here.
You would used the solution proposed by ovicko.
Second question:
You can change the theme configuration dynamically in controller through view object:
$this->view->theme->pathMap =['#app/views' => '#app/themes/myTheme/',];
EDIT
According to Documentation:
Theming is a way to replace a set of views with another without the need of touching the original view rendering code.
What means that the original view file must exist and theming simply replace it in during rendering. So you must create a file in /var/www/html/myProject/app/frontend/views/site/index.php (a empty file is valid) in order to theming works.
This sounds quite ridiculous, I Know, but it works.
But I think that is much better and easier the use of differents layouts, again, to change dinamically the layout in your controller:
$this->layout = 'route/yourlayout';

URL-Manager will not route

I cloned our repositorie and created excatly the same URL-rules like at my own project. Now, i will get error like this after having logged in:
Firefox:
Fehler: Umleitungsfehler
The website called is rerouting request,which never will come to an end.
This problem sometimes occures, if cookies are deactivated
Chrome:
ERR_TOO_MANY_REDIRECTS
I definetly accepted using cookies at both browser!!
Debugging shows me,that I have dozen of 302-Requests,so Yii breaks down!
I use Windows, not LINUX, so I don't care about any permissions.
Here are the rules:
'urlManager' => [
'class' => 'yii\web\UrlManager',
'enablePrettyUrl' => true,
'showScriptName' => true,
'enableStrictParsing' => true,
'rules' => [
'/' => 'site/login',
'home' => 'site/index',
'logout' => 'site/logout',
'contact' => 'site/contact',
'signup' => 'site/signup',
'reset' => 'site/request-password-reset',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<action:(contact|captcha)>' => 'site/<action>'
],
Here is frontend configuration:
<?php
$config = [
// LZA 17-07-30
'sourceLanguage' => 'de-DE',
'language' => 'de-DE',
// LZA 17-07-30 siehe Funktionen in http://demos.krajee.com/grid#module
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => '4lD2RxDNkC4ckpwxTmkDzOLIvk0JMs3F',
],
],
];
if (!YII_ENV_TEST) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
// LZA 17-07-30 CRUD
'generators' => [// customized CRUD generator
'crud' => [
// 'class' => 'app\myCrud\crud\Generator', // LZA 17-07-20 die Klasse von CRUD generator
'class' => '\common\wsl_dev\wsl_crud\crud\Generator', // LZA 17-07-20 die Klasse von CRUD generator
'templates' => [
'myCrud' => '/#common/wsl_dev/wsl_crud/crud/default', //LZA 17-07-20 Templatename und Templatepfad
]
]
],
// LZA 17-07-30 CRUD
];
}
return $config;
If I deacitvate URLManger,setting
'enablePrettyUrl' => false,
everything works fine.
If I put in manually Url like this:
http://localhost/yii2_perswitch/frontend/web/yiic.php/home
everything works fine,too
Any ideas,how to fix this?
I deleted all my cookies,without any effects!
Solution 1:
Enable debug mode from web/index.php (uncomment these two lines):
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
and you can see exactly what causes the problem.
Redirected too many times error was because the 777 permissions for
runtime and assets folder were not set.
Solution 2:
I think that the problem is related with the path or domain of the cookie. I believe that this info could be useful.
https://github.com/samdark/yii2-cookbook/blob/master/book/cookies.md

Using Yii2 authClient to retrieve scope data from Facebook after successful authentication

Currently working with the Yii2 framework and using the includable \yiisoft\yii2-authclient OAuth abstraction class. I am able to connect and authenticate via Facebook but can not figure out how to access secondary data available through the OAuth2 scope configuration option.
Related but vague (as it does not explain how scope applies to the situation nor how to use the authClient to retrieve the data: Login with Facebook API
Config
'authClientCollection' => [
'class' => 'yii\authclient\Collection',
'clients' => [
'facebook' => [
'authUrl' => 'https://www.facebook.com/dialog/oauth',
'class' => 'yii\authclient\clients\Facebook',
'clientId' => '*****',
'clientSecret' => '*****',
'scope' => [
'email',
'public_profile',
'user_about_me',
'user_location',
'user_work_history',
]
],
],
],
Controller setup:
public function actions()
{
return [
'auth' => [
'class' => 'yii\authclient\AuthAction',
'successCallback' => [$this, 'onAuthSuccess'],
],
];
}
...
/**
* [onAuthSuccess description]
*
* #param [type] $client [description]
* #return [type] [description]
*/
public function onAuthSuccess($client)
{
$attributes = $client->getUserAttributes();
echo '<pre>';
print_r( $attributes );
echo '</pre>';
exit;
...
The returned object is as follows:
yii\authclient\clients\Facebook Object
(
[authUrl] => https://www.facebook.com/dialog/oauth
[tokenUrl] => https://graph.facebook.com/oauth/access_token
[apiBaseUrl] => https://graph.facebook.com
[scope] => Array
(
[0] => email
[1] => public_profile
[2] => user_about_me
[3] => user_location
[4] => user_work_history
)
[attributeNames] => Array
(
[0] => name
[1] => email
)
[version] => 2.0
...
)
How would I access the user's user_about_me data?
*Edited to add controller logic that provides the data dump.
You can get following info by setting this values in attributeNames
id
name
first_name
last_name
age_range
link
gender
locale
picture
timezone
updated_time
verified
In your config file
...
'components' => [
...
'authClientCollection' => [
'class' => 'yii\authclient\Collection',
'clients' => [
'facebook' => [
'class' => 'yii\authclient\clients\Facebook',
'authUrl' => 'https://www.facebook.com/dialog/oauth',
'clientId' => 'YOUR APP CLIENT ID',
'clientSecret' => 'YOUR APP CLIENT SECRET',
'attributeNames' => [
'id',
'name',
'first_name',
'last_name',
'link',
'about',
'work',
'education',
'gender',
'email',
'timezone',
'locale',
'verified',
'updated_time',
],
],
],
],
...
],
...
Important Links and references
https://developers.facebook.com/docs/facebook-login/permissions/v2.2
Login with Facebook API
What data can be obtained about a user who logs in with Facebook Oauth?
https://developers.facebook.com/tools/explorer/?method=GET&path=me%3Ffields%3Did%2Cname%2Cemail&version=v2.7
https://developers.facebook.com/docs/graph-api/using-graph-api/#fieldexpansion
You should use getUserAttributes method:
public function actions()
{
return [
[
'class' => 'yii\authclient\AuthAction',
'successCallback' => [$this, 'successCallback']
]
];
}
/**
* #param OAuth2 $client
*/
public function successCallback($client)
{
$attributes = $client->getUserAttributes();
...
}