Yii Framework Forum: [SOLVED]User Login With DB - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

[SOLVED]User Login With DB Login details stored inside DB Rate Topic: -----

#1 User is offline   ejgomez 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 94
  • Joined: 14-June 11

Posted 23 June 2011 - 08:27 AM

I want to login using the details stored inside a DB.After going through several topics and forums. i edited my Useridentity.php and Login.php files. But nothing is working for me.Can someone pls help.


My useridentity code
public function authenticate()
	{
			$user = TblUser::model()->findByAttributes(array('username'=>$this->username));

		if ($user===null) {
			$this->errorCode=self::ERROR_USERNAME_INVALID;
		} else if ($user->password !== SHA1($this->password) ) { 
			$this->errorCode=self::ERROR_PASSWORD_INVALID;
		} else { // Okay!
		    $this->errorCode=self::ERROR_NONE;
		   
		    
		}
		return !$this->errorCode;
	}



loginform.php

public function rules()
{
	return array(
		array('username, password', 'required'),
		array('password', 'authenticate'),
	);
}

	
	public function authenticate($attribute,$params)
	{
		if(!$this->hasErrors())  // we only want to authenticate when no input errors
		{
			$identity=new UserIdentity($this->username,$this->password);
			$identity->authenticate();
			switch($identity->errorCode)
			{
				case UserIdentity::ERROR_NONE:
					Yii::app()->user->login($identity);
					break;
				case UserIdentity::ERROR_USERNAME_INVALID:
					$this->addError('username','Username is incorrect.');
					break;
				default: // UserIdentity::ERROR_PASSWORD_INVALID
					$this->addError('password','Password is incorrect.');
					break;
			}
		}
	}


sitecontroller.php
public function actionLogin()
	{
		$model=new LoginForm;

		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			
			if($model->validate() && $model->login())
				$this->redirect(Yii::app()->user->returnUrl);
		}
		$this->render('login',array('model'=>$model));
	}

0

#2 User is offline   kiran sharma 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 429
  • Joined: 21-May 11
  • Location:India

Posted 23 June 2011 - 09:32 AM

Hi , refer following steps.

step : 1

first you have to override id using getId() function , I post here working code of UserIdentity ,

class UserIdentity extends CUserIdentity
{
   private $_id;
   public function authenticate()
   {
       $record=Employee::model()->findByAttributes(array('E_EMAIL'=>$this->username));  // here I use Email as user name which comes from database
       if($record===null)
               {
                       $this->_id='user Null';
         			   $this->errorCode=self::ERROR_USERNAME_INVALID;
               }
       else if($record->E_PASSWORD!==$this->password)            // here I compare db password with passwod field
               {        $this->_id=$this->username;
                       $this->errorCode=self::ERROR_PASSWORD_INVALID;
               }
	 else if($record['E_STATUS']!=='Active')                //  here I check status as Active in db
               {        
			   		$err = "You have been Inactive by Admin.";
			        $this->errorCode = $err;
               }
	
       else
       {  
          $this->_id=$record['E_NAME'];
	   $this->setState('title', $record['E_NAME']);
           $this->errorCode=self::ERROR_NONE;

       }
       return !$this->errorCode;
   }

   public function getId()       //  override Id
   {
       return $this->_id;
   }
}




step : 2
here is my loginForm function ,

public function authenticate($attribute,$params)
	{
		if(!$this->hasErrors())
		{
			$this->_identity=new UserIdentity($this->username,$this->password);
			if(!$this->_identity->authenticate())
				$this->addError('password','Incorrect username or password.');
		}
	}


step : 3
finaly i use controller as ,

public function actionLogin()
	{
		$model=new LoginForm;
		
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		if(isset($_POST['LoginForm']))
		{
		
			$model->attributes=$_POST['LoginForm'];
			
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login())
			{
                          $this->redirect(array("page_after_login"));
			
			}
				
		}
                	$this->render('login',array('model'=>$model));
}

Thanks,
Kiran Sharma.
1

#3 User is offline   ejgomez 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 94
  • Joined: 14-June 11

Posted 24 June 2011 - 12:55 AM

Thanx a lot for the reply..


Fixed it.
0

#4 User is offline   saham 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 11
  • Joined: 02-February 12

Posted 02 February 2012 - 10:27 AM

I am not sure where I have to put this post so I decided to reply this is topic.
I have generated Model and CRUD with gii and as you know it comes with to username/password pairs namely
admin/admin and demo/demo. I have 2 questions:

1. How can we have more than two userename/password pairs with separate task assign to each. For example, I want to define two other usernames/password like user1/user1 and user2/user2. I want user 1 to be able to view and add and user2 view/add/delete.

2. What if I dont want to set usernames and password UserIdentity.php and instead, want to retrieve from a Database? The simplest table is a table with two columns, User name and password.

I am really beginner to Yii and Gii so this question may look like straight forward.
Thank you
0

#5 User is offline   kiran sharma 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 429
  • Joined: 21-May 11
  • Location:India

Posted 30 May 2012 - 09:25 AM

Yes saham here is your answer,
First refer above code for user login from database,

now as i post in step:1 see else part,

else
       {  
          $this->_id=$record['E_NAME'];
           $this->setState('title', $record['E_NAME']);
           [b]$this->setState('userType', $record['userType']); [/b]  // by here you can set state define in db ( admin or normal user )
           $this->errorCode=self::ERROR_NONE;

       }


now you have to use your controller for page redirect at different location by userType, see below code for controller

if($model->validate() && $model->login())
			{
				if(Yii::app()->user->userType=='Admin'){        // we had set above
					$this->redirect(array("index"));
				}elseif(Yii::app()->user->userType=='User'){
					$this->redirect(array("home"));
				}
			}


simple.. :)
Thanks,
Kiran Sharma.
0

#6 User is offline   mint 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 1
  • Joined: 20-June 12

Posted 20 June 2012 - 03:26 AM

I had the same problem and follwed your steps to authenticate user from database but it did'nt workout for me. I had store value directly in the database uing inser query and not using the framework.

UserIdentity.php
<?php

/**
* UserIdentity represents the data needed to identity a user.
* It contains the authentication method that checks if the provided
* data can identity the user.
*/
class UserIdentity extends CUserIdentity
{
private $_id;
/**
* Authenticates a user using the User data model.
* @return boolean whether authentication succeeds.
*/
public function authenticate()
{
$user=User::model()->findByAttributes(array('username'=>$this->username));
if($user===null)
{
$this->errorCode=self::ERROR_USERNAME_INVALID;
}
else if($user->password!==$this->password)
{
$this->errorCode=self::ERROR_PASSWORD_INVALID;
}
else
{
$this->_id = $user->id;
$this->errorCode == self::ERROR_NONE;
}

return !$this->errorCode;
}

public function getId()
{
return $this->_id;
}
}

LoginForm.php
<?php

/**
* LoginForm class.
* LoginForm is the data structure for keeping
* user login form data. It is used by the 'login' action of 'SiteController'.
*/
class LoginForm extends CFormModel
{
public $username;
public $password;
public $rememberMe=false;

private $_identity;

/**
* Declares the validation rules.
* The rules state that username and password are required,
* and password needs to be authenticated.
*/
public function rules()
{
return array(
// username and password are required
array('username, password', 'required', 'on'=>'login'),
// rememberMe needs to be a boolean
array('rememberMe', 'boolean'),
// password needs to be authenticated
array('password', 'authenticate'),
);
}

/**
* Declares attribute labels.
*/
public function attributeLabels()
{
return array(
'rememberMe'=>'Remember me next time',
);
}

/**
* Authenticates the password.
* This is the 'authenticate' validator as declared in rules().
*/
public function authenticate($attribute,$params)
{

$this->_identity=new UserIdentity($this->username,$this->password);
if(!$this->_identity->authenticate())
$this->addError('password','Incorrect username or password.');



}
/**
* Logs in the user using the given username and password in the model.
* @return boolean whether login is successful
*/
public function login()
{
if($this->_identity===null)
{
$this->_identity=new UserIdentity($this->username,$this->password);
$this->_identity->authenticate();
}
if($this->_identity->errorCode===UserIdentity::ERROR_NONE)
{
$duration=$this->rememberMe ? 0 : 0;
Yii::app()->user->login($this->_identity,$duration);
return true;
}
else
return false;
}
}

SiteController.php
<?php

class SiteController extends Controller
{
/**
* Declares class-based actions.
*/
public function actions()
{
return array(
// captcha action renders the CAPTCHA image displayed on the contact page
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
),
// page action renders "static" pages stored under 'protected/views/site/pages'
// They can be accessed via: index.php?r=site/page&view=FileName
'page'=>array(
'class'=>'CViewAction',
),
);
}

/**
* This is the default 'index' action that is invoked
* when an action is not explicitly requested by users.
*/
public function actionIndex()
{
// renders the view file 'protected/views/site/index.php'
// using the default layout 'protected/views/layouts/main.php'
$this->render('index');
}

/**
* This is the action to handle external exceptions.
*/
public function actionError()
{
if($error=Yii::app()->errorHandler->error)
{
if(Yii::app()->request->isAjaxRequest)
echo $error['message'];
else
$this->render('error', $error);
}
}

/**
* Displays the contact page
*/
public function actionContact()
{
$model=new ContactForm;
if(isset($_POST['ContactForm']))
{
$model->attributes=$_POST['ContactForm'];
if($model->validate())
{
$headers="From: {$model->email}\r\nReply-To: {$model->email}";
mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);
Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
$this->refresh();
}
}
$this->render('contact',array('model'=>$model));
}

/**
* Displays the login page
*/
public function actionLogin()
{
$model=new LoginForm;

// if it is ajax validation request
if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}

// collect user input data
if(isset($_POST['LoginForm']))
{
$model->attributes=$_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
if($model->validate() && $model->login())
$this->redirect(Yii::app()->user->returnUrl);
}
// display the login form
$this->render('login',array('model'=>$model));
}

/**
* Logs out the current user and redirect to homepage.
*/
public function actionLogout()
{
Yii::app()->user->logout();
$this->redirect(Yii::app()->homeUrl);
}
}
0

#7 User is offline   Haviator 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 2
  • Joined: 12-December 12

Posted 13 December 2012 - 01:48 AM

Hi everybody , I'm new to yii , and thnaks to your help i managed to get the user login through my database working , but know i can't logout anymore as it shows me a page with message this when I click logout
Error 404 
The system is unable to find the requested action "logout".


The exception generated is

06:46:55.130893	error	exception.CHttpException.404	
exception 'CHttpException' with message 'The system is unable to find the
requested action "logout".' in

#0 C:\wamp\www\YiiRoot\framework\web\CController.php(271):
CController->missingAction('logout')
#1 C:\wamp\www\YiiRoot\framework\web\CWebApplication.php(283):
CController->run('logout')
#2 C:\wamp\www\YiiRoot\framework\web\CWebApplication.php(142):
CWebApplication->runController('site/logout')
#3 C:\wamp\www\YiiRoot\framework\base\CApplication.php(162):
CWebApplication->processRequest()
#4 C:\wamp\www\ChefsClub\index.php(15): CApplication->run()
#5 {main}

REQUEST_URI=/ChefsClub/index.php/site/logout
HTTP_REFERER =localhost/ChefsClub/index.php/site/page?view=about

---



What have I done wrong ?
0

#8 User is offline   Haviator 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 2
  • Joined: 12-December 12

Posted 13 December 2012 - 02:15 AM

View PostHaviator, on 13 December 2012 - 01:48 AM, said:

Hi everybody , I'm new to yii , and thnaks to your help i managed to get the user login through my database working , but know i can't logout anymore as it shows me a page with message this when I click logout
Error 404 
The system is unable to find the requested action "logout".


The exception generated is

06:46:55.130893	error	exception.CHttpException.404	
exception 'CHttpException' with message 'The system is unable to find the
requested action "logout".' in

#0 C:\wamp\www\YiiRoot\framework\web\CController.php(271):
CController->missingAction('logout')
#1 C:\wamp\www\YiiRoot\framework\web\CWebApplication.php(283):
CController->run('logout')
#2 C:\wamp\www\YiiRoot\framework\web\CWebApplication.php(142):
CWebApplication->runController('site/logout')
#3 C:\wamp\www\YiiRoot\framework\base\CApplication.php(162):
CWebApplication->processRequest()
#4 C:\wamp\www\ChefsClub\index.php(15): CApplication->run()
#5 {main}

REQUEST_URI=/ChefsClub/index.php/site/logout
HTTP_REFERER =localhost/ChefsClub/index.php/site/page?view=about

---



What have I done wrong ?


Problem Solved now .I figured out that I accidently deleted the logout function :P
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users