Starting with Yii2 - User Authentication

User Management

The Yii2 base projects, Basic and Advanced, comes with a simpleUser authentication and Login system included.

It provides two users, Admin and Demo, which are hard coded into the User model.  It is left to the developer to wire this up into a database or whatever other persistent system you are planning.

Composer Updates

I recently updated a project through composer and found that I could no longer access any of the Admin functions in my application.  On investigation, I found that the Identity object was not being set properly and therefore isGuest was always true.

Cause and Effect

Eventually, I found that it was caused by two things;

Firstly, the Session cookie was corrupted and need to be deleted through the browser.

Secondly, I started getting naming conflicts between the User data model and the User base class \Yii\web\user.  Why oh why has the Yii team called a base class 'User'?  Won't this lead to on-going naming conflicts, even given namespaces???

Rename Your User Model

The simple answer is to rename your User class.  It's only a couple of changes in the Basic application.  

  1. Change the Model name to Users
  2. Within the Users model change the class name to Users
  3. In the LoginForm model, change the reference in the getUser function from $this->_user = User::findByUsername($this->username); to $this->_user = Users::findByUsername($this->username);

Done!

 

 

Did you know you can hire me?

I take on projects of all sizes. From Consulting to large Development Projects.

If you're starting a new Yii project and would like some help to get setup and running or you need some help with a particular module or you just need someone to develop the whole dang thing, then just ask ...


Leave a Comment

twitterfacebookgooglelinkedin https://me.yahoo.com