Yii redirecting the admin and authenticated user to the desired page - yii

I am new to yii. I want my admin upon login from webapp/user/login to redirect to the page I want which is localhost/webapp/story right now it is redirecting me to the index.php.
I have also registered a user and given that user a role which is authenticated and I want that when my user(the authenticated user) logs in via webapp/user/login then that user is redirected to index.php.
so there are two things:
1. redirecting admin to the desired page which is webapp/story.
2. redirecting the authenticated user to index.php.
I am using yii user and right extension. Please help me with this.
The code LoginController is below:
<?php
class LoginController extends Controller
{
public $defaultAction = 'login';
/**
* Displays the login page
*/
public function actionLogin()
{
if (Yii::app()->user->isGuest) {
$model=new UserLogin;
// collect user input data
if(isset($_POST['UserLogin']))
{
$model->attributes=$_POST['UserLogin'];
// validate user input and redirect to previous page if valid
if($model->validate()) {
$this->lastViset();
if (Yii::app()->user->returnUrl=='/index.php')
$this->redirect(Yii::app()->controller->module->returnUrl);
else// yehen par kuch aye ga according
$this->redirect(Yii::app()->user->returnUrl);
}
}
// display the login form
$this->render('/user/login',array('model'=>$model));
} else
$this->redirect(Yii::app()->controller->module->returnUrl);
}
private function lastViset() {
$lastVisit = User::model()->notsafe()->findByPk(Yii::app()->user->id);
$lastVisit->lastvisit = time();
$lastVisit->save();
}
}

I think could be somethings like this
<?php
class LoginController extends Controller
{
public $defaultAction = 'login';
/**
* Displays the login page
*/
public function actionLogin()
{
if (Yii::app()->user->isGuest) {
$model=new UserLogin;
// collect user input data
if(isset($_POST['UserLogin']))
{
$model->attributes=$_POST['UserLogin'];
// validate user input and redirect to previous page if valid
if($model->validate()) {
$this->lastViset();
// Old code commentede
//if (Yii::app()->user->returnUrl=='/index.php')
// $this->redirect(Yii::app()->controller->module->returnUrl);
//else// yehen par kuch aye ga according
// $this->redirect(Yii::app()->user->returnUrl);
// new code
if (UserModule::isAdmin()){
$this->redirect(array('story/index'));
}
else {
$this->redirect(Yii::app()->user->returnUrl);
}
}
}
// display the login form
$this->render('/user/login',array('model'=>$model));
} else
$this->redirect(Yii::app()->controller->module->returnUrl);
}
private function lastViset() {
$lastVisit = User::model()->notsafe()->findByPk(Yii::app()->user->id);
$lastVisit->lastvisit = time();
$lastVisit->save();
}
}

Related

how can I redirect login page if do not login in yii framework?

I have the actionLogin and create cookie like here :
public function actionLogin()
{
$this->layout = 'login';
$model=new LoginForm;
if(isset($_POST['LoginForm']))
{
$model->attributes=$_POST['LoginForm'];
if($model->validate() && $model->login()){
$cookie = new CHttpCookie('loginSuccess',$model->username);
$cookie->expire = 604800;
Yii::app()->request->cookies['loginSuccess'] = $cookie;
$this->redirect('/ktbeauty/index.php/categories/index');
}
}
$this->render('login',array(
'model'=>$model,
));
}
And Now I have some controllers which must check to login before access controllers, if not login, it must redirect to login page, how can I work for this ?
thankyou very much
in the action of your controller you can try something like this
public function actionGoToLogin()
{
if(!Yii::app()->user->isGuest)
{
// do something if user is authenticated
}
else
{
Yii::app()->user->loginRequired();
// or if you want you can redirect using Yii::app()->createUrl('controller/login');
}
}
In Controller, you have a function as below:
public function accessRules() {
Here you can define the actions and users who can access those functions.
If you are not logged in, then it'll redirected to login page by default.
This feature available by default in YII.
check this URL:
http://www.yiiframework.com/wiki/169/configuring-controller-access-rules-to-default-deny/

How to set default action dynamically in Yii

i want to change default action of a controller depends on which user is logged in.
Ex. There are two users in my site : publisher and author and i want to set publisher action as default action when a publisher is logged in, and same for author.
what should i do? when can I check my roles and set their relevant actions?
Another way to do this would be setting the defaultAction property in your controller's init() method. Somewhat like this:
<?php
class MyAwesomeController extends Controller{ // or extends CController depending on your code
public function init(){
parent::init(); // no need for this call if you don't have anything in your parent init()
if(array_key_exists('RolePublisher', Yii::app()->authManager->getRoles(Yii::app()->user->id)))
$this->defaultAction='publisher'; // name of your action
else if (array_key_exists('RoleAuthor', Yii::app()->authManager->getRoles(Yii::app()->user->id)))
$this->defaultAction='author'; // name of your action
}
// ... rest of your code
}
?>
Check out CAuthManager's getRoles(), to see that the returned array will have format of 'role'=>CAuthItem object, which is why i'm checking with array_key_exists().
Incase you don't know, the action name will be only the name without the action part, for example if you have public function actionPublisher(){...} then action name should be: publisher.
Another, simpler, thing you can do is keep the default action the same, but that default action simply calls an additional action function depending on what kind of user is logged in. So for example you have the indexAction function conditionally calling this->userAction or this->publisherAction depending on the check for who is logged in.
I think you can save "first user page" in user table. And when a user is authenticated, you can load this page from database. Where you can do this? I think best place is UserIdentity class. After that, you could get this value in SiteController::actionLogin();
You can get or set "first page" value:
if (null === $user->first_page) {
$firstPage = 'site/index';
} else {
$firstPage = $user->first_page;
}
This is a complete class:
class UserIdentity extends CUserIdentity
{
private $_id;
public function authenticate()
{
$user = User::model()->findByAttributes(array('username' => $this->username));
if ($user === null) {
$this->errorCode = self::ERROR_USERNAME_INVALID;
} else if ($user->password !== $user->encrypt($this->password)) {
$this->errorCode = self::ERROR_PASSWORD_INVALID;
} else {
$this->_id = $user->id;
if (null === $user->first_page) {
$firstPage = 'site/index';
} else {
$firstPage = $user->first_page;
}
$this->errorCode = self::ERROR_NONE;
}
return !$this->errorCode;
}
public function getId()
{
return $this->_id;
}
}
/**
* 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->first_page);
}
// display the login form
$this->render('login', array('model' => $model));
}
Also, you can just write right code only in this file. In SiteController file.

Symfony 2 & FOSUserBundle : authenticate user after resetting password

When overriding FOSUserBundle resetting password controller, there is a function call to "authenticateUser" method (line 104) :
https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Controller/ResettingController.php#L104
....
$this->authenticateUser($user);
....
My problem is that I already override the Symfony authentication handler, and have my own logic when a user logs in.
EDIT
Here is my authentication handler :
<?php
/* ... all includes ... */
class AuthenticationHandler implements AuthenticationSuccessHandlerInterface, LogoutSuccessHandlerInterface
{
private $router;
private $container;
public function __construct(Router $router, ContainerInterface $container)
{
$this->router = $router;
$this->container = $container;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
// retrieve user and session id
$user = $token->getUser();
/* ... here I do things in database when logging in, and dont want to write it again and again ... */
// prepare redirection URL
if($targetPath = $request->getSession()->get('_security.target_path')) {
$url = $targetPath;
}
else {
$url = $this->router->generate('my_route');
}
return new RedirectResponse($url);
}
}
So, How could I call the "onAuthenticationSuccess" method from my authentication handler in the ResettingController ?
In order to avoid rewriting the same code...
Thanks for your help !
Aurel
You should call your onAuthenticationSuccess method loading it as a service. In your config.yml:
authentication_handler:
class: Acme\Bundle\Service\AuthenticationHandler
arguments:
container: "#service_container"
And then, call it in the authenticateUser function:
protected function authenticateUser(UserInterface $user) {
try {
$this->container->get('fos_user.user_checker')->checkPostAuth($user);
} catch (AccountStatusException $e) {
// Don't authenticate locked, disabled or expired users
return;
}
$providerKey = $this->container->getParameter('fos_user.firewall_name');
$token = new UsernamePasswordToken($user, null, $providerKey, $user->getRoles());
$this->container->get('security.context')->setToken($token);
$request = $this->container->get('request');
$this->container->get('authentication_handler')->onAuthenticationSuccess($request, $token);
}
this do the trick and pass through your custom auth handler. More info.

Save user's last log out

I am trying to save user's last logout time into a DB in Yii framework.
I have WebUser as:
<?php
// this file must be stored in:
// protected/components/WebUser.php
class WebUser extends CWebUser {
public function afterLogout()
{
$user=user::Model();
$user->logOutDateTime='TEST';
$user->saveAttributes(array('logOutDateTime'));
parent::afterLogout();
}
}
?>
and in config\main.php I have these lines
// application components
'components'=>array(
'user'=>array(
// enable cookie-based authentication
'class'=>'WebUser',
'allowAutoLogin'=>true,
)
For now I have set logOutDateTime datatype to varchar, to test, and I assume every time user logs out, it should write 'TEST' into database but it does nothing.
Where did I go wrong?
I don't think the afterLogout() still has the Yii::app()->user set, so I would do something like (untested):
public function beforeLogout()
{
if (parent::beforeLogout()) {
$user = User::model()->findByPk(Yii::app()->user->id); // assuming you have getId() mapped to id column
$user->logOutDateTime='TEST';
$user->saveAttributes(array('logOutDateTime'));
return true;
} else {
return false;
}
}
$user = user::Model();
should be:
$user = user::Model()->find(/* model_conditions */);

codeigniter sess_destroy() not working properly,what m i doing wrong?

I am a newbie in codeigniter. I am using an an login form to login as an admin. When the admin logs in with the correct user name and password s/he is directed to the home page with a session variable.and then if he clicks the log out button the session is supposed to be destroyed and redirect the user to log in page i.e log in form page.
The 1st controller is admin:
<?php
class Admin extends CI_Controller
{
function index()
{
$data['main_content'] = 'admin/log_in';
$this -> load -> view('includes/admin/admin_template', $data);
}
function log_in()
{
$this->load->model('admin_model');
$query = $this -> admin_model -> validate();
if ($query)// if the user's credentials validated...
{
$data = array('user_name' => $this -> input -> post('user_name'), 'is_logged_in' => true);
$this -> session -> set_userdata($data);
redirect('admin/home/admin_home');
} else// incorrect username or password
{
$this -> index();
}
}
function log_out()
{
$this->session->sess_destroy();
redirect('/admin/admin','refresh');
}
}
The second controller is the home controller:
<?php
class Home extends CI_Controller
{
function __construct()
{
parent:: __construct();
$this->is_logged_in();
}
function is_logged_in()
{
$is_logged_in = $this -> session -> userdata('is_logged_in');
if (!isset($is_logged_in) || $is_logged_in != true)
{
$this -> load -> view('admin/forbidden');
}
}
function admin_home()
{
$data['main_content'] = 'home_view';
$this->load->view('admin/home_view');
}
}
The model is admin_model:
<?php
class Admin_model extends CI_Model
{
function __construct()
{
parent:: __construct();
}
function validate()
{
$this->db->where('user_name',$this->input->post('user_name'));
$this->db->where('password', $this->input->post('password'));
$query = $this->db->get('user');
if($query->num_rows==1)
{
return true;
}
}
}
Now, it supposed the user to logout and destroy the session, but if I click the back button of my browser I can get page back which was supposed not to be and the session is not destroyed.
please tell me what I am doing wrong here. I am using codeigniter 2.1.0.
after going through all the troubles and searching in various places i have finally found a proper solution to this question.the problem arrived because the browser was showing the cached pages.it was not the session that was creating the problem and it was working properly.
here is the solution:
in the home controller adding a function to clear the cache and calling it in the constructor function does the trick :)
here is the home controller with the solution:
<?php
class Home extends CI_Controller
{
function __construct()
{
parent:: __construct();
$this->is_logged_in();
$this->clear_cache();
}
function is_logged_in()
{
if (!$this->session->userdata('is_logged_in'))
{
redirect('/admin/admin');
}
}
function clear_cache()
{
$this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate, no-transform, max-age=0, post-check=0, pre-check=0");
$this->output->set_header("Pragma: no-cache");
}
function admin_home()
{
$data['main_content'] = 'home_view';
$this->load->view('admin/home_view');
}
}
now thanks goes to this link " logout feature in code igniter ",here is where i have found the solution and it works perfectly :)
If you logout then although the session is destroyed, the session userdata remains for the duration of the current CI page build.
As a precautionary measure you should do:
function log_out()
{
$this->session->sess_destroy();
// null the session (just in case):
$this->session->set_userdata(array('user_name' => '', 'is_logged_in' => ''));
redirect('/admin/admin');
}
See: http://codeigniter.com/forums/viewthread/110993/P130/#662369