how can i set new cashe just in 10s using laravel Cashe - laravel-5

I used put function for make new manual Cashe. for example :
$cashtime =Cache::put('filekey', 'mycashtime', 20);
and sent it to view but it not expired .
when i send it to view it will back me true. but after 20s have to send me false and expire it.
and then how can i check it is expired or not .

I solved it.my problem was first I have to check if key doesnt exist set again else do someting.
view()->composer('admin.sidebar', function($view){
$cashtime = Cache::get('filekeys');
if($cashtime == Null){
Cache::put('filekeys', 'mycashtimes', now()->addMinutes(1));
//do something
}else{
//do something
}
$view->with(['testmneda' => $cashtime]);
});

Related

Laravel Collective SSH results

I am performing SSH in Laravel whereby I connect to another server and download a file. I am using Laravel Collective https://laravelcollective.com/docs/5.4/ssh
So, the suggested way to do this is something like this
$result = \SSH::into('scripts')->get('/srv/somelocation/'.$fileName, $path);
if($result) {
return $path;
} else {
return 401;
}
Now that successfully downloads the file and moves it to my local server. However, I am always returned 401 because $result seems to be Null.
I cant find much or getting the result back from the SSH. I have also tried
$result = \SSH::into('scripts')->get('/srv/somelocation/'.$fileName, $path, function($line){
dd( $line.PHP_EOL);
});
But that never gets into the inner function.
Is there any way I can get the result back from the SSH? I just want to handle it properly if there is an error.
Thanks
Rather than rely on $result to give you true / false / error, you can check if the file was downloaded successfully in another way:
// download the file
$result = \SSH::into('scripts')->get('/srv/somelocation/'.$fileName, $path);
// see if downloaded file exists
if ( file_exists($path) ) {
return $path;
} else {
return 401;
}
u need to pass file name also like this in get and put method:
$fileName = "example.txt";
$get = \SSH::into('scripts')->get('/remote/somelocation/'.$fileName, base_path($fileName));
in set method
$set = \SSH::into('scripts')->set(base_path($fileName),'/remote/location/'.$fileName);
in list
$command = SSH::into('scripts')->run(['ls -lsa'],function($output) {
dd($output);
});

How to prevent additional page requests after response sent

I have configured a listener on kernel.request which sets a new response with redirect when the session time has reached a certain value. The listener works fine and redirects to a certain page, on the next request, after the session has ended. But my problem is on the page I have many links and if I press multiple times the same link, the initial request with the redirect is cancelled/stopped and a new request is made with the last link pressed and so it passes my redirect even though the session has ended and is destroyed. So, my question is how to prevent additional requests/link presses after the firs request is made?
Here is my code:
public function onKernelRequestSession(GetResponseEvent $event)
{
$request = $event->getRequest();
$route = $request->get('_route');
$session = $request->getSession();
if ((false === strpos($route, '_wdt')) && ($route != null)) {
$session->start();
$time = time() - $session->getMetadataBag()->getCreated();
if ($route != 'main_route_for_idle_page') {
if (!$session->get("active") && $route == 'main_route_for_site_pages') {
$session->invalidate();
$session->set("active", "1");
} else {
if ($time >= $this->sessionTime) {
$session->clear();
$session->invalidate();
$event->setResponse(new RedirectResponse($this->router->generate('main_route_for_idle_page')));
}
}
} else {
if ($session->get("activ")) {
$session->clear();
$session->invalidate();
}
}
}
}
Thak you.
Idea #1: Simple incremental counter
Each request sends sequence number as param which is being verified as expected at the server.
Server increments the number and sends it back via response
the new number is used in future requests
Basically, if server expects the SEQUENCE number to be 2 and client sends 1 the request is to be rejected.
Idea #2: Unique hash each time
Similar to the idea above, but uses unique hashes to eliminate predictive nature of incremental sequence.
I resolved the issue using JQuery: when a link was pressed I disabled the other ones and so only one request is made from the page:
var isClicked = false;
$(".menu-link").click(function(e) {
if(!isClicked) {
isClicked = true;
} else {
e.preventDefault();
}
});
Thanks.

IonAuth - seems to be randomly logging me out

I'm using ionAuth & it seems to be logging me out almost randomly? I'm using Codeigniter v2.1.4 - it logs in perfect fine however ionAuth seems to log out at random intevals, is there a way to force the session to stay active until I call the ionAuth->logout function?
My CI config looks like as follows:
$config['sess_cookie_name'] = 'cisession';
$config['sess_expiration'] = 7200;
$config['sess_expire_on_close'] = FALSE;
$config['sess_encrypt_cookie'] = FALSE;
$config['sess_use_database'] = TRUE;
$config['sess_table_name'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 600;
My ion_auth config file looks as follows:
$config['user_expire'] = 0;
$config['user_extend_on_login'] = FALSE;
Can anyone give me any pointers on what might be causing the issue(s)?
The cause of the problem is a session cookie rotation when an AJAX Call is performed, the proper fix was included in CodeIgniter 3
You have four options:
Cope:
I faced this problem myself before without knowing exactly the cause of it. In short, I saved the promise of each XMLHttpRequest, if the HTTP status code 401 was encountered, the client side application would request the credentials in the form of a popup, and then retry the AJAX promise.
Client side with jQuery, just add this ajaxError handler:
$(document).ajaxError(function (e, xhr, settings, exception) {
if (xhr.status == 401)
{
// open your popup
$('#login-popup').modal('open');
// attach the xhr object to the listener
$(document).bind( "retry-xhr", {
xhro: xhr
},
function( event ) {
// retry the xhr when fired
$.ajax( event.data.xhro );
});
}
});
and when you are logged back in, just call this to retry your request:
$(document).trigger('retry-xhr');
Server side, you only need to add an if in your constructor
if (!$this->session->userdata('logged_in') && $this->input->is_ajax_request())
{
$this->output->set_status_header('401');
exit;
}
This was useful because some users would leave their web app window open overnight and the session timeout would kick in. Then the users would call me about not being able to do any AJAX function, and I would have to tell them to press F5
ps. if on Angular, I have used the HTTP Auth Interceptor Module successfully
Hack:
See this post, his solution is to create another field in the ci_session table and check for both cookies, so your session will still be valid after rotation.
It also explains in detail what is causing this glitch
http://www.hiretheworld.com/blog/tech-blog/codeigniter-session-race-conditions
Upgrade:
Start using the next version where it's already fixed:
https://github.com/EllisLab/CodeIgniter/tree/release/3.0
Patch
Replace line 346 in system/libraries/Session.php (function sess_update())
if (($this->userdata['last_activity'] + $this->sess_time_to_update) >= $this->now)
With:
if (($this->userdata['last_activity'] + $this->sess_time_to_update) >= $this->now || $this->CI->input->is_ajax_request())

Destroying the session if the user is idle

My goal is to destroy the logged-in used session and force him to log in again if he was idle for 20 minutes. Here is my way of doing it:
In each controller, I do this check:
if(reach_idle_limit()) {
redirect('logout');
}
And reach_idle_limit() is a helper method in one of my helper classes:
function reach_idle_limit() {
$idle_period = 1200; //20 mins
$CI =& get_instance();
$last_activity = $CI->session->userdata('last_activity');
$now_time = time();
//If $last_activity is not set, don't force a logout
if($last_activity == False || $last_activity == 0){
return false;
}
//If idle period exceeded: destroy the session and return true
else if($now_time - $last_activity > $idle_period){
$CI->session->sess_destroy();
return true;
}
//else, update session's last_activity to current time, return false
else{
$CI->session->set_userdata('last_activity', $now_time);
return false;
}
}
This works fine when I give $idle_period a small value, like 60 sec. But when I give it the value I seek, 20 min, it doesn't work!
FYI:
I'm using ag_auth library with Codeigniter (for the authentication part).
My config's variable sess_expiration is set to 0.
In this case, why not use session.gc_maxlifetime?
session.gc_maxlifetime specifies the number of seconds after which data will be seen as 'garbage' and potentially cleaned up. Garbage collection may occur during session start (depending on session.gc_probability and session.gc_divisor).
just use:
ini_set('session.gc_maxlifetime',20);

CI Route Issue Not Getting Variable

I'm having an issue with this route and not sure what my problem is exactly.
My page is located at http://www.kansasoutlawwrestling.com/kowmanager/pmsystem/viewmessage/1 where 1 is the message id.
I set up a route to look like
$route['pmsystem/viewmessage/(:num)'] = 'pmsystem/viewmessage/$1';
and I'm still getting a error message like this
A PHP Error was encountered
Severity: Warning
Message: Missing argument 1 for Pmsystem::viewmessage()
Filename: controllers/pmsystem.php
Line Number: 76
// View A Message
function viewmessage($message_id)
{
//Config Defaults Start
$msgBoxMsgs = array();//msgType = dl, info, warn, note, msg
$cssPageAddons = '';//If you have extra CSS for this view append it here
$jsPageAddons = '<script src='.base_url().'../assets/js/cpanel/personalmessages.js></script><script src='.base_url().'assets/js/mylibs/jwysiwyg/jquery.wysiwyg.js></script>';//If you have extra JS for this view append it here
$metaAddons = '';//Sometimes there is a need for additional Meta Data such in the case of Facebook addon's
$siteTitle = '';//alter only if you need something other than the default for this view.
//Config Defaults Start
//examples of how to use the message box system (css not included).
//$msgBoxMsgs[] = array('msgType' => 'dl', 'theMsg' => 'This is a Blank Message Box...');
/**********************************************************Your Coding Logic Here, Start*/
// Checks to see if a session is active for user and shows corresponding view page
if (!$this->loggedin->chkLoginStatus() === FALSE)
{
if( ! $this->uri->segment(3))
{
redirect('error', 'refresh');
}
}
else
{
redirect('login', 'refresh');
}
$bodyContent = 'viewpm';//which view file
$bodyType = "full";//type of template
/***********************************************************Your Coding Logic Here, End*/
//Double checks if any default variables have been changed, Start.
//If msgBoxMsgs array has anything in it, if so displays it in view, else does nothing.
if(count($msgBoxMsgs) !== 0)
{
$msgBoxes = $this->msgboxes->buildMsgBoxesOutput(array('display' => 'show', 'msgs' =>$msgBoxMsgs));
}
else
{
$msgBoxes = array('display' => 'none');
}
if($siteTitle == '')
{
$siteTitle = $this->metatags->SiteTitle(); //reads
}
//Double checks if any default variables have been changed, End.
$this->data['msgBoxes'] = $msgBoxes;
$this->data['cssPageAddons'] = $cssPageAddons;//if there is any additional CSS to add from above Variable this will send it to the view.
$this->data['jsPageAddons'] = $jsPageAddons;//if there is any addictional JS to add from the above variable this will send it to the view.
$this->data['metaAddons'] = $metaAddons;//if there is any addictional meta data to add from the above variable this will send it to the view.
$this->data['pageMetaTags'] = $this->metatags->MetaTags();//defaults can be changed via models/metatags.php
$this->data['siteTitle'] = $siteTitle;//defaults can be changed via models/metatags.php
$this->data['bodyType'] = $bodyType;
$this->data['bodyContent'] = $bodyContent;
$this->data['user_data'] = $this->users->getUserByUserId($this->session->userdata('user_id'));
$this->data['users'] = $this->loggedin->getUserList();
$this->data['personal_messages'] = array($this->pmmodel->getTotalMessages($this->session->userdata('user_id')), $this->pmmodel->getTotalUnreadMessages($this->session->userdata('user_id')), $this->pmmodel->getLast5Messages($this->session->userdata('user_id')));
$this->data['messages'] = array($this->pmmodel->getInboxMessages($this->session->userdata('user_id')), $this->pmmodel->getSentMessages($this->session->userdata('user_id')));
//$this->data['message_data'] = $this->pmmodel->getPmMessage($this->uri->segment(3));
$this->load->view('cpanel/index', $this->data);
}
UPDATE
// Checks to see if a session is active for user and shows corresponding view page
if (!$this->loggedin->chkLoginStatus() === FALSE)
{
if (!is_numeric($this->uri->segment(3)))
{
$this->data['message_data'] = 'Invalid message id!';
}
else
{
$this->data['message_data'] = $this->pmmodel->getPmMessage($this->uri->segment(3));
}
$bodyContent = 'viewpm';//which view file
}
else
{
redirect('login', 'refresh');
}
$bodyType = "full";//type of template
This route is unnecessary - it doesn't change anything.
$route['pmsystem/viewmessage/(:num)'] = 'pmsystem/viewmessage/$1';
You can remove that route. The problem is here:
function viewmessage($message_id) // no default value means it's required
{
// your code
}
Your controller methods literally accept user input as arguments (whatever's in the address bar). You always have to account for those required arguments not being present in CI controller methods.
function viewmessage($message_id = NULL)
{
if ( ! $message_id) show_404();
// your code
}
This will silence the errors and show a 404 if the required $message_id is not there. Additionally, $this->uri->segment(3) is unnecessary because it should have the same value as $message_id.
I highly discourage redirecting to an error page when you really want a 404, but that's up to you. It sure doesn't help the user realize their mistake when the address is lost after the redirect, and you're sending the wrong HTTP headers by doing so.

Resources