Joomla logout with message - joomla

I'm trying to modify the
'Token Interceptor' system plugin
by joomunited.com
The original plugin redirects on encountering an invalid token error using register_shutdown_function.
I'm trying to get it to:
Log the user out if they are logged in
Redirect to the login page with the invalid token message
Code:
$app = JFactory::getApplication();
if (!JFactory::getUser()->guest)
{
$app->logout();
}
$app->redirect('/index.php', JText::_('JINVALID_TOKEN'), 'warning');
I can successfully log the user out and redirect to the login page but the error message is not being displayed.
How can I retain the message after logging the user out?
i've also tried:
$app->enqueueMessage(JText::_('JINVALID_TOKEN'), 'warning');
but that didn't work either...

The solution I came up with was a variation of Alonzo Turner's 2nd post here.
The plugin redirects to the login page with a parameter passed in the url. The onAfterInitialise event then looks for this parameter and displays a message if it's found.
class PlgSystemTokeninterceptor extends JPlugin
{
public function __construct(&$subject, $config = array())
{
parent::__construct($subject, $config);
$app = JFactory::getApplication();
if (($app->isSite() && $this->params->get('use_frontend')) || ($app->isAdmin() && $this->params->get('use_backend')))
{
register_shutdown_function(array($this,'redirectToLogin'));
}
}
public function redirectToLogin()
{
$content = ob_get_contents();
if($content == JText::_('JINVALID_TOKEN') || $content == 'Invalid Token')
{
$app = JFactory::getApplication();
if (!JFactory::getUser()->guest)
{
$app->logout();
}
$app->redirect(JURI::base().'index.php?invalid_token=true');
return false;
}
}
function onAfterInitialise()
{
$app = JFactory::getApplication();
$invalid_token = $app->input->get('invalid_token', 'false');
if ($invalid_token == 'true')
{
$app->enqueueMessage(JText::_('JINVALID_TOKEN'), 'warning');
}
return true;
}
}

When you logout you destroy the session so you are not going to have the message any more.
This will get you a message on redirect.
$this->redirect = JUri::base() . 'index.php?option=com_users&view=login';
if (!JFactory::getUser()->guest && $app->input->getCmd('option') != 'com_users')
{
$app->enqueueMessage('message', 'warning');
//$app->logout();
$app->redirect($this->redirect);
}
This will not because the session is destroyed
$this->redirect = JUri::base() . 'index.php?option=com_users&view=login';
if (!JFactory::getUser()->guest && $app->input->getCmd('option') != 'com_users')
{
$app->enqueueMessage('message', 'warning');
$app->logout();
$app->redirect($this->redirect);
}
Not tested but
$app->logout()
echo '<div class="">'. JText::_('whatever you want') . '</div>';
$module = JModuleHelper::getModule('login');
$output = JModuleHelper::renderModule($module);
Something like that

Related

Testing laravel routes identify method type

How can I get about a Laravel route if the request is a get or post?
I try to test my laravel routes with the following
public function testRoutes()
{
$app = app();
$routes = $app->routes->getRoutes();
/**
* Test if mynamespace routes are redirected to login page if is not the login page
*/
echo PHP_EOL;
foreach ($routes as $route) {
if(strpos($route->getName(),'mynamespace::' ) !== false ) {
$url = $route->uri;
//$appURL = env('APP_URL') .'/';
$response = $this->get($url);
if((int)$response->status() !== 200 ){
echo $url . ' (FAILED) did not return 200. The response is ' . $response->status();
$this->assertTrue(false);
} else {
echo $url . ' (success ?)';
$this->assertTrue(true);
}
echo PHP_EOL;
}
}
}
but I would like exclude post requests for the moment
As we can see the Route class has a property $methods.
Your solution would look something like:
if (in_array('POST', $route->methods)) continue;
It may be interesting for you to look into the testing provided by Laravel itself. A simple way of testing response testing and much more!
Laravel testing.

Custom Error Message Does Not Display When Redirected If Session Expire

I am working on my login controller with Codeigniter Version 3.0.3 and HMVC
When the user logs on to the admin dashboard it sets a session token and then redirects it to url
http://localhost/projectname/admin/common/dashboard/?token=bf9691a625fbd0c3513ad822b0f76c6efb45e9b535c7b732d1ff006ce17f8734
When the session expires it redirects back to the admin page And should display message on login page. I am
trying to set a $data variable message instead of using flash data
For some reason when session expires and gets redirected back to admin the warning message does not activate.
Question: Why does the custom data message not show up when session expires once redirected back to admin login?
I also use codeigniter hook function to run the login check function
Controller
Filename: Login.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends MX_Controller {
private $error = array();
public function index() {
$data['title'] = 'Administration';
$data['heading_title'] = 'Administration';
if (($this->input->server('REQUEST_METHOD') == 'POST') && $this->validate()) {
$this->load->library('encryption');
$token = bin2hex($this->encryption->create_key(32));
$this->session->set_userdata(array('token' => $token));
redirect('admin/common/dashboard/?token=' . $token);
}
// Message Below Not Display On Login If Session Expire And Has Been Redirected Back To Admin
if ((isset($_SESSION['token']) && !isset($_GET['token'])) || ((isset($_GET['token']) && (isset($_SESSION['token']) && ($_GET['token'] != $_SESSION['token']))))) {
$this->error['warning'] = 'Your Session Token Is Invalid!';
}
if (isset($this->error['warning'])) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
$data['header'] = Modules::run('admin/common/header/index', $data);
$data['footer'] = Modules::run('admin/common/footer/index');
$this->load->view('common/login', $data);
}
protected function validate() {
if (!isset($_POST['username']) || !isset($_POST['password']) || !$this->user->login($_POST['username'], html_entity_decode($_POST['password'], ENT_QUOTES, 'UTF-8'))) {
$this->error['warning'] = 'Incorrect Username Or Password!';
}
return !$this->error;
}
public function check() {
$uri_route = $this->uri->segment(2) .'/'. $this->uri->segment(3);
$route = isset($uri_route) ? $uri_route : '';
$ignore = array(
'common/login',
'common/forgotten',
'common/reset'
);
if (!$this->user->is_logged() && !in_array($route, $ignore)) {
redirect('admin/common/login');
}
if (isset($route)) {
$ignore = array(
'common/login',
'common/logout',
'common/forgotten',
'common/reset',
'error/not_found',
'error/permission'
);
if (!in_array($route, $ignore) && (!isset($_GET['token']) || !isset($_SESSION['token']) || ($_GET['token'] != $_SESSION['token']))) {
redirect('admin/common/login');
}
} else {
if (!isset($_GET['token']) || !isset($_SESSION['token']) || ($_GET['token'] != $_SESSION['token'])) {
redirect('admin/common/login');
}
}
}
}
Login View $error_warning
<?php if ($error_warning) { ?>
<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> <?php echo $error_warning; ?>
<button type="button" class="close" data-dismiss="alert">×</button>
</div>
<?php } ?>
Hook
<?php
$hook['pre_controller'] = array(
'class' => 'Login',
'function' => 'check',
'filename' => 'Login.php',
'filepath' => 'modules/admin/controllers/common'
);
Because you never set that messsage. Your session has expired, and your if has two parts.
First part: (isset($_SESSION['token']) && !isset($_GET['token'])): session has expired, the token is not set in session, so the first condition is false.
And the second, beefy condition: ((isset($_GET['token']) && (isset($_SESSION['token']) && ($_GET['token'] != $_SESSION['token']))), even if the token is set in the $_GET array that second condition will never be true, because your session has expired, and the token is not set in the session, and/or is not the same to the token in the $_GET array.

How to display custom error message without using codeigniter session flashdata

On my project I am trying to create a error message for my session. I am trying to make it so that if session redirects to main page then will echo message that is on login controller.
Note: I am trying not to use session flashdata if possible. I
already know how to use flashdata.
When I login to my dashboard it displays token in url
Example http://localhost/project-session/index.php/dashboard/32118fa09a0ef2df16851d1f35e3f7d5
On my dashboard __construct() I have this code below.
if ($this->session->userdata('user_id') == FALSE) {
redirect('/');
}
The code above redirects session to home if token is false.
And if it has been redirected because session expires then below message should be activated, On login controller
$get_url_token = $this->uri->segment(2);
$get_session_token = $this->session->userdata('token');
if ((isset($get_session_token) && !isset($get_url_token)) || ((isset($get_url_token) && (isset($get_session_token) && ($get_url_token != $get_session_token))))) {
echo "Session Token Invalid";
}
Login Controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index()
{
$this->load->library('form_validation');
$this->load->library('encryption');
$key = bin2hex($this->encryption->create_key(16));
$get_url_token = $this->uri->segment(2);
$get_session_token = $this->session->userdata('token');
if ((isset($get_session_token) && !isset($get_url_token)) || ((isset($get_url_token) && (isset($get_session_token) && ($get_url_token != $get_session_token))))) {
echo "Session Token Invalid";
}
$this->form_validation->set_rules('username', 'Username');
$this->form_validation->set_rules('password', 'Password');
if ($this->form_validation->run() == FALSE) {
$this->load->view('welcome_message');
} else {
$data = array(
'token' => $key
);
$this->session->set_userdata($data);
redirect('dashboard' .'/'. $key);
}
}
}
Question: Without using codeigniter session flashdata how can I echo my message in my login controller when it is redirect to login because session expire. When I am redirect the echo message does not get activated.
Updated Login Controller
I have got message working but when I go to reload page it does not clear message. Any Suggestions.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
private $error = array();
public function index() {
$this->load->library('form_validation');
$this->load->library('encryption');
$key = bin2hex($this->encryption->create_key(16));
$this->form_validation->set_rules('username', 'Username');
$this->form_validation->set_rules('password', 'Password');
if ($this->form_validation->run() == TRUE) {
$this->session->set_userdata(array('token' => $key));
redirect('dashboard' .'/'. $key);
}
$get_url_token = $this->uri->segment(2);
$get_session_token = $this->session->userdata('token');
if ((isset($get_session_token) && !isset($get_url_token)) || ((isset($get_url_token) && (isset($get_session_token) && ($get_url_token != $get_session_token))))) {
$this->error['warning'] = 'Session Token';
}
if (isset($this->error['warning'])) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
$this->load->view('welcome_message', $data);
}
}

Magento remove param and redirect to same url

I want to remove some URL parameter (like utm_source, but whatever), put it in session and redirect to same page with URL clean of this specific param
I've done in controller_front_init_before like this:
$frontController = $observer->getEvent()->getFront();
$params = $frontController->getRequest()->getParams();
$myParams = array("b");
foreach($myParams as $myParam) {
if (isset($params[$myParam])) {
$customerSession->setData(
$myParam, $params[$myParam]
);
unset($params[$myParam]);
}
}
$frontController->getRequest()->setParams($params); // <- I don't know what to do with that
Now what is the best method to redirect to the same page in request ?
For example redirect http://example.com?a=1&b=2&c=3 to http://example.com?a=1&c=3
Thanks!
$frontController = $observer->getEvent()->getFront();
$params = $frontController->getRequest()->getParams();
$shouldRedirect = false
foreach($params as $key => $value) {
if ($key !== 'b') {
$customerSession->setData($key, $value);
}
else{
unset($params[$key]);
$shouldRedirect = true;
}
}
if($shouldRedirect){
//$url = get url and redirect
//see http://magento.stackexchange.com/questions/5000/add-query-parameters-to-an-existing-url-string
Mage::app()->getResponse()->setRedirect($url);
}

Redirect , POST and Flashdata issue in Codeigniter

i am developing an application where i need some suggestions. Here is the detail of the problem.
public function form()
{
$this->load->helper('inflector');
$id = $this->uri->segment(3,0);
if($data = $this->input->post()){
$result = $this->form_validation->run();
if($result){
if($id > 0){
// here update code
}else{
$this->mymodel->insert($data);
$this->session->set_flashdata('message','The page has been added successfully.');
$this->redirect = "mycontroller/index";
$this->view = FALSE;
}
}else{
//$this->call_post($data);
$this->session->set_flashdata('message','The Red fields are required');
$this->view = FALSE;
$this->redirect = "mycontroller/form/$id";
}
}else{
$row = $this->mymodel->fetch_row($id);
$this->data[]= $row;
}
}
public function _remap($method, $parameters)
{
if (method_exists($this, $method))
{
$return = call_user_func_array(array($this, $method),$parameters);
}else{
show_404();
}
if(strlen($this->view) > 0)
{
$this->template->build('default',array());
}else{
redirect($this->redirect);
}
}
Here you can see how i am trying to reload the page on failed validation.
Now the problem is that i have to display the flash data on the view form which is only available after redirect and i need to display the validation errors to which are not being displayed on redirect due to the loss of post variable. If i dont use redirect then cant display flashdata but only validation errors. I want both of the functionalities togather. I have tried even creating POSt again like this
public function call_post($data)
{
foreach($data as $key => $row){
$_POST[$key] = $row;
}
}
Which i commented out in the formmethod.How can i achieve this.
Here's a thought.
I think you can add the validation error messages into the flash data. Something like this should work:
$this->session->set_flashdata('validation_error_messages',validation_errors());
Notice the call to the validation_errors function. This is a bit unconventional, but I think it should work. Just make sure that the code are executed after the statement $this->form_validation->run(); to make sure the validation error messages are produced by the Form Validation library.
well i have little different approach hope will help you here it is
mycontroller extend CI_Controller{
function _remap($method,$params){
switch($method){
case 'form':
$this->form($params);
break;
default:
$this->index();
break;
}
}
function form(){
$this->load->helper('inflector');
$id = $this->uri->segment(3,0);
$this->form_validation->set_rules('name','Named','required|trim');
$this->form_validation->set_rules('email','email','required|valid_email|trim');
// if validation fails and also for first time form called
if(!$this->form_validation->run()){
$this->template->build('default',array());
}
else{ // validation passed
$this->save($id)
}
}
function save($id = 0){
$data = $this->input->post();
if($id == 0){
$this->mymodel->insert($data);
$this->session->set_flashdata('message','The page has been added successfully.');
$this->redirect = "mycontroller/index";
$this->view = FALSE;
}else{
// update the field
$this->session->set_flashdata('message','The Red fields are required');
}
redirect("mycontroller/index");
}
}
your form/default view should be like this
<?
if(validation_errors())
echo validation_errors();
elseif($this->session->flashdata('message'))
echo $this->session->flashdata('message');
echo form_open(uri_string());// post data to same url
echo form_input('name',set_value('name'));
echo form_input('email',set_value('email'));
echo form_submit('submit');
echo form_close();
try it if you face any problem post here.

Resources