How on my yii2 extension use messages for this extension? - yii2

How on my yii2 extension use messages for this extension?
On my module i used as belove, but after do it as extension it is not work
public function init()
{
parent::init();
$this->registerTranslations();
}
public function registerTranslations()
{
Yii::$app->i18n->translations['vendor/abdualiym/yii2-contacts/*'] = [
'class' => 'yii\i18n\PhpMessageSource',
'sourceLanguage' => 'en',
'basePath' => '#vendor/abdualiym/contacts/messages',
'fileMap' => [
'vendor/abdualiym/yii2-contacts' => 'contact.php',
],
];
}
public static function t($category, $message, $params = [], $language = null)
{
return Yii::t('vendor/abdualiym/yii2-contacts/' . $category, $message, $params, $language);
}
```

To have own messages in extension i did following:
added to common config file:
'contact' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#vendor/abdualiym/yii2-contacts/messages',
'sourceLanguage' => 'en',
'fileMap' => [
'contact' => 'contact.php',
],
],
Then i use
Yii::t('contact', 'Text')

Related

Yii2 all controllers and actions require login, need to add some exceptions. How can I do it?

I've found a lot of answers on how to create Access Control that requires login to all controllers and actions.
The following post shows how I did all controllers require login:
Yii2 require all Controller and Action to login
I've used the code below under my components:
'as beforeRequest' => [
'class' => 'yii\filters\AccessControl',
'rules' => [
[
'allow' => true,
'actions' => ['login', 'error'],
],
[
'allow' => true,
'roles' => ['#'],
],
]
],
But, I want to add some exceptions to it. Some controllers need to have some actions visible to Guest.
I've tried to use this code inside my behaviors on ReportsController:
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'allow' => true,
'actions' => ['share'],
'roles' => ['?'],
],
],
]
Still get redirected to login.
I'm trying to to make actionShare($param) {} public to guests.
What am I missing?
Thanks for all your help!
First execute
yii migrate --migrationPath=#yii/rbac/migrations
from command prompt to create RBAC table in data base.
Then create RbacController in component folder
namespace app\components;
use yii;
use yii\web\Controller;
use yii\filters\AccessControl;
class RbacController extends Controller
{
public function RbacRule($modules = false)
{
$rules = false;
if ($modules){
$rules = [
'allow' => true,
'roles' => ['#'],
'matchCallback' => function ($rule, $action) {
$module = Yii::$app->controller->module->id;
$action = Yii::$app->controller->action->id;
$controller = Yii::$app->controller->id;
$route = "/$module/$controller/$action";
$post = Yii::$app->request->post();
if (\Yii::$app->user->can($route)) {
return true;
}
}
];
}else{
$rules = [
'allow' => true,
'roles' => ['#'],
'matchCallback' => function ($rule, $action) {
//$module = Yii::$app->controller->module->id;
$action = Yii::$app->controller->action->id;
$controller = Yii::$app->controller->id;
$route = "/$controller/$action";
$post = Yii::$app->request->post();
if (\Yii::$app->user->can($route)) {
return true;
}
}
];
}
return $rules;
// return true;
}
}
then extend to your controller using this RbacController instead of controller.
use app\components\RbacController;
class AdminController extends RbacController
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
// [
// 'actions' => ['login', 'logout'],
// 'allow' => true,
// 'roles' => ['?'],
// ],
parent::RbacRule(),
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
'bulk-delete' => ['post'],
],
],
];
}
.......
}
If your controller is inside Modules folder then you have to use
parent::RbacRule(TRUE) instead of parent::RbacRule(),

yii2 change database for admin and site panel

I have the following config file
common/main-local.php
return [
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=aishwariya_basic2',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
],
// 'db' => $db,
'db2' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=aishwariya_basic',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '#common/mail',
],
// autoloading model and component classes
'import'=> [
'class' => 'yii2-widget-linkpager',
'application.extensions.MyLinkPager.*',
],
],
];
Admincontroller
namespace frontend\controllers;
use Yii;
use frontend\models\Site_login;
use frontend\models\EntryForm_model;
use frontend\models\Asal_page_model;
use frontend\models\Interest_page_model;
use frontend\models\Return_page_model;
use frontend\models\Daily_report_model;
use frontend\models\Changepassword;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;
use yii\db\Query;
class AdminController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['index', 'signup'],
'rules' => [
[
'actions' => ['index'],
'allow' => true,
'roles' => ['?'],
],
[
'actions' => ['settings','changepassword'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
/**
* #inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
#####Action index code starts here
public function actionIndex()
{
$this->layout = 'admin';
$my2DbConn = Yii::$app->db;
$model = new Site_login();
if ($model->load(Yii::$app->request->post()) )
{
if ($model->validate()) {
$url = Yii::$app->getUrlManager()->getBaseUrl()."/admin/search";
return $this->redirect($url);
}
}
return $this->render('index', ['model' => $model]);
}
Site controller
public function actionInitial()
{
$this->layout = 'site';
$my2DbConn = Yii::$app->db2;
$model=new Initial_model();
if ($model->load(Yii::$app->request->post()))
{
}
return $this->render('initial',['model'=>$model]);
}
I would like to change the database belongs to controller. Please give me some help. I have used two db but it tooks first db file.
You can configure more then a db in config
return [
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=testdb',
'username' => 'demo',
'password' => 'demo',
],
'db2' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=testdb2',
'username' => 'demo2',
'password' => 'demo2',
],
],
];
and obtain your db (this is if you want use direct command in controller and not for activeRecord)
class yourController extends \yii\web\Controller
{
public function actionYourAction()
{
...
$my2DbConn = Yii::$app->db2;
....
}
Or you can manage programmatically with the proper setting
If for your model (like you have in your code ) you want to use a different database connection other than the db component, you should override the getDb() method in your related ActiveRecord MODEL (see the doc .. link at the bottom):
class YourModel extends ActiveRecord // eg: Initial_model
{
// ...
public static function getDb()
{
// use the "db2" application component
return \Yii::$app->db2;
}
}
and not assign $my2DbConn = Yii::$app->db; in controller this is for createCommand (direct sql commend) and not for activeRecord like you need ..
see this guide http://www.yiiframework.com/doc-2.0/guide-db-active-record.html or this reference for related param http://www.yiiframework.com/doc-2.0/yii-db-connection.html

Invalid JSON data in request body: Syntax error POST Call Rest API YII2

When I try to post using Postman,I get this error {"name":"Bad Request","message":"Invalid JSON data in request body: Syntax error.","code":0,"status":400,"type":"yii\\web\\BadRequestHttpException"}
My controller is
`class CountryController extends ActiveController
{
public $modelClass = 'app\models\Country';
public function behaviors()
{
return [
[
'class' => 'yii\filters\ContentNegotiator',
'only' => ['index', 'view','create'],
'formats' => ['application/json' => Response::FORMAT_JSON,],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'index'=>['get'],
'view'=>['get'],
'create'=>['post'],
'update'=>['put'],
'delete' => ['delete'],
'deleteall'=>['post'],
],
],
];
}
}`
added
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
in api/config.php file.
Where I am wrong??
Try this
public function behaviors()
{
return [
[
'class' => 'yii\filters\ContentNegotiator',
'only' => ['index', 'view','create'],
'formats' => ['application/json' => Response::FORMAT_JSON]
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'index'=>['get'],
'view'=>['get'],
'create'=>['post'],
'update'=>['post'],
'delete' => ['delete'],
'deleteall'=>['post'],
]
]
];
}
I am using wordpress 4.7 on php 7, also getting problems with the empty request body.
My Controller :
add_action('rest_api_init', function()
{
register_rest_route('v0', '/accounts/(?P<slug>[a-z0-9_\-]+)/accounts', array(
'methods' => 'GET',
'callback' => function($request)
{
try {
return 'hello';
}
catch (Exception $e) {
$error = json_decode($e->getMessage(), true);
return new WP_Error($error['status_code'], $error['message'], "");
}
}
));
});
Response Error :
{"code":"rest_invalid_json","message":"Invalid JSON body passed.","data":{"status":400,"json_error_code":4,"json_error_message":"Syntax error"}}
I did not found any solution rather than changing in WP core : wp-includes/rest-api/class-wp-rest-request.php and chaning line 672 for conditional check for empty body or not.
$params = json_decode( $this->get_body(), true );

Yii2 RESTFUL API without models: getting 404 response

I'm implementing RESTFUL API with Yii2. The thing is I don't use models at all. My API just gets the request and performs some calculations (or passes request as a proxy to somewhere else) and outputs the response.
I have following controllers in app\modules\api\v1\controllers:
namespace app\modules\api\v1\controllers;
class CarController extends \yii\rest\Controller
{
// GET /v1/car/:id
public function actionIndex()
{
$carId = \Yii::$app->request->get('id');
// Forwarding request to other API
return ['some_reponse'];
}
// DELETE /v1/car/:id
public function actionDelete()
{
$carId = \Yii::$app->request->get('id');
// Forwarding request to other API
return ['some_reponse'];
}
public function behaviors()
{
return [
'verbs' => [
'class' => \yii\filters\VerbFilter::className(),
'actions' => [
'create' => ['post'],
'delete' => ['delete']
],
],
];
}
}
// ===============================
namespace app\modules\api\v1\controllers;
class CarsController extends \yii\rest\Controller
{
// POST /v1/cars
public function actionCreate()
{
$carData = \Yii::$app->request->post;
// Forwarding data to other API
return ['some_reponse'];
}
public function behaviors()
{
return [
'verbs' => [
'class' => \yii\filters\VerbFilter::className(),
'actions' => [
'create' => ['post']
],
],
];
}
}
// ===============================
namespace app\modules\api\v1\controllers;
class NotificationsController extends \yii\rest\Controller
{
// POST /v1/notifications
public function actionCreate()
{
$noticicationsData = \Yii::$app->request->post;
// Perform some additinal actions here
return ['some_reponse'];
}
public function behaviors()
{
return [
'verbs' => [
'class' => \yii\filters\VerbFilter::className(),
'actions' => [
'create' => ['post']
],
],
];
}
}
Url manager configuration:
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => [ 'v1/cars' ],
'extraPatterns' => [ 'POST cars' => 'create' ]
],
[
'class' => 'yii\rest\UrlRule',
'controller' => [ 'v1/car' ],
'extraPatterns' => [ 'GET car' => 'index', 'DELETE car' => 'delete' ]
],
[
'class' => 'yii\rest\UrlRule',
'controller' => [ 'v1/notifications' ],
'extraPatterns' => [ 'POST notifications' => 'create' ]
]
]
]
Cars endpoint works fine. But other endoints return 404 error. Error response example:
{
"name": "Not Found",
"message": "Page not found.",
"code": 0,
"status": 404,
"type": "yii\web\NotFoundHttpException",
"previous": {
"name": "Invalid Route",
"message": "Unable to resolve the request: v1/car/options",
"code": 0,
"type": "yii\base\InvalidRouteException"
}
}
Any ideas whats wrong here? I guess something is wrong with my rules.
The problem was with urlManager rules configuration. For e.g. if I create CarController it treats like CarsController. So I have to set pluralize to false. Also modified extraPatterns section as well:
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => [ 'v1/cars' ],
'extraPatterns' => [ 'POST' => 'create' ],
],
[
'class' => 'yii\rest\UrlRule',
'controller' => [ 'v1/car' ],
'extraPatterns' => [ 'GET' => 'index', 'DELETE' => 'delete' ],
'pluralize' => false
],
[
'class' => 'yii\rest\UrlRule',
'controller' => [ 'v1/notifications' ],
'extraPatterns' => [ 'POST' => 'create' ]
]
]
]
Problem with yii\rest\Controller::actions(), this method already have actions index , options,view etc. You need disabled action to use your action:
public function actions()
{
$actions = parent::actions();
unset($actions['view'], $actions['index']);
return $actions;
}

How to log in with sha256 in CakePHP 3?

I have a problem. I did a login form with all by default (bcrypt), but I need to do it with sha256 password in my database. How can I do it?
This is my AppController:
public function initialize()
{
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'nombre',
'passwordHasher' => array(
'hashType' => 'sha256',
'className' => 'password'
)
]
]
],
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
'loginRedirect' => [
'controller' => 'Home',
'action' => 'index'
]
]);
// Allow the display action so our pages controller
// continues to work.
$this->Auth->allow(['display']);
}
And usersController:
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error('El usuario o contraseña no es válido.');
}
}
I have to say that no errors are showed, but it shows that user or password are incorrect.