Underfind index in session - php

I try to load a session as I want with me into my handler. But the line 8 says that "during the find index" what is the error in my controller? It is a user name that I want to use a database to retrieve the id of the person.
Controller:
<?php
require_once ("View/PersonInfoView.php");
require_once ("Handler/UserHandler.php");
class PersonInfoController{
public function DoPersonInfo(){
$Personinfoview = new PersonInfoView();
$UserHandler = new UserHandler();
$PK = $UserHandler->GetUserID($_SESSION['Person']);
$Person_array = $UserHandler->ListPerson($PK);
$Personinfoview->Personbox($Person_array);
}
}
I set Session :
<?php
require_once ("Handler/Userhandler.php");
require_once ("Controller/LoginController.php");
class DologinHandler{
public function Login(){
if(isset($_REQUEST['is_ajax']))
{
$LoginController = new LoginController();
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$_SESSION['Person'] = $username;
$UserHandler = new UserHandler();
$sign = $UserHandler -> controllDB($username,$password);
if($sign == true)
{
echo 'success';
return true;
}
else
{
echo 'error';
return false;
}
}
}
}
$loginclass = new DologinHandler();
$loginclass->Login();

I'm guessing your $_REQUEST doesn't contain the key Person. Try doing a var_dump() on $_REQUEST to see what it contains.
Other than that, I suggest you implement some kind of error handeling when calling $UserHandler->GetUserID()
For instance.
try {
$PK = $UserHandler->GetUserID($_SESSION['Person']);
} catch(Exception $e) {
echo($e->getMessage());
}
Read about exceptions.

Related

Get int from column by using email to identify row

I want to get and echo a users permission level.
I have a function where the users email is passed, the function then needs to get the users permission level and return it, so it can be echoed on another page.
I imagine the function will look though the database for the passed email, it then finds the users permission and returns with that.
In the 'User.class.php'
public static function permGetter($email)
{
try
{
$db = Database::getInstance();
$stmt = $db->prepare('SELECT permission FROM users WHERE email = :email LIMIT 1');
$stmt->execute([':permission'=>$permission]);
$user = $stmt->fetchObject('User');
if($user !== false)
{
return $permission;
}
}
catch (PDOException $exception)
{
error_log($exception->getMessage());
return false;
}
}
In the 'permRequest.php'
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once("../includes/init.php");
//Get passed from an external program
$email = $_GET['email'];
$pass = $_GET['pass'];
if($email && $pass !== null)
{
// Checks if the user's entered credential matches with those in database
if(Auth::getInstance()->login($email, $pass))
{
//Uses the passed email to get permission level in 'User.class.php'
if(User::permGetter($email))
{
echo 'Permission ' + (int) $permission;
}
}
else
{
//I use level 5 as a debug so i can see when it fails
echo 'Permission 5';
}
}
?>
Database
Here's an example on what my database looks like.
Edit 1
Okay messing about, I think i got closer to the solution.
First, #Lawrence Cherone, thanks for pointing out my mistake in my execute.
Okay I have changed my code in
User.class.php
public static function permGetter($email, $permission)
{
try
{
$db = Database::getInstance();
$stmt = $db->prepare('SELECT permission FROM users WHERE email = :email');
$stmt->execute([':email'=>$email]);
$row = $stmt->fetch(PDO::FETCH_NUM);
$permission = $row['permission'];
}
catch (PDOException $exception)
{
error_log($exception->getMessage());
return false;
}
}
I have made small changes to
permRequest.php
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once("../includes/init.php");
//Get passed from an external program
$email = $_GET['email'];
$pass = $_GET['pass'];
$permission = '';
if($email && $pass !== null)
{
// Checks if the user's entered credential matches with those in database
if(Auth::getInstance()->login($email, $pass))
{
//Uses the passed email to get permission level in 'User.class.php'
if(User::permGetter($email, $permission))
{
echo 'Permission ', $permission;
}
}
}
?>
But now i get an error. The error is this Notice: Undefined index: permission in /classes/User.class.php on line 56
So, I read up on it and it seemed like it should be emptied first, so I empty it in permRequest.php that's why I'm passing it too, but I still get this error after i emptied it?
However if i change
$row = $stmt->fetch(PDO::FETCH_NUM);
to
$row = $stmt->fetch(PDO::FETCH_ASSOC);
/* OR */
$row = $stmt->fetch(PDO::FETCH_BOTH);
I get no error but it simply says my email or password is incorrect, which it isn't I have double and triple checked it.
So I'm confused to which PDO::FETCH_ I should use. I have read this (Click here) and I would say that both ASSOC, BOTH and NUM would fit the purpose.
So why is one giving an error while the two other's simply fails the login?
Edit 2
Found the solution and i have written it as a Answer. Can't accept it for the next two days however.
I moved everything out of the User.class.php and moved it into permRequest.php. This solved my problem for some reason. So my code looks like this now
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL ^ E_NOTICE);
require_once("../includes/init.php");
$email = $_GET['email'];
$pass = $_GET['pass'];
if($email && $pass !== null)
{
if(Auth::getInstance()->login($email, $pass))
{
try
{
$db = Database::getInstance();
$stmt = $db->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute([':email' => $email]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$sub = $row['permission'];
echo 'Permission ', $sub;
}
catch (PDOException $exception)
{
error_log($exception->getMessage());
return false;
}
}
}
And I don't use the User.class.php for this function.
So my guess is something went wrong when returning $sub when it was in User.class.php

PHP Session not setting

I have a PHP page and session, i started session on top of every site, but this isn't working.
I'm setting session (I'm setting class into session) with
}else if(isset($_POST['username']) and isset($_POST['password'])){
$account = new Account;
$password = hash('sha256', $_POST['password']);
$account->setTheAccount($_POST['username'],$password);
$acc_data = $account->getDatabaseAccounts('root','','schoolpage','localhost','accounts');
$acc_status = $account->isAccountTrue();
if ($acc_status==true){
$_SESSION['account'] = $account;
echo 'true';
header('Location:panel.php');
}else{
echo 'false';
}
}
and accessing it by:
if (isset($_SESSION['account'])){
$account = $_SESSION['account'];
if ($account->isAccountTrue() == true){
echo 'XD';
}
}
but it doesnt work.
I haven't idea why session not working.
Account class
class Account{
private $acc_data,$username,$password;
function setTheAccount($usernamei, $passwordi){
$this->username = $usernamei;
$this->password = $passwordi;
}
function getDatabaseAccounts($dbUser,$dbPassword,$dbName,$dbHost, $dbTable){
$pdo = new PDO('mysql:host='.$dbHost.';dbname='.$dbName, $dbUser, $dbPassword);
$this->acc_data = $pdo->query('SELECT * FROM `'.$dbTable.'`');
}
function isAccountTrue(){
$acc_status=false;
foreach ($this->acc_data as $i) {
if ($i['username'] == $this->username and $i['password'] == $this->password){
$acc_status = true;
}
}
return $acc_status;
}
function isUserLogged(){
}
}
Account class var dump
truearray(2) { ["login"]=> bool(true) ["account"]=> object(Account)#1 (3) { ["acc_data":"Account":private]=> object(PDOStatement)#3 (1) { ["queryString"]=> string(24) "SELECT * FROM `accounts`" } ["username":"Account":private]=> string(5) "admin" ["password":"Account":private]=> string(64) "4813494d137e1631bba301d5acab6e7bb7aa74ce1185d456565ef51d737677b2" } }
To store an object in $_SESSION you have to serialize it, then deserialize it to call the method ->isAccountTrue(), otherwise just store the result:
$_SESSION['accountValid']=$account->isAccountTrue();
...
if($_SESSION['accountValid']===true){
// do stuff
}
Put
error_reporting(-1);
ini_set('display_errors', true);
on top of the page to enable the php errors, and you will see that you can't serialize a resource, PDO instances, PDOStatement, etc. into session.
You can't serialize Account's $acc_data, since it's an instance of PDOStatement. You cannot serialize or unserialize PDOStatement instances.
Change
$this->acc_data = $pdo->query('SELECT * FROM `'.$dbTable.'`');
to
$this->acc_data = $pdo->query('SELECT * FROM `'.$dbTable.'`')->fetchAll();
then delete your session and retry.

Strange Password_Hash Issue

So im using the exact same script as I used to a while back and for some reason when I move to my new domain and hosting it is having really weird issues, I created a user and got hm to try login, It wasnt working for him I got a new hash from a random test.php file with this php:
<?php
/**
* In this case, we want to increase the default cost for BCRYPT to 12.
* Note that we also switched to BCRYPT, which will always be 60 characters.
*/
$options = [
'cost' => 9,
];
echo password_hash("His Pass", PASSWORD_BCRYPT, $options)."\n";
?>
It then worked, He logged in fine and I then tried to login to my main admin account and for some reason its now not working even when I try remaking the hash 2 times now.
I have no idea whats going on can someone please enlighten me.
Heres the login code:
//If User Submits Form continue;
if(isset($_POST['username'])) {
//If the captcha wasn't submitted;
if(empty($_POST['g-recaptcha-response'])) {
//And theres already a try with there IP;
if($trycount != '0') {
//Increment there try count and give a notification;
updateTries(); ?>
<script type="text/javascript">localStorage.setItem("notification", "nocaptcha");</script> <?php
//If there isn't a try on there IP yet;
} else {
//Add one try and give a notification;
addTry(); ?>
<script type="text/javascript">localStorage.setItem("notification", "nocaptcha");</script> <?php
}
//If the captcha was submitted;
} else {
//Set captcha variable to the Submitted Captcha Response;
$captcha=$_POST['g-recaptcha-response'];
//Captcha Verification Url;
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=t&response=';
//JSON Encode the Captcha's response and Site IP;
$response = json_decode(file_get_contents($url.urlencode($captcha).'&remoteip='.$_SERVER['REMOTE_ADDR']), true);
//If the captcha wasn't verified;
if($response['success'] == false) {
//And theres already a try with there IP;
if($trycount != '0') {
//Increment there try count and give a notification;
updateTries(); ?>
<script type="text/javascript">localStorage.setItem("notification", "captchafailed");</script> <?php
//If there isn't a try on there IP yet;
} else {
//Add one try and give a notification;
addTry(); ?>
<script type="text/javascript">localStorage.setItem("notification", "captchafailed");</script> <?php
}
//Otherwise if it was verified;
} else {
//Try log in with the given details;
user_login($_POST['username'],$_POST['password']);
//If logged in redirect and give a notification;
if(loggedin()) { ?>
<script type="text/javascript">localStorage.setItem("notification", "loggedin");</script>
<meta http-equiv="refresh" content="0;URL='https://gameshare.io'" /> <?php
} else {
//And theres already a try with there IP;
if($trycount != '0') {
//Increment there try count and give a notification;
updateTries(); ?>
<script type="text/javascript">localStorage.setItem("notification", "loginfailed");</script> <?php
//If there isn't a try on there IP yet;
} else {
//Add one try and give a notification;
addTry(); ?>
<script type="text/javascript">localStorage.setItem("notification", "loginfailed");</script> <?php
}
}
}
}
}
User_login function:
//Create a new function named user_login;
function user_login($username = false, $password = false) {
//Fetch for the username and password applied;
$st = fetch("SELECT username,password,email,image FROM users WHERE username = :username",array(":username"=>$username));
//If a row was found continue
if($st != 0) {
$storedhash = $st[0]['password'];
if (password_verify($password, $storedhash)) {
//Set a new username session and set it the username;
$_SESSION['username'] = $username;
$_SESSION['email'] = $st[0]['email'];
$_SESSION['image'] = $st[0]['image'];
if($username == 'admin') {
$_SESSION['role'] = 'admin';
} else {
$_SESSION['role'] = 'user';
}
}
}
//If no errors happened Make the $valid true;
return true;
$dontaddtry = true;
}
Fetch function:
//Create a new function named fetch;
function fetch($sql = false,$bind = false,$obj = false) {
//Prepare The SQL Query;
$query = Connect()->prepare($sql);
//Execute Binded Query;
$query->execute($bind);
//While Fetching Results;
while($result = $query->fetch(PDO::FETCH_ASSOC)) {
//Add a row to the results respectiveley;
$row[] = $result;
}
//If there are no rows;
if(!empty($row)) {
//Make it an object;
$row = ($obj)? (object) $row : $row;
} else {
//Else row is false;
$row = false;
}
//If no errors happened Make $row true;
return $row;
}
Connect Function:
//Create a new function named LoggedIn, And apply database info;
function Connect($host = 'localhost',$username = 'x',$password = 'x',$dbname = 'x') {
//Try execute the PHP with no errors;
try {
//Create a PDO Session;
$con = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
//Session Attributes;
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
//Catch all PDOException errors;
catch (PDOException $e) {
//If any errors print result;
echo "<code><pre>".print_r($e)."</pre></code>";
//Make the PDO session false;
$con = false;
}
//If no errors happened Make the PDO session true;
return $con;
}
P.S If you wish to get an account to try on my site let me know and ill make a temporary account.
Make sure your the php version of your new hosting. password_hash needs at-least PHP 5.5.0.
You can check your current PHP version via following code.
<?php
echo 'Current PHP version: ' . phpversion();
?>

zend how to validate 3 separate form in same action?

So, I have 3 forms on the same page and same controller action, when I click on one of the submit button, it validates all forms instead of the one I clicked.
how can I separate it from validation??
here my code:
public function signUpAction()
{
$firstName = $this->getRequest()->getParam('firstName');
$lastName = $this->getRequest()->getParam('lastName');
$email = $this->getRequest()->getParam('email');
$emailAdrress = $this->getRequest()->getParam('Email_Address');
$password = $this->getRequest()->getParam('password');
$signupForm = new Application_Form_UserSignUp();
$loginForm = new Application_Form_UserLogin();
$retreivePasswordForm = new Application_Form_UserRetreivePassword();
if ($this->getRequest()->isPost('signupForm'))
{
/*********** Sign Up Form ***********/
if ($signupForm->isValid($this->getRequest()->getParams()))
{
$user = $this->_helper->model('Users')->createRow($signupForm->getValues());
if ($user->save())
{
Zend_Session::rememberMe(186400 * 14);
Zend_Auth::getInstance()->getStorage()->write($user);
$user->sendSignUpEmail();
$this->getHelper('redirector')->gotoRoute(array(), 'invite');
return;
}
else
{
}
}
else
{
// something
}
}
if ($this->getRequest()->isPost('loginForm'))
{
/************ Login Form ************/
if ($loginForm->isValid($this->getRequest()->getParams()))
{
$user = $this->_helper->model('Users')->createRow($loginForm->getValues());
$user = $this->_helper->model('Users')->fetchRowByFields(array('email' => $email, 'hash' => $password));
if($user)
{
Zend_Session::rememberMe(86400 * 14);
Zend_Auth::getInstance()->getStorage()->write($user);
$this->getHelper('redirector')->gotoRoute(array(), 'invite');
return;
}
else {
// Error message
$this->view->errorMsg = "<b>password</b> - invalid, please try again! *";
}
}
else
{
// something
}
}
if ($this->getRequest()->isPost('retreivePasswordForm'))
{
/****** Retreive Password Form ******/
if ($retreivePasswordForm->isValid($this->getRequest()->getParams()))
{
$user = $this->_helper->model('Users')->createRow($retreivePasswordForm->getValues());
$user = $this->_helper->model('Users')->fetchRowByFields(array('email' => $emailAdrress));
if($user)
{
Zend_Auth::getInstance()->getStorage()->write($user);
$user->sendRetreiveEmail();
$_SESSION['email'] = $emailAdrress;
$redirector = $this->_helper->getHelper('redirector');
$redirector->setCode(301)->setUseAbsoluteUri();
$newPath = 'http://refer.lavasoft.com/#retreive_sent';
$redirector->gotoUrl($newPath);
//$this->view->assign('sendEmail', $emailAddress);
}
else
{
}
}
else
{
// something
}
}
$this->view->retreivePasswordForm = $retreivePasswordForm;
$this->view->loginForm = $loginForm;
$this->view->signupForm = $signupForm;
}
This is not how it works in ZF. You cannot pass the form name to isPost() unless you override isPost() in your code.
What you could do is Define all your fields like:
loginForm[name]
loginForm[password]
and
signupForm[name]
etc
then just check for isset($_POST['loginFom'])
This should work fine.
Or use a hidden field named formName and check in your code what's its value is.
You can also use a different action for each form and in the end redirect to the signUpAction wich would yeld the same result without the hassle.

Joomla 2.5 authentication Plugin Fatal error: Call to a member function get() on a non-object

I wrote a simple authentication plugin that uses a SOAP webservice to check the username and the password. That works fine.
I wanted to have some parameter like the SOAP password in the admin of joomla. So I have added the params in the xml, it shows fine in the admin. When I try to get the value of it the php, I get:
Fatal error: Call to a member function get() on a non-object
So I compared with other authentication and I do it exactly the same way.... I do not understand why it is so.
Here is the code of the Plugin:
public function __construct() {
$nusoap = JPATH_SITE . '/plugins/authentication/ers/nusoap/lib/nusoap.php';
if (! file_exists ( $nusoap )){
$response->error_message = "No such file";
return;
}
require_once ($nusoap);
}
function onUserAuthenticate($credentials, $options, &$response)
{
//Without defaults (the plugin crashes on the first get() bellow)
$webservice = $this->params->get('webservice', '');
$group = $this->params->get('group', '');
$whitepaw = $this->params->get('whitepaw', '');
JRequest::checkToken() or die( 'Invalid Token' );
// For JLog
$response->type = 'ERS SOAP Webservice';
// MyCompany does not like blank passwords (So does Joomla ;))
if (empty($credentials['password'])) {
$response->status = JAuthentication::STATUS_FAILURE;
$response->error_message = JText::_('JGLOBAL_AUTH_EMPTY_PASS_NOT_ALLOWED');
return false;
}
if (empty($credentials['username'])) {
$response->status = JAuthentication::STATUS_FAILURE;
$response->error_message = JText::_('Please enter a username');
return false;
}
// Add a user to joomla
function addJoomlaUser($name, $username, $password, $email, $group) {
$data = array(
"name"=>$name,
"username"=>$username,
"password"=>$password,
"password2"=>$password,
"email"=>$email,
"block"=>0,
"groups"=>array("1","2", $group) // the uer is added into the group "public" and "registered" as well as a group of the user's choice.
);
$user = clone(JFactory::getUser());
//Write to database
if(!$user->bind($data)) {
throw new Exception("Could not bind data. Error: " . $user->getError());
}
if (!$user->save()) {
throw new Exception("Could not save user. Error: " . $user->getError());
}
return $user->id;
}
// Pour supprimer le cache du web-service
ini_set('soap.wsdl_cache_enabled', 0);
// Nouveau Client SOAP
try {
// Nouvelle instance de la classe soapClient
$client = new SoapClient($webservice, array('trace' => true));
$username = $credentials['username'];
$password = $credentials['password'];
$result = $client->CheckLogin(array('whitepaw'=>$whitepaw, 'username'=>$username, 'password'=>$password));
if($result->isInDB){
$name = $result->fname.' '.$result->lname;
$email = $result->email;
$response->error_message = $username.'<br>'.$password.'<br>'.$name.'<br>'.$email."<br><br>".
"<b>Request :</b><br>".htmlentities($client->__getLastRequest())."<br><br>".
"<b>RESPONSE :</b><br>".htmlentities($client->__getLastResponse())."<br><br>";
if(!$result->email == '' || empty ($result)) {
//Todo: check if the user is already in joomla db
$user_id = addJoomlaUser($name, $username, $password, $email,$group);
$response->status = JAuthentication::STATUS_SUCCESS;
//for testing purposes
$response->error_message = $user_id;
} else {
$response->error_message = "The webservice did not return data".$email.'did you see it?';
}
} else {
$response->status = JAuthentication::STATUS_FAILURE;
$response->error_message = 'You do not have yet an account in myers. Please register.<br>';
$response->error_message .= $result->isInDB;
}
} catch (Exception $fault) {
$response->error_message = $fault->getMessage();
}
}
}
Since you have your own constructor, you need to call the parent constructor like this:
public function __construct(& $subject, $params = array()) {
$nusoap = JPATH_SITE . '/plugins/authentication/ers/nusoap/lib/nusoap.php';
if (! file_exists ( $nusoap )){
$response->error_message = "No such file";
return;
}
require_once ($nusoap);
// call the parent constructor
parent::__construct($subject, $params);
}
The parent constructor is where the $this->params object gets set, so if you don't call it then $this->params is never set. That's why you get the error saying params is not an object.

Categories