I am trying to create a simple login using Yii Here is my auth controller
class AuthController extends Controller
{
/**
* Declare class-based actions.
*/
public function actionLogin()
{
$model = new LoginForm;
$post = Yii::app()->request->getPost('LoginForm');
// If form is submitted
if($post) {
$identity = new UserIdentity($post['username'], $post['password']);
echo $identity->testing();
if($identity->authenticate()) {
echo 'yes';
} else {
echo 'no';
}
exit;
}
$this->render('login', array('model' => $model));
}
}
And here is my UserIdentity
class UserIdentity extends CUserIdentity
{
private $_id;
public function authenticate()
{ echo 'testing';
$user = LoginForm::model()->findByAttributes(array('username' => $this->username));
if(is_null($user)) {
%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;
}
function getId()
{
return $this->_id;
}
}
I have mentioned echo 'yes' and echo 'no' but both are not displaying. How to correct it
Well first of all, you won't even see those echo statements, the only things that are rendered visually for an end-user to see in Yii are the "views". For my login code, which is just a little bit different from yours, after confirming authentication, my app is redirected to home page. Your custom UserIdentity file looks fine, but again, that echo statement won't even be seen. This UserIdentity file is just for performing custom user authentication behind the scenes.
In my UserController (as opposed to your AuthController), my actionLogin is:
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);
}
}
$this->render('/user/login',array('model'=>$model));
}
From the above, for example, you could redirect to the previous page you were at or redirect to your main site view at "/site/index" and under that have some code that does some arbitrary functions or print out HTML depending on if you're logged in or not. An overly simple site view example:
<?php
/* #var $this SiteController */
if (Yii::app()->user->isGuest)
{
// Do stuff here if user is guest.
echo 'User is a guest.';
}
else
{
// Do stuff here if user is authenticated.
echo 'User is authenticated.';
}
?>
Related
I am working on login and search functionality using CodeIgniter.
What Exactly I am doing?
When the user searches something in the search form and on submitting that form I put a check if the user is logged in then it will directly show the result & if the user is not logged in then it redirects the user to the login page and I saved the search data in session as search_session_data.
I have a controller which redirects user regarding the session. If the user came directly to the login page then the user is redirected to the dashboard after login. but if the user is coming from search page then the user is redirected to the search result page after login.
I have mentioned the problem inside the code with a comment.
This is the controller:
public function get_the_search_result() {
$search_session_data = $this->session->userdata('search_session_data');
$this->load->model ('my_model');
$result_data = $this->my_model->find_data_regarding_search_criteria($search_session_data);
$this->load->view ('app/app_statch_result',['result_data' => $result_data,]);
}
public function login_function() {
//necessary login code
if ($this->session->userdata('search_session_data')) {
//Here I want the if `search_session_data` available in session then
// user goest to `get_the_search_result` and view the
//'app/app_statch_result` but it is not working.
$this->get_the_search_result();
} else {
return redirect('dashboard');
}
}
So How do I redirect the user to app_statch_result from
login_function function?
Any suggestion regarding improvement is applicable. Thanks
If I were you, I would do the following:
Create login controller, or better, library and put all login logic inside that class. Then you can load that library from any controller... For example:
Sample library
class User_controll{
private $CI;
public function __construct() {
$this->CI = &get_instance();
}
public function check_user_data($username, $password) {
$tmpId;
// To increase security you can encrypt password
$user = $this->CI->db->from('users')->where(array('username' => $username, 'password' => $password))->get()->result();
if(count($user) == 1){
$this->CI->session->set_userdata('loggedIn', 1);
redirect('user_page');
}
}
protected function logout() {
$this->CI->session->set_userdata('loggedIn', 0);
}
public function isLoggedIn() {
return $this->CI->session->userdata('loggedIn') == 1;
}
}
Sample Controller
class User_page extends CI_Controller{
public function __construct() {
parent::__construct();
$this->load->library('User_controll');
}
public function index() {
if(!$this->user_controll->isLoggedIn()){
redirect('user_page/loginForm');
}
else {
// do whatever you want
}
}
}
I have a action which i am calling it two time
Controller.php
UserController extends Controller {
public actionCopy($id = false){
if($id){
//redireting to a view
}
else{
//rediredtion to a differnet view
}
}
}
I am getting a id first then from first view i am again coming to Copy action with no id so else part is running nw but in this i want to get the $id which i get from first request.
I have tried to define a global variable in controller like
Controller.php
UserController extends Controller {
public $user;
public actionCopy($id= false){
if($id){
$this->user = $id;
//redireting to a view
}
else{
echo $this->user ;// but it has nothing
//rediredtion to a differnet view
}
}
}
and set it like this.
I know that if condition is not executing so $id has no value but i set $this->user first time then why it has no value.
Any help is appreaciated
Just try this,
class UserController extends Controller {
public actionCopy($id = false){
if($id){
//set up a session here
Yii::app()->session['_data_id'] = $id;
//remaining code here
}
else{
$id=isset(Yii::app()->session['_data_id'])?Yii::app()->session['_data_id']:NULL; // the id you want from previous request
if($id!=NULL){
//remaining code
unset(Yii::app()->session['_data_id']); //clear it after use
}
}
}
}
Ok, so I haven't had this issue in a while, but I've done most the options I can to resolve this and have read other people's posts. I'm at a lost right now.
After creating the controller, I did the "php ./composer.phar dump-autoload" command, saying it generated successfully, and it's still saying the controller doesn't exist. There are already 3 other controllers in the folder it's in, and each one of those works, it's just this controller that's having the problem.
Code to Controller: (/apps/controllers/api/apiBulkController.php)
class apiBulkController extends BaseController {
private $error;
public function __construct()
{
// Set default values
$this->error = 'false';
}
public function create()
{
$bulk = array();
// Authenticate the user using the api
if (!isset($_SERVER['PHP_AUTH_USER'])) {
$this->authenticate();
} else {
$auth = User::where('username', $_SERVER['PHP_AUTH_USER'])->first();
// Check to see if the user is valid
if(isset($auth->authkey) && $auth->authkey == $_SERVER['PHP_AUTH_PW'])
{
$req = Request::get();
$bulk = new Bulk;
// Add Columns by example below
$bulk->save();
//ex. $Bulk->Name = Request::get(''); $object->column_name = Request;
// Return JSON data
return Response::json(array(
'error' => $this->error
));
}
else
{
echo $_SERVER['PHP_AUTH_USER'].": Your hash seems to be incorrect.";
}
}
}
public function authenticate()
{
header('WWW-Authenticate: Basic realm="User Authentication (Username / Hash)"');
header('HTTP/1.0 401 Unauthorized');
echo "You must enter a valid Login ID and Hash to access this resource\n";
exit;
}
}
You should probably add
namespace api;
at the beginning of your controller
and run controller also using your namespace before class name, for example in Route api\apiBulkController#create instead of apiBulkController#create.
If error changes, you should then alter your class adding namespaces or uses to other classes for example instead of extends BaseController should be extends \BaseController and so on
I have the following controller in ZF1 with a "logout" action:
class DefaultController extends Website_Controller_Action
{
//...
public function logoutAction()
{
try {
if ($this->user && $this->user instanceof \Transfer_User) {
$userLogin = new User_Login();
//set cookie here
$userLogin->logout($this->user);
}
Messages::addSuccess($this->view->translate('success_logout'));
$this->_redirect('/');
} catch (Exception $e) {
$this->_redirect('/');
}
}
//...
}
The action checks if the user is logged in and then does a logout. Before the logout is executed I want to set a cookie with some specific data that is read on the next login.
I tried setcookie(...) and new Zend_Http_Cookie(...) but both of them don't work. Is there any other way to set a cookie on a controller action in ZF1?
Thank you for your answers ;-)
I'm new to Yii PHP Framework and I'm trying to work on a login form. I know there's already a login function on Yii when you install the testdrive app. I just edit it to make login via database and it's not working. I don't have any errors in codes but when I login it always says incorrect password or username. Here's my code.
For UserIdentity.php
class UserIdentity extends CUserIdentity
{
/**
* Authenticates a user.
* The example implementation makes sure if the username and password
* are both 'demo'.
* In practical applications, this should be changed to authenticate
* against some persistent user identity storage (e.g. database).
* #return boolean whether authentication succeeds.
*/
private $_id;
public function authenticate()
{
$record=User::model()->findByAttributes(array('username'=>$this->username));
if($record===null)
$this->errorCode=self::ERROR_USERNAME_INVALID;
else if($record->password!==crypt($this->password,$record->password))
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else
{
$this->_id=$record->id;
$this->setState('title', $record->title);
$this->errorCode=self::ERROR_NONE;
}
return !$this->errorCode;
}
public function getId()
{
return $this->_id;
}
}
Here's for SiteController.php
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));
}
Can you help me out? Thanks!
if your password saved in db text plain dont use crypt
class UserIdentity extends CUserIdentity
{
/**
* Authenticates a user.
* The example implementation makes sure if the username and password
* are both 'demo'.
* In practical applications, this should be changed to authenticate
* against some persistent user identity storage (e.g. database).
* #return boolean whether authentication succeeds.
*/
private $_id;
public function authenticate()
{
$record=User::model()->findByAttributes(array('username'=>$this->username));
if($record===null)
$this->errorCode=self::ERROR_USERNAME_INVALID;
else if($record->password!==$this->password) // changed
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else
{
$this->_id=$record->id;
$this->setState('title', $record->title);
$this->errorCode=self::ERROR_NONE;
}
return !$this->errorCode;
}
public function getId()
{
return $this->_id;
}
}
In your coding, the line
else if($record->password!==crypt($this->password,$record->password))
is comparing the password with string hashing (crypt() makes the string hash/encription).
if you save the password in db without encrypting, you can compare the both user input password and the password you have saved in db directly, no need to apply crypt()
($this->password!==$record->password)
//$this->password - user input
//$record->password - save password from db
Now change the code as
public function authenticate()
{
$record = User::model()->findByAttributes(array('username' => $this->username));
if ($record === null)
$this->errorCode = self::ERROR_USERNAME_INVALID;
else if (trim($this->password)!== $record->password)
$this->errorCode = self::ERROR_PASSWORD_INVALID;
else
{
$this->_id = $record->id;
$this->setState('title', $record->title);
$this->errorCode = self::ERROR_NONE;
}
return !$this->errorCode;
}