Cakephp 3.8 - Authentication succeed, but I stay on the login page - cakephp-3.0

My cakephp 3 application works well.
I wanted to duplicate my application into an other folder to have a development environment. I use the same deposit. My production folder is linked with the master branch. My developement folder is linked with the develop branch.
The sources are the same in the two cases. The only differences are the database used (tests database for my environment folder) and the root folder.
When I connect on the production version, all works well.
When I connect on the developement version, login works well, I get the correct redirection information from $this->Auth->redirectUrl(), but I stay on the login page.
Anyone can help me please?
public function login()
{
$this->log("UserController - login()", "debug");
$this->Auth->allow();
$this->viewBuilder()->layout('login');
//return $this->redirect( ['controller' => 'Login', 'action' => 'index']);
if ($this->request->is('post')) {
$user = $this->Auth->identify();
//debug($user); debug($this->Auth); die();
if ($user) {
//debug($user); die();
$this->log("UserController - login(): ".$user["id"].' - '.$user["username"], "debug");
$this->loadModel('Logs');
$log = $this->Logs->newEntity();
$log->log_userId = $user["id"];
$log->log_action = "LOGIN";
$log->log_srcip = $_SERVER["REMOTE_ADDR"];
if ($this->Logs->save($log)) {
//$this->Flash->success(__("L'utilisateur a été sauvegardé."));
}
$this->Auth->setUser($user);
//debug($user); die();
$this->log("UserController - login() - role = : ".$user['role'], "debug");
switch($user['role']) {
case "club_master":
return $this->redirect([
'controller' => 'candidats',
'action' => 'index'
]);
break;
case "register_agent":
return $this->redirect([
'controller' => 'inscriptions',
'action' => 'index'
]);
break;
default:
//debug($this->Auth->redirectUrl()); die();
return $this->redirect($this->Auth->redirectUrl());
}
}
$this->Flash->error(__('Login ou mot de passe invalide, veuillez essayer de nouveau.'));
}
}

Related

Login access not working in yii2

Im using yii2 for my project. I need to use two different tables for login (Login page is same). I have two models Admin and User. And i have one LoginFrom for login.
I can login properly but the problem is after logged in i cannot get whether the admin is logged in or the user is logged in.
I have set it in config file (web.php) like below:
'admin' => [
'identityClass' => 'app\models\Admin',
'enableAutoLogin' => false,
'class' => 'yii\web\User',
'authTimeout' => 1200, // in Seconds. 1200 seconds means 20 mins
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => false,
'authTimeout' => 1200
],
So im getting logged in user details by using below method:
\Yii::$app->admin->identity;
\Yii::$app->user->identity;
My problem is if im logged in as admin i can get user values also by using this : \Yii::$app->user->identity; or if im logged in as user i can get admin values by using this : \Yii::$app->admin->identity;.
My LoginForm.php is :
<?php
namespace app\models;
use Yii;
use yii\base\Model;
class LoginForm extends Model
{
public $username;
public $password;
public $rememberMe = true;
private $_user = false;
public function rules()
{
return [
// username and password are both required
[['username', 'password'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, 'Incorrect username or password.');
}
}
}
public function login()
{
if ($this->validate()) {
if(!empty($this->getUser()['phone_number'])) {
return Yii::$app->admin->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
} else {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
}
}
return false;
}
public function getUser()
{
if ($this->_user === false) {
$this->_user = User::findByUsername($this->username);
if(!$this->_user) {
$this->_user = Admin::findByUsername($this->username);
}
}
return $this->_user;
}
}
I cant find the problem and if i logged in identity creating for both the users so i could'nt write access rules in particular controller to allow admin only to access the controller.Please help me :(
From reading the comments I think you should just create a unifying table for the two identities where they both get their IDs from. Then make that the identity class. The reason you are able to see the details in both identity classes is that they have the same ID.

reset password validation in Yii2

I have a form in which I am trying to reset the password. I have 3 fields password, changepassword and re-enterpassword.
First I need to check whether the password field matches with database password.
While user signup I have used the default Yii2 functionality which generates random password and saves that password into database. Also I used the default login functionality while user login.
And now, for validating the password, I am trying to use the same default Yii2 validation which is used in login. But, it is not working fine. It is always giving validation true when I had echoed and checked in the controller with $user->validate(), which you will find in the below code.
I have a view resetProfilePassword.php in which I have a form
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?php
echo $form->field($resetpasswordmodel, 'password');
echo $form->field($resetpasswordmodel, 'changepassword');
echo $form->field($resetpasswordmodel, 'reenterpassword');
?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
I have a model resetProfilePasswordForm.php
<?php
namespace frontend\models;
use common\models\User;
use yii\base\Model;
class ResetProfilePasswordForm extends Model
{
public $password;
public $changepassword;
public $reenterpassword;
public function rules()
{
return [
['password', 'validatePassword'],
['changepassword', 'required'],
['reenterpassword', 'required'],
['reenterpassword', 'compare', 'compareAttribute'=>'changepassword', 'message'=>"Passwords don't match" ]
];
}
public function attributeLabels()
{
return [
//'user_profile_id' => 'User Profile ID',
//'user_ref_id' => 'User Ref ID',
'password' => 'Password',
'changepassword' => 'Change Password',
'reenterpassword' => 'Re-enter Password',
];
}
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, 'Incorrect username or password.');
}
}
}
protected function getUser()
{
if ($this->_user === null) {
$this->_user = User::findByUsername($this->username);
}
return $this->_user;
}
}
This is controller ProfileController.php
public function actionResetProfilePassword()
{
$resetpasswordmodel = new ResetProfilePasswordForm();
if ($resetpasswordmodel->load(Yii::$app->request->post())) {
$user = User::find()->where(['id' => Yii::$app->user->identity->id])->one();
if($user->validate()){
$user->save(false);
}
}
return $this->render('ResetProfilePassword', [
'resetpasswordmodel' => $resetpasswordmodel
]);
}
Please help me where I am facing the issue.
If this is not the right way to validate, please help me in providing the better way to validate password
To apply resetpasswordmodel validation - just run the validate() method and then - update user model like that:
public function actionResetProfilePassword()
{
$resetpasswordmodel = new ResetProfilePasswordForm();
if ($resetpasswordmodel->load(Yii::$app->request->post())) {
$user = User::find()->where(['id' => Yii::$app->user->identity->id])->one();
# here we run our validation rules on the model
if ($resetpasswordmodel->validate()) {
# if it is ok - setting the password property of user
$user->password = $resetpasswordmodel->changepassword;
# and finally save it
$user->save();
}
return $this->render('ResetProfilePassword', [
'resetpasswordmodel' => $resetpasswordmodel
]);
}
you can create new hash and replace it in database with older password
*note: salt is your email account that you want restore it.
$salt= 'omid.ahmadyani#Outlook.com';
$pass = crypt('00000000',$salt);
die($pass);
my new password is 00000000
and my hashed pass is omXXQw/O/i1po
S F My English!

To fetch data from mysql table using hooks codeigniter

I am new for hooks in codeigniter. I have enabled the hooks in config file.
$config['enable_hooks'] = TRUE;
and then in hooks.php I have written my hook that is like below
$hook['pre_controller'] = array(
'class' => 'MyClass',
'function' => 'Myfunction',
'filename' => 'Myclass.php',
'filepath' => 'hooks',
'params' => '');
AND the class having function is as below
class MyClass {
function MyClass() {
$this->CI = &get_instance();
require_once(APPPATH . 'config/database.php');
}
function Myfunction() {
$record = $this->CI->db->SELECT('*')
->FROM('currency')
->get()
->result();
echo "<pre>";
print_r($record);
die;
}}
but i am getting a blank page. please tell me what is wrong with me.
I think your main problem was in this area.
function MyClass() {
$this->CI = &get_instance();
require_once(APPPATH . 'config/database.php');
}
Try
Note: codeigniter 3 versions are case sensitive should be first letter upper case only on class and file name.
application > hooks > My_class.php
<?php
class My_class {
public function __construct() {
$this->CI = &get_instance();
// Auto load database
// require_once(APPPATH . 'config/database.php');
}
public function my_function() {
$query = $this->CI->db->get('currency');
$record = $query->result_array();
echo "<pre>";
print_r($record);
echo "</pre>";
}
}
Config Hook
$hook['pre_controller'] = array(
'class' => 'My_class',
'function' => 'my_function',
'filename' => 'My_class.php',
'filepath' => 'hooks',
);
Autoload the database better option
$autoload['libraries'] = array('database');
Codeigniter Hooks

HybridAuth CakePHP3.X,how to save user after successful login?

I have read the description over,
Once a user is authenticated through the provider the authenticator gets the user profile from the identity provider and using that tries to find the corresponding user record in your app's users table. If no user is found and registrationCallback option is specified the specified method from the User model is called. You can use the callback to save user record to database.
But where to define/declare registrationCallback
If you want user to register if not exist then this code will execute :
if (!empty($this->_config['registrationCallback'])) {
$return = call_user_func_array(
[
TableRegistry::get($userModel),
$this->_config['registrationCallback']
],
[$provider, $providerProfile]
);
if ($return) {
$user = $this->_fetchUserFromDb($conditions);
if ($user) {
return $user;
}
}
You need to define the registration function in config ( in __construct) and regarding call_user_func_array read this link - https://php.net/call-user-func-array
To Store user in database after login
1>defines the function in UsersTabel.php
public function registration($provider, $profile) {
$user = $this->newEntity([
'username' => $profile->displayName,
'provider' => $provider,
'provider_uid' => $profile->identifier
]);
if(!$this->save($user))
{
Log::write(LOG_ERR, 'Failed to create new user record');
return false;
}
return true;
}
2>Replace the function of file vendor ▸ admad ▸ cakephp-hybridauth ▸ src ▸ Auth▸ HybridAuthAuthenticate.php
public function __construct(ComponentRegistry $registry, $config)
{
$this->config([
'fields' => [
'provider' => 'provider',
'provider_uid' => 'provider_uid',
'openid_identifier' => 'openid_identifier'
],
'hauth_return_to' => null,
'registrationCallback'=>'registration'
]);
parent::__construct($registry, $config);
}

Auth login not working cakephp 2.5.7 in Server

Hi, Everyone cakephp login works in my localhost, but it doesn't works in
web server.
My localhost server php version 5.5 and mysql server 5.6.
My web server version 5.2.17 and mysql server 5.1.61-rel13.2-log
Below is my controller code.
UsersController.php
public function login(){
$this->layout='userlogin';
if ($this->request->is('post'))
{
if ($this->Auth->login())
{
return $this->redirect($this->Auth->redirect());
}else{
$this->request->data=array();
return $this->Session->setFlash('Invalid username or password, try again','default',array('class'=>'alert alert-danger'),'logerr');
}
}
}
AppController.php
public $components = array(
'RequestHandler','Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'Users', 'action' => 'UserDashboard'),
'logoutRedirect' => array('controller' => 'Users', 'action' => 'login'),
'authError' => 'Did you really think you are allowed to see that?',
'authorize' => array('Controller'),
)
);
Thanks in Advance