PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, February 22, 2022

[FIXED] Cakephp 3.x way to check if a user exists in the database

 February 22, 2022     cakephp, cakephp-3.0, php     No comments   

Issue

I want to create a simple check if a user exists in my database just after he is logged on (LDAP Authentication). If he doesn't exist, a record should be created in the db. Is there any standard CakePHP 3.x -way of doing such things? Or I can just create a function in my "users" Controller which checks if a user exists in the db and call it in the end of login() function (if user session has been successfully created)?

public function login(){
        if ($this->request->is('post')){
            $user = $this->Auth->identify();
            if ($user) {
                $this->Auth->setUser($user);
                $this->createStudent($user);
                return $this->redirect($this->Auth->redirectUrl());
            }

            // user is not identified
            $this->Flash->error('Your username or password is not correct');
        }
    }

public function createStudent($user){
        $studExists = $this->Students->find('isExists', ['uid' => $user['uid']]);

    if (!$studExists) {
        $student = $this->Students->newEntity();
        $data = ['id' => $user['uid']];
        $student = $this->Students->patchEntity($student, $data);
        if ($this->Students->save($student)) {
            $this->Flash->success(__('It is your first logon. You have been added to our database!'));
            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error(__('You could not be saved in our database. Please, try again.'));
        }
    }
}

Thank you in advance.


Solution

What you have shown works but a better way would using an event from your LDAP authenticate class to notify that a new user record needs to be created in your app. Your table's createStudent() can be set as a listener callback for that event. Also your LDAP authenticate class should also only return info if a matching record is found in your datbase table, which I don't think is the case currently.

You can refer to this HybridAuthAuthenticate which does similar. The readme of the plugin shows how to setup listener for the event.



Answered By - ADmad
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing