Cygnite - A Modern Toolkit For Web Developers

The Elegant Way of Building Full-Featured Web Applications

Cygnite Dynamic Routing

Authentication

Documentation

Authentication Manager

Creating A Model Class For Authentication

You also required a model class in order to authenticate users. Let us assume we are using "User" model to authenticate. Model class should look like below.


namespace Apps\Models;

use Cygnite\Database\Cyrus\ActiveRecord;

class User extends ActiveRecord
{
    //your database connection name
    protected $database = 'cyrus';

    // your table name here
    //protected $tableName = 'user';

    protected $primaryKey = 'id';

    public function __construct()
    {
        parent::__construct();
    }
}

Setting Model For Auth Manager

You must register the src/Apps/Models/User.php model class into Auth manager in order to get the Auth object.


namespace Apps\Controllers;

use Apps\Middleware\Authentication\Auth;
use Cygnite\Mvc\Controller\AbstractBaseController;

class AuthController extends AbstractBaseController
{
    private $auth;

    /**
     * Your constructor.
     *
     * @access public
     *
     */
    public function __construct()
    {
        parent::__construct();
        /*
         | User Model to authenticate user using
         | credentials
         */
        $this->auth = Auth::model('\Apps\Models\User');
    }

}

Authenticating Users

By default skeleton application shipped with src/Apps/Controllers/AuthController for authentication out of box. AuthController helps you to authenticate and login into the application.

Verify User Credentials Without Login

Some time you may wish to just verify user credentials against database without actually login into the application. In such cases you can use verify method to validate credentials.



 public function checkAction(Request $request)
 {
    $credentials = ['email' => $email, 'password' => $password];

    if ($this->auth->verify($credentials)) {

      //......
    }

 }


Logging In A User / Create User Session

If user credentials are verified and you would like to set current user session, you may simply use login method.


 public function checkAction(Request $request)
 {
     $credentials = ['email' => $email, 'password' => $password];

     if ($this->auth->verify($credentials)) {

        $this->auth->login(); // will login current user and create session
     }
 }


Logging In A User Directly

If you wish to validate and login given user directly then you may set the credential before using login method. This method is equivalent to verify using credentials.


    public function checkAction(Request $request)
    {
         $credentials = ['email' => $email, 'password' => $password];

         if ($this->auth->credential($credentials)->login() ) {

            //........
         }
    }


Logging In A User With Conditions

You may also wish to perform extra check to authenticate user and login. For example, only active user with email and password can login.


 $credentials = [
       'email' => $email, 'password' => $password, 'status' => '1'
 ];

 if ( $this->auth->credential($credentials)->login() ) {

    // User is active user and exists
 }

 Or

 // In this case your user  table should have 'username' 'password' 'status' columns
 if ( $this->auth->verify($username, $password, $status)->login() ) {

    // User is active user and exists
 } 


Your check action looks like below.



    /**
     * Authenticate user and login into the system
     *
     */
    public function checkAction(Request $request)
    {
        $crypt = new Encrypt;

        //$this->logoutAction();
        $credentials = [
            'username' => $request->post->get('username'),
            'password' => $crypt->encode($request->post->get('password'))
        ];

        if ($this->auth->credential($credentials)->login()) {
            //$this->auth->login();
            $userInfo = $this->auth->userInfo();
            return Response::json(['status' => true, 'user' => $userInfo]);
        }

        return ['status' => false, 'user' => []];
    }

Getting Current User Information

You may want to access the current user session information to do some action.


  if ($this->auth->verify($credentials)) {

    $this->auth->login();
    $userInfo = $this->auth->userInfo(); // Get the current session informations
 }


Check If A User Is Authenticated

You may use isLoggedIn method to determine if user already logged into the application.


 
 if ($this->auth->isLoggedIn()) {

    // User already logged in and session exists
 }


Log Out Current User

You may use logout method to logout from the application.


 
 $this->auth->logout();// Logout and redirect to base url

 public function logoutAction()
 {
     $this->auth->logout(false); //logout but won't redirect to home page /baseurl.

     return ['status' => true, 'user' => []];
 }


Your final AuthController will look like below.

 
namespace Apps\Controllers;

use Cygnite\Common\Encrypt;
use Apps\Middleware\Authentication\Auth;
use Cygnite\Http\Requests\Request;
use Cygnite\Http\Responses\Response;
use Cygnite\Mvc\Controller\AbstractBaseController;

class AuthController extends AbstractBaseController
{
    protected $templateEngine = false;
    private $auth;

    /**
     * Your constructor.
     *
     * @access public
     */
    public function __construct()
    {
        parent::__construct();
        // Set the user model to authenticate user
        $this->auth = Auth::model('\Apps\Models\User');
    }

    /**
     * Authenticate user and login into the system
     *
     * @param \Cygnite\Http\Requests\Request $request
     * @return array
     */
    public function checkAction(Request $request)
    {
        $crypt = new Encrypt;
        $credentials = [
            'username' => $request->post->get('username'),
            'password' => $crypt->encode($request->post->get('password'))
        ];

        if ($this->auth->credential($credentials)->login()) {
            $userInfo = $this->auth->userInfo();
            return ['status' => true, 'user' => $userInfo];
        }

        return ['status' => false, 'user' => []];
    }

    /**
     * Destroy the session and Logout the user.
     *
     * @return \Cygnite\Http\Responses\JsonResponse
     */
    public function logoutAction()
    {
        $this->auth->logout(false);
        return Response::json(['status' => true, 'user' => []]);
    }
}

 
 

Routing To Auth Controller

Add a below route entry in your src/Apps/Routing/Routes.php file.

 
 use Cygnite\Http\Responses\RedirectResponse;

 $app->router->any('/authenticate/', function ($router) {

    $request = $router->request();
    $auth = $router->callController(["Auth@check", [$request]]);

    if ($auth['status'] !== false) {
        return new RedirectResponse($request->getBaseUrl().'home/index');
    }

    return new RedirectResponse($request->getBaseUrl().'home/login');

 });
 
 
Follow Us On Facebook Twitter Google+ Linkedin
Released Under The MIT Public License. Copyrights @2012-2017. Powered by- Sanjoy Dey Productions.