Is It Good To Keep Auth Code In Model?

I confused about keeping authentication code in model.

On the one hand it’s very comfortable because we can write all the code in one place - in model.

For example, in afterValidate method of any CActiveRecord class we can write something like:


if ($this->scenario == 'login') {

    $idenity = new UserIdentity($this->username, $this->password);

    if ($identity->authenticate()) {

        Yii::app()->user->login($identity);        

    }

    else {

        switch ($identity->errorCode) {

            case(UserIdentity::ERROR_USERNAME_INVALID):

                $this->addError('username', 'Invalid username!');

            break;

            ...

        }

    }

}

But on the other hand model should only be dealing with processing and Create-Read-Update-Delete operations (authentication doesn’t belong to any of this). From a position of MVC authentication code should be in Controller.

So what do you think about the problem? Where do you keep your authentication code?

Well its a nice discussion you have started here.I like it :)

I am just going to add a few line in your explanation which will be probably answer for your question.

According to me we can treat a model as a single entity which is handling all the features,operations related to model.That’s why generally i never move that code from model class.

And suppose if there is some additional methods required related to model according to our business logic then diffidently i will write that code in model class not in any other class or helper.

In this way you can separately define a code for specific business logic with a related model class. And i guess this will be better Approach for MVC.

What you think about it.:)

Thanks and Regards

Models are not only for CRUD operations. Those are specific to ORM which is kind of model, but not the only one. Models in MVC should encapsulate business logic and authentication is a business logic after all.

There are also two approaches: thin controller and fat controller. First one says you should put everything in models and actions should be as simple as possible. The other assumes there can be more code in actions however still it is recommended to put reusable code and code specific to some model in related models.

codesutra, redguy, thank you! I carefully read your answers.

As a result in case with fat model we should keep authentication code in model (or maybe we can create one base model and extend it in many different models for different purposes). And there’s no need to place authentication code in controller. Am I right?

your welcome :)