I have a external API where I want to GET some data, and I want to keep session id through all the request until I log out. Using cURL lib in codeigniter I have the following flow (myacc and mypass are just placeholders):
public function getCURL() {
echo $this->curl->simple_get('http://37.99.110.537:6001/webapi/auth.cgi?api=SYNO.API.Auth&method=login&version=2&account=myacc&passwd=mypassD&format=sid&session=SurveillanceStation');
}
This will output:
{"data":{"sid":"lH6WJCWMm5rkA14B0MPN570354"},"success":true}
I will have to keep that provided sid (session id) when making the next request:
http://37.99.110.537:6001/webapi/entry.cgi?api=SYNO.SurveillanceStation.Camera&method=GetSnapshot&version=1&cameraId=2×tamp=1480512959&preview=true&_sid="lH6WJCWMm5rkA14B0MPN570354"
See at the end sid="lH6WJCWMm5rkA14B0MPN570354".
And then log out and kill that sid.
After each login I would get a new sid that I have to use it to get a picture (with that URL) and then logout.
I think that saving and using cookies from a file in my case isn't needed, I think something like:
public function getCURL() {
echo $this->curl->simple_get('http://37.99.210.237:6001/webapi/auth.cgi?api=SYNO.API.Auth&method=login&version=2&account=myacc&passwd=mypassD&format=sid&session=SurveillanceStation');
if ($this->form_validation->run()){
$data= array(
'sid'=> $this->input->post('sid'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
if(false == $this->CI->session->userdata('is_logged_in')) {
echo $this->curl->simple_get('http://37.99.110.537:6001/webapi/entry.cgi?api=SYNO.SurveillanceStation.Camera&method=GetSnapshot&version=1&cameraId=2×tamp=1480512959&preview=true&_sid="sid"');
}
}
}
^^ That syntax is messed up, but how I can make it in a proper way or how it's the best way to keep session id on the request chain ?
if you want to keep sid for long session, for multiple request etc, you can save this json to some json file and clear content of file while logging out.
wrap your $sid getter to some other function.
function getSid()
{
//try to read from json
if(is_file('path/to/sid.json'){
$sid = json_decode(file_get_contents('path/to/sid.json', true));
if(!isset($sid['logout'])){
return $sid['data']['sid'];
}
}
$sid = $this->curl->simple_get('http://37.99.110.537:6001/webapi/auth.cgi?api=SYNO.API.Auth&method=login&version=2&account=myacc&passwd=mypassD&format=sid&session=SurveillanceStation');
//check and save `$sid`
if(strlen($sid) > 20) {
file_put_contents('path/to/sid.json', $sid);
return json_decode($sid, true)['data']['sid'];
}
return false;
}
and update content of sid.json while logging out.
function logout()
{
file_put_contents('path/to/file', json_encode(['logout' => 'true']));
}
and call these methods.
for every request in one execution, it will use the same sid, and when you'll hit 'logout()' it will destroy the sid so that new generated and used on next execution.
Related
I have /signup/select-plan which lets the user select a plan, and /signup/tos which displays the terms of services. I want /signup/tos to be only accessible from /signup/select-plan. So if I try to go directly to /signup/tos without selecting a plan, I want it to not allow it. How do I go about this?
In the constructor, or the route (if you are not using contructors), you can check for the previous URL using the global helper url().
public function tos() {
if ( !request()->is('signup/tos') && url()->previous() != url('signup/select-plan') ) {
return redirect()->to('/'); //Send them somewhere else
}
}
In the controller of /signup/tos which returns the tos view just add the following code:
$referer = Request::referer();
// or
// $referer = Request::server('HTTP_REFERER');
if (strpos($referer,'signup/select-plan') !== false) {
//SHOW THE PAGE
}
else
{
dd("YOU ARE NOT ALLOWED")
}
What we are doing here is checking the HTTP referrer and allowing the page access only if user comes from select-plan
You are need of sessions in laravel. You can see the following docs to get more info: Laravel Sessions
First of all you need to configure till how much time you want to have the session variable so you can go to your directory config/sessions.php and you can edit the fields 'lifetime' => 120, also you can set expire_on_close by default it is being set to false.
Now you can have following routes:
Route::get('signup/select-plan', 'SignupController#selectPlan');
Route::post('signup/select-token', 'SignupController#selectToken');
Route::get('signup/tos', 'SignupController#tos');
Route::get('registered', 'SignupController#registered');
Now in your Signupcontroller you can have something like this:
public function selectPlan()
{
// return your views/form...
}
public function selectToken(Request $request)
{
$request->session()->put('select_plan_token', 'value');
return redirect('/signup/tos');
}
Now in signupController tos function you can always check the session value and manipulate the data accordingly
public function tos()
{
$value = $request->session()->get('select_plan_token');
// to your manipulation or show the view.
}
Now if the user is registered and you don't need the session value you can delete by following:
public function registered()
{
$request->session()->forget('select_plan_token');
// Return welcome screen or dashboard..
}
This method will delete the data from session. You can manipulate this. You won't be able to use in tos function as you are refreshing the page and you want data to persist. So its better to have it removed when the final step or the nextstep is carried out. Hope this helps.
Note: This is just the reference please go through the docs for more information and implement accordingly.
I am trying to use Laravel session variable to store a user's viewing mode which should toggle when the user clicks on a button. I created a route for this. For some reason the session variable is not being persisted accross the whole app.
Take a look at my code. This is the method in my controller accessed via a link:
public function changeQuoteViewModeAjax(Request $request)
{
$mode = $request->session()->get('mode');
if($mode == 'private') {
$request->session()->put('mode', 'public');
} else {
$request->session()->put('mode', 'private');
}
if($request->session()->has('mode')) {
print_r(json_encode([
'success' => true,
'mode' => $request->session()->get('mode')
]));
die();
}
}
When I visit this link I constantly get a printed output that the view mode is private. This is because the $mode variable in the beginning is always empty. I am not sure why this is.
Any help much appreciated
I've been working on the security of my site (PHP) and there's a ton of information to ingest. I've tried to implement security I've researched on OWASP, but one thing I'm a little nervous about, among other things, is how to handle SESSIONS when the user logs out.
Currently all I'm using is:
session_destroy();
But, I've read that I should change the XRSF token and start another SESSION so it forces the user to resubmit login credentials in-turn explicitly ending the users SESSION.
Is session_destroy() enough?
EDIT
I've downloaded michael-the-messenger, which I believe was created by Michael Brooks (Rook) which should be VERY secure, and I saw some code that I might want to use. Is this something that could safely replace the session_destroy() I'm using?
CODE
if($_SESSION['user']->isAuth())
{
/* if they have clicked log out */
/* this will kill the session */
if($_POST['LogMeOut'] == 'true')
{
//When the user logs out the xsrf token changes.
$tmp_xsrf = $_SESSION['user']->getXsrfToken();
$_SESSION['user']->logout();
$loginMessage = str_replace($tmp_xsrf, $_SESSION['user']->getXsrfToken(), $loginMessage);
print layout('Authorization Required', $loginMessage);
}
else
{
header("Location: inbox.php");
//user is allowed access.
}
}
else
{
// code goes on ....
LOGOUT
public function logout()
{
$_SESSION['user'] = new auth();
}
Obviously $_SESSION['user'] = new auth(); reinstantiates the object which sets a private variable $auth to false.
but one thing I'm a little nervous about, among other things, is how
to handle SESSIONS when the user logs out.
According to manual:
In order to kill the session altogether, like to log the user out, the
session id must also be unset. If a cookie is used to propagate the
session id (default behavior), then the session cookie must be
deleted. setcookie() may be used for that.
So, in order to safely destroy a session, we'd also erase it on the client-machine.
session_destroy() along with setcookie(session_name(), null, time() - 86400) will do that.
Apart from that,
What you are doing wrong and why:
Session storage merely uses data serialization internally. By storing
an object in the $_SESSION superglobal you just do
serialize/unserialize that object on demand without even knowing it.
1) By storing an object in $_SESSION you do introduce global state. $_SESSION is a superglobal array, thus can be accessed from anywhere.
2) Even by storing an object that keeps an information about logged user, you do waste system memory. The length of object representation is always greater than a length of the strings.
But why on earth should you even care about wrapping session functionality? Well,
It makes a code easy to read, maintain and test
It adheres Single-Responsibility Principle
It avoids global state (if properly used), you'll access session not as $_SESSION['foo'], but $session->read['foo']
You can easily change its behaivor (say, if you decide to use DB as session storage) without even affecting another parts of your application.
Code reuse-ability. You can use this class for another applications (or parts of it)
If you wrap all session-related functionality into a signle class, then it will turn into attractive:
$session = new SessionStorage();
$session->write( array('foo' => 'bar') );
if ( $session->isValid() === TRUE ) {
echo $session->read('foo'); // bar
} else {
// Session hijack. Handle here
}
// To totally destroy a session:
$session->destroy();
// if some part of your application requires a session, then just inject an instance of `SessionStorage`
// like this:
$user = new Profile($session);
// Take this implementation as example:
final class SessionStorage
{
public function __construct()
{
// Don't start again if session is started:
if ( session_id() != '' ) {
session_start();
}
// Keep initial values
$_SESSION['HTTP_USER_AGENT'] = $_SERVER['HTTP_USER_AGENT'];
$_SESSION['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR'];
}
/**
* You can prevent majority of hijacks using this method
*
* #return boolean TRUE if session is valid
*/
public function isValid()
{
return $_SESSION['HTTP_USER_AGENT'] === $_SERVER['HTTP_USER_AGENT'] && $_SESSION['REMOTE_ADDR'] === $_SERVER['REMOTE_ADDR'] ;
}
public function __destruct()
{
session_write_close();
}
/**
* Fixed session_destroy()
*
* #return boolean
*/
public function destroy()
{
// Erase the session name on client side
setcookie(session_name(), null, time() - 86400);
// Erase on the server
return session_destroy();
}
public function write(array $data)
{
foreach($data as $key => $value) {
$_SESSION[$key] = $value;
}
}
public function exists()
{
foreach(func_get_args() as $arg){
if ( ! array_key_exists($arg, $_SESSION) ){
return false;
}
}
return true;
}
public function read($key)
{
if ( $this->exists($key) ){
return $_SESSION[$key];
} else {
throw new RuntimeException('Cannot access non-existing var ' .$key);
}
}
}
Maybe session_unset() is what you are looking for.
I'm trying to implement and authentication system with jQuery and PHP. All the php work is made in the controller and datahandler class. There is no php code inside the .html files, all the values in .html files are rendered via jQuery that request the data from php server. So what I'm trying to do is:
When user clicks the login button, the jQuery makes a call to the authenticate() method in my controller class, it checks if the user is correct and stuff, and if it is, start the session and set the user_id on the session so I can access it later, and returns the userId to the jQuery client again.
After that, if everything is fine, in jQuery I redirect it to the html file. On the html file I call a jQuery from the <script> tag that will handle other permissions. But this jQuery will access the method getPermissionString (from the same class of authenticate() method mentioned before), and it will need to get the session value set in authenticate method.
The Problem:
When I try to get the session value inside getPermissionString() it says:
Notice: Undefined variable: _SESSION
I've tried to check if the session is registered in the second method, but looks like it's not. Here is my PHP code.
Any idea? Thanks.
public function authenticate($login, $password)
{
$result = $this->userDataHandler->authenticateUser($login, $password);
if(is_numeric($result) && $result != 0)
{
session_start();
$_SESSION["uid"] = $result;
if(isset($_SESSION["uid"]))
{
echo "registered";
$userId = $_SESSION["uid"];
}
else
{
echo "not registered";
}
echo $result;
}
else
{
echo 0;
}
}
public function getPermissionString()
{
if(isset($_SESSION["uid"]))
{
echo "registered";
$userId = $_SESSION["uid"];
}
else
{
echo "not registered";
}
}
Before you can access $_SESSION in the second function you need to ensure that the program has called session_start() beforehand. The global variable is only populated when the session has been activated. If you never remember to start a session before using it then you can change the php.ini variable below:
[session]
session.auto_start = 1
Further, you said that you're using a class for your code. In this case you can also autos tart your session each time the class in created by using magic methods:
class auth {
function __construct() {
session_start();
}
function yourfunction() {
...
}
function yoursecondfunction(){
...
}
}
If you don't have session.auto_start enabled, and authenticate and getPermissionString are called on two different requests, you need to call session_start() in each function.
If you need more information on how the session ID is passed, just read Passing the Session ID
You should not use that function if session is not started. So throw an exception:
public function getPermissionString()
{
if (session_status() !== PHP_SESSION_ACTIVE)
{
throw new Exception('No active session found.');
}
if(isset($_SESSION["uid"]))
{
echo "registered";
$userId = $_SESSION["uid"];
}
else
{
echo "not registered";
}
}
This ensures the pre-conditions of your functions are checked inside the function so you don't need to check it each time before calling the function.
You will now see an exception if you wrongly use that function and it will give you a backtrace so you can more easily analyze your code.
For php sessions to work you have to call session_start() every time you script is requested by the browser.
I'm writing a Ajax/PHP web application. Most ajax calls are using accessing the user object which is stored in the session.
<?php
session_start();
function session_user()
{
static $session_user = null;
if (!isset($session_user))
{
if (isset($_SESSION['user']))
$session_user = unserialize($_SESSION['user']);
else
$session_user = new User();
}
return $session_user;
}
class User {
public $books_borrowed = array();
public function __construct()
{
}
function __destruct()
{
// store the user object in the session upon destruction
session_start();
$_SESSION[ 'user' ] = serialize( $this );
}
function authorise($user_id, $password)
{
// if the user_id and password match, load books_borrowed from the DB
...
}
function deauthorise()
{
session_destroy();
}
}
?>
Ajax calls access the user object like this:
return session_user()->books_borrowed;
Note that the user object stores itself upon destruction, which, as far as I can tell, happens just before the ajax call return.
The reason I'm storing the user object to the session every time the object is destroyed is that it contains other objects (books) that might change during ajax calls, and neither do I want the book object to 'know' about the user object (for reusability) nor do I want to bother with having to remember storing the user object whenever any information within it changes.
Can someone see anything wrong with this strategy?
Thanks
The main strategy when you make a design for brand new application with ajax is not to think of ajax like about something special. It is regular request performed by browser. Absolutely the same like when you open new page by typing url manually and pressing enter.