<commit_before><?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use app\models\User;
use yii\data\ActiveDataProvider;
use yii\web\NotFoundHttpException;

class UserController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                    'rules' => [
                        [
                            'actions' => ['index', 'create', 'update'],
                            'allow' => true,
                            'roles' => ['userManager'],
                        ]
                    ],
                ],
            ];
    }

    /**
     * List all users.
     */
    public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => User::find()->orderBy('LOWER(email)'),
                'pagination' =>  [
                    'pageSize' => 20,
                ]
            ]);
        return $this->render('index', ['dataProvider' => $dataProvider]);
    }

    /**
     * Create a new user.
     * If creation is successful, the browser will be redirected to the 
     * 'update' page.
     */
    public function actionCreate()
    {
        $model = new User();
        if(null !== (Yii::$app->request->post()))
        {
            if($this->saveUser($model))
            {
                Yii::$app->session->setFlash('userUpdated');
                $this->redirect(['update', 'id' => $model->getId()]);
                return;
            }

        }

        return $this->render('create', ['model' => $model]);
    }

    public function actionUpdate($id)
    {
        $model = User::findOne(['id' => $id]);
        if(null === $model)
        {
            throw new NotFoundHttpException(Yii::t('ica_auth', 'No such user.'));
        }

        if($this->saveUser($model))
        {
            Yii::$app->session->setFlash('userUpdated');
        }
        
        return $this->render('update', ['model' => $model]);
    }

    /**
     * Save a user to a model.
     * @param $model the model to save
     * @return whether saving was successful or not
     */
    private function saveUser($model)
    {
        if(null === $model)
        {
            throw new Exception('No model supplied.');
        }

        if(null === Yii::$app->request->post())
        {
            return false;
        }

        $canSave = true;
        $newPassword = null;
        if(isset(Yii::$app->request->post()['User']['password']))
        {
            $passwordConfirm = '';
            if(isset(Yii::$app->request->post()['password_confirm']))
            {
                $passwordConfirm = Yii::$app->request->post()['password_confirm'];
            }
            if($passwordConfirm != Yii::$app->request->post()['User']['password'])
            {
                $model->addError('password', Yii::t('ica_auth', 'Passwords don\'t match.'));
                $canSave = false;
            }
            else
            {
                $newPassword = Yii::$app->request->post()['User']['password'];
            }
        }

        if( ! $canSave )
        {
            return false;
        }

        if(! isset(Yii::$app->request->post()['User']))
        {
            if(null === $newPassword)
            {
                return false;
            }
            $model->setPassword($newPassword);
            return $model->save(true, ['password_hash']);
        }

        if(null !== $newPassword)
        {
            $model->setPassword($newPassword);
            if(! $model->validate(['password_hash']))
            {
                return false;
            }
        }

        $model->email = Yii::$app->request->post()['User']['email'];
        if(! $model->save(true, ['email', 'password_hash']))
        {
            return false;
        }

        if(isset(Yii::$app->request->post()['auth_items'])
            && is_array(Yii::$app->request->post()['auth_items']))
        {
            $allAssignmentsValid = true;
            foreach(Yii::$app->request->post()['auth_items'] as $roleName)
            {
                if(null === Yii::$app->getAuthManager()->getRole($roleName))
                {
                    $allAssignmentsValid = false;
                    break;
                }
            }

            if($allAssignmentsValid)
            {
                Yii::$app->getAuthManager()->revokeAll($model->getId());
                foreach(Yii::$app->request->post()['auth_items'] as $roleName)
                {
                    Yii::$app->getAuthManager()->assign(
                        Yii::$app->getAuthManager()->getRole($roleName),
                        $model->getId());
                }
            }
        }
        
        return true;
    }



}<commit_msg>Fixed bug in controller where password would always be overwritten<commit_after><?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use app\models\User;
use yii\data\ActiveDataProvider;
use yii\web\NotFoundHttpException;

class UserController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                    'rules' => [
                        [
                            'actions' => ['index', 'create', 'update'],
                            'allow' => true,
                            'roles' => ['userManager'],
                        ]
                    ],
                ],
            ];
    }

    /**
     * List all users.
     */
    public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => User::find()->orderBy('LOWER(email)'),
                'pagination' =>  [
                    'pageSize' => 20,
                ]
            ]);
        return $this->render('index', ['dataProvider' => $dataProvider]);
    }

    /**
     * Create a new user.
     * If creation is successful, the browser will be redirected to the 
     * 'update' page.
     */
    public function actionCreate()
    {
        $model = new User();
        if(null !== (Yii::$app->request->post()))
        {
            if($this->saveUser($model))
            {
                Yii::$app->session->setFlash('userUpdated');
                $this->redirect(['update', 'id' => $model->getId()]);
                return;
            }

        }

        return $this->render('create', ['model' => $model]);
    }

    public function actionUpdate($id)
    {
        $model = User::findOne(['id' => $id]);
        if(null === $model)
        {
            throw new NotFoundHttpException(Yii::t('ica_auth', 'No such user.'));
        }

        if($this->saveUser($model))
        {
            Yii::$app->session->setFlash('userUpdated');
        }
        
        return $this->render('update', ['model' => $model]);
    }

    /**
     * Save a user to a model.
     * @param $model the model to save
     * @return whether saving was successful or not
     */
    private function saveUser($model)
    {
        if(null === $model)
        {
            throw new Exception('No model supplied.');
        }

        if(null === Yii::$app->request->post() || ! isset(Yii::$app->request->post()['User']))
        {
            return false;
        }

        $canSave = true;
        // First check if we want to change the password and, if so, if the
        // new password is ok.
        $newPassword = null;
        if(isset(Yii::$app->request->post()['User']['password']) && strlen(Yii::$app->request->post()['User']['password']))
        {
            $passwordConfirm = Yii::$app->request->post()['User']['password'];
            if(isset(Yii::$app->request->post()['password_confirm']))
            {
                $passwordConfirm = Yii::$app->request->post()['password_confirm'];
            }
            if($passwordConfirm != Yii::$app->request->post()['User']['password'])
            {
                $model->addError('password', Yii::t('ica_auth', 'Passwords don\'t match.'));
                $canSave = false;
            }
            // The new password is ok. Allow updating it.
            else
            {
                $newPassword = $password<PASSWORD>;
            }
        }

        if( ! $canSave )
        {
            return false;
        }

        if(null !== $newPassword)
        {
            $model->setPassword($newPassword);
            if(! $model->validate(['password_hash']))
            {
                return false;
            }
        }

        $model->email = Yii::$app->request->post()['User']['email'];
        if(! $model->save(true, ['email', 'password_hash']))
        {
            return false;
        }

        if(isset(Yii::$app->request->post()['auth_items'])
            && is_array(Yii::$app->request->post()['auth_items']))
        {
            $allAssignmentsValid = true;
            foreach(Yii::$app->request->post()['auth_items'] as $roleName)
            {
                if(null === Yii::$app->getAuthManager()->getRole($roleName))
                {
                    $allAssignmentsValid = false;
                    break;
                }
            }

            if($allAssignmentsValid)
            {
                Yii::$app->getAuthManager()->revokeAll($model->getId());
                foreach(Yii::$app->request->post()['auth_items'] as $roleName)
                {
                    Yii::$app->getAuthManager()->assign(
                        Yii::$app->getAuthManager()->getRole($roleName),
                        $model->getId());
                }
            }
        }

        return true;
    }



}
{'fraction_non_alphanumeric': 0.16155419222903886, 'fraction_numerical': 0.00040899795501022495, 'mean_word_length': 1.4434174369223083, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 142, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1345424', 'n_tokens_mistral': 2655, 'n_tokens_neox': 2601, 'n_words': 454}