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.
Related
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')
Problem regarding login with Auth in cakephp3
$this->loadComponent('Auth', [
'loginRedirect' => [
'controller' => 'Articles',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Pages',
'action' => 'display',
'home'
]
]);
it only allows me to use username by default, Okay If I wanted to login using email, that through I have searched and got this:
UserController.php
public function login()
{
if ($this->request->is('post'))
{
$this->Auth->config('authenticate', [
'Form' => [
'fields' => ['username' => 'email']
]
]);
$this->Auth->constructAuthenticate();
$this->request->data['email'] = $this->request->data['username'];
unset($this->request->data['username']);
$user = $this->Auth->identify();
if ($user)
{
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error(__('Invalid username or password, try again'));
}
}
I can change fields from username to email and reconstruct it but What if I wanted to login with ID field.
$this->Auth->config('authenticate', [
'Form' => [
'fields' => ['username' => 'id']
]
]);
If I change from email to id, it is not allowing me to login. Do I have to use then queries instead?
I just had the same issue and solved it like this using cakePHP 3.3
Your AppController
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
]
]
],
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
'unauthorizedRedirect' => $this->referer(),
'loginRedirect' => [
'plugin' => false,
'controller' => 'Pages',
'action' => 'home',
],
]);
Your UserController (login action)
/**
* #return Response|null
*/
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('Your username or password is incorrect.');
}
}
Your basic Users/login.ctp template
<?= $this->Form->create() ?>
<?= $this->Form->input('email') ?>
<?= $this->Form->input('password') ?>
<?= $this->Form->button('Login') ?>
<?= $this->Form->end() ?>
Your problem is, when you changed the 'email' field to 'id' in the below code,
`('authenticate', ['Form' => ['fields' => ['username' => 'id']]]);`
you should have changed the input field of your view 'login.ctp'.
from this: <?= $this->Form->input('email') ?>
to this: <?= $this->Form->input('id') ?>
I have this controller code for login:
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
return $this->redirect(Yii::$app->request->baseUrl.'/telephone/index');
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->redirect(Yii::$app->request->baseUrl.'/telephone/index');
}
return $this->render('login', [
'model' => $model,
]);
}
And for preventing the add and delete action for unauthorized users i used:
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['add','delete'],
'rules' => [
// allow authenticated users
[
'allow' => true,
'roles' => ['#'],
],
// everything else is denied by default
],
],
];
}
But if unauthorized users clik add or delete, it is redirected to site/login. How can i change that controller and action?
There are different approaches to changing that route depending on the scope. They all involve changing the loginUrl property of the yii\web\User class.
Global
Edit config file.
'components' => [
'user' => [
'loginUrl' => ["controller/action"],
],
],
Controller/Action
Edit beforeAction method of the controller.
public function beforeAction($action)
{
// action-specific
if(in_array($action->id,['not', 'allowed', 'actions']))
Yii::$app->user->loginUrl = ["controller/action"];
// controller-wide
Yii::$app->user->loginUrl = ["controller/action"];
if (!parent::beforeAction($action)) {
return false;
}
return true;
}
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['add','delete'],
'rules' => [
'allow' => true,
'actions' => ['add','delete'],
'roles' => ['#'],
'denyCallback' => function ($rule, $action) {
return $this->redirect('index.php?r=site/login');
}
],
],
];
}
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
Right now I am working on project where we need facebook and twitter login.
And I have also configure the login in my project but now its not authenticate with simple username and password.
This is AppController.php
class AppController extends Controller
{
public function initialize()
{
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'loginRedirect' => [
'controller' => 'Users',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Users',
'action' => 'login'
],
'authenticate' => [
'ADmad/HybridAuth.HybridAuth'
]
]);
}
}
Its working with only facebook and twitter login,and please let me know how to store user in database after successful login in fb or twitter.
Change above function to this.
public function initialize()
{
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authenticate' => [
'Form',
'ADmad/HybridAuth.HybridAuth'
],
'loginRedirect' => [
'controller' => 'Users',
'action' => 'index',
'plugin' => false
],
'logoutRedirect' => [
'controller' => 'Users',
'action' => 'login',
'plugin' => false
]
]);
}
The point here is: just add "Form" under "authenticate".
CakePHP can handle many login types simultaneously.
To store your users in the database just follow the plugin's instructions to set up the users and social_profiles tables.
Then simply add your regular user logic (UsersController + login.ctp, etc, etc).
Here's how I load the Auth component to achieve this:
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
],
],
'ADmad/HybridAuth.HybridAuth' => [
'fields' => [
'provider' => 'provider',
'openid_identifier' => 'openid_identifier',
'email' => 'email'
],
'profileModel' => 'ADmad/HybridAuth.SocialProfiles',
'profileModelFkField' => 'user_id',
'hauth_return_to' => null
],
],
]);