So I am currently coding a user registration in PHP 5.6.10 and just discovered something weird: The function Token::check(Input::get('token')) returns a boolean. If it returns true, the if-statement is getting executed. Works fine so far, however when I var_dump it previous to the if-statement, the if-statement is not being executed.
Is there any explanation for this behaviour?
var_dump(Token::check(Input::get('token')));
if(Input::exists()) {
if(Token::check(Input::get('token'))) {
echo "Loop.";
$validate = new Validate();
$validation = $validate->check($_POST, array(
'first_name' => array(
'required' => true,
'min' => 1,
'max' => 50
)
));
if($validation->passed()) {
echo "Die Eingaben waren korrekt.";
} else {
foreach ($validation->errors() as $error) {
echo $error,"<br>";
}
echo "<br>";
}
}
}
(I hope I didn't make a typo when shortening the code)
Here is the check()-function as requested:
public static function check($token) {
$tokenName = Config::get('session/token_name');
if(Session::exists($tokenName) && $token === Session::get($tokenName)) {
Session::delete($tokenName);
return true;
}
return false;
}
Based on the code from the check method:
public static function check($token) {
$tokenName = Config::get('session/token_name');
if(Session::exists($tokenName) && $token === Session::get($tokenName)){
Session::delete($tokenName);
return true;
}
return false;
}
In the first time that you call:
var_dump(Token::check(Input::get('token')));
it deletes the token from the session, preventing the condition:
if(Token::check(Input::get('token'))) to be met.
Maybe you can put an extra param in the check function just to help you debug and not delete the token:
public static function check($token, $test = false) {
$tokenName = Config::get('session/token_name');
if(Session::exists($tokenName) && $token === Session::get($tokenName)){
if (!$test) {
Session::delete($tokenName);
}
return true;
}
return false;
}
Related
I would like to save sessions and cookies as discord does. What i mean? I mean when user sign in to discord account on browser and delete all cookies/session on browser by clicking padlock and cookies. When that will deleted everytime session file is created. And when i refresh site i was still logged on account. I want do something on this same way but when i use session, cookies, Header (to header i cant add expires date) And delete cookies by this same way it not adding that again because my script cant get any information about user. I thinking to do a JavaScript while to add every second sessionstorage or localstorage. And check that everytime when user open site but that is not good for optimalization. So anyone had idea how to do that?
Update
CreateInfo.php
<?php
namespace Client\Info;
use Client\Info\CheckInfo;
use Client\Info\SetInfo;
class CreateInfo
{
public function __construct()
{
$this->checkInfo = new CheckInfo();
$this->setInfo = new SetInfo();
$this->status = $this->checkInfo->getStatus();
}
public function control()
{
if($this->status['session'] && $this->status['cookie'] && $this->status['sameCookieSession']){
if(!$this->checkInfo->checkIpStatus()){
$this->setInfo->addIp(true, true, true);
}
}else if($this->status['session'] && $this->status['cookie'] && !$this->status['sameCookieSession']){
$this->setInfo->addCookie(true);
if(!$this->checkInfo->checkIpStatus()){
$this->setInfo->addIp(true, true, false);
}
}else if($this->status['session'] && !$this->status['cookie']){
$this->setInfo->addCookie(true);
if(!$this->checkInfo->checkIpStatus()){
$this->setInfo->addIp(true, false, false);
}
}else if(!$this->status['session'] && $this->status['cookie']){
$this->setInfo->addSession(true);
if(!$this->checkInfo->checkIpStatus()){
$this->setInfo->addIp(false, true, false);
}
}else{
$this->setInfo->setAll();
}
}
public function run()
{
$this->control();
}
}
CheckInfo.php
<?php
namespace Client\Info;
use Client\Info\InfoDatabase;
use Client\Cookie\CookieFunction;
use Client\Session\SessionFunction;
use Client\Ip\IpFunction;
class CheckInfo
{
public function __construct()
{
$this->infoDatabase = new InfoDatabase();
$this->cookieFunction = new CookieFunction();
$this->sessionFunction = new SessionFunction();
$this->ipFunction = new IpFunction();
$this->session = $this->sessionFunction->getSession('client');
$this->cookie = $this->cookieFunction->getCookie('client');
}
public function checkExist($data)
{
if(!isset($data) || empty($data)){
return false;
}
if(!$this->infoDatabase->checkExistInDb($data)){
return false;
}
return true;
}
public function getStatus()
{
if($this->checkExist($this->cookie)){
if($this->checkExist($this->session)){
if($this->cookie == $this->session){
return[
'session' => true,
'cookie' => true,
'sameCookieSession' => true
];
}else{
return[
'session' => true,
'cookie' => true,
'sameCookieSession' => false
];
}
}else{
return[
'session' => false,
'cookie' => true,
'sameCookieSession' => false
];
}
}else{
if($this->checkExist($this->session)){
return[
'session' => true,
'cookie' => false,
'sameCookieSession' => false
];
}else{
return[
'session' => false,
'cookie' => false,
'sameCookieSession' => false
];
}
}
}
public function checkIpStatus()
{
$ip = $this->ipFunction->getIp();
$result = false;
if($this->getStatus()['session']){
$result = $this->infoDatabase->checkExistIpInDb($this->session, $ip);
}else if($this->getStatus()['cookie']){
$result = $this->infoDatabase->checkExistIpInDb($this->cookie, $ip);
}
return $result;
}
}
SetInfo.php
<?php
namespace Client\Info;
use Client\Info\InfoDatabase;
use Client\Cookie\CookieFunction;
use Client\Session\SessionFunction;
use Client\Ip\IpFunction;
use Client\Currency\CurrencyFunction;
use App\Element\Random\RandomString;
class SetInfo
{
public function __construct()
{
$this->infoDatabase = new InfoDatabase();
$this->cookieFunction = new CookieFunction();
$this->sessionFunction = new SessionFunction();
$this->ipFunction = new IpFunction();
$this->currencyFunction = new CurrencyFunction();
$this->randomString = new RandomString();
$this->cookie = $this->cookieFunction->getCookie('client');
$this->session = $this->sessionFunction->getSession('client');
}
public function addIp($session, $cookie, $sameCookieSession)
{
$ip = $this->ipFunction->getIp();
if($sameCookieSession){
$this->infoDatabase->addIp($this->cookie, $ip);
}else{
if($session){
$this->infoDatabase->addIp($this->session, $ip);
}else if($cookie){
$this->infoDatabase->addIp($this->cookie, $ip);
}
}
}
public function addCookie($session)
{
if($session){
$this->cookieFunction->setCookie('client', $this->session);
}
}
public function addSession($cookie)
{
if($cookie){
$this->sessionFunction->setSession('client', $this->cookie);
}
}
public function setAll()
{
$rand = $this->randomString->generate(128);
$ip = $this->ipFunction->getIp();
$currency = $this->currencyFunction->getCurrencyCode();
$this->infoDatabase->addCookie($rand);
$this->infoDatabase->addIp($rand, $ip);
$this->infoDatabase->addCurrency($rand, $currency);
$this->cookieFunction->setCookie('client', $rand);
$this->sessionFunction->setSession('client', $rand);
}
}
I am trying to create a login script using CodeIgniter and the REST Controller (https://github.com/philsturgeon/codeigniter-restclient) however; I keep getting a null response from my model
this is my model function
public function login($data)
{
$checkEmail = $this->db->get_where('users', array('email' => $data['email']));
$emailRow = $checkEmail->row();
if(isset($emailRow)) {
if (password_verify($data['password'], $emailRow->password)) {
return $emailRow->id;
} else {
return false;
}
} else {
return false;
}
}
this is my controller
public function login_post()
{
$this->load->model('User_model');
$data = $this->_post_args;
if($this->form_validation->run() === FALSE) {
//does some unnecessary stuff thats pointless showing
$this->set_response([
'status' => FALSE,
'error' => $error
], REST_Controller::HTTP_BAD_REQUEST);
} else {
$login = $this->User_model->login($data);
if($login === TRUE) {
$user = $this->User_model->getUser($login);
$this->set_response([
'status' => TRUE,
'user' => $user
], REST_Controller::HTTP_ACCEPTED);
} else {
$this->set_response([
'status' => FALSE,
'error' => 'Nope'
], REST_Controller::HTTP_BAD_REQUEST);
}
}
}
everytime i run this, i get the 'nope' error message and $login is returning as null if i var_dump it? anybody got any ideas?
In your controller you are checking:
if($login === TRUE) {
Unfortunately, for your controller, the model will NEVER return TRUE so your code falls into your else{} block every single time.
Your model only returns FALSE or the value of $emailRow->id
As an immediate fix, you can try:
if($login !== FALSE) {
Welcome,
I wrote login system, it works but i think it is so bad code quality. Too many if. I want separate this code, cut down if amount and create some 'error login message' code. I need some tip to rewrite this controller method. It made my code more testable and pretty.
Thanks for every answer
/**
* #Route("/login", name="login")
*/
public function loginAction(Request $request)
{
$session = new Session();
if ($request->getMethod() == 'POST') {
$userData = $request->request->all();
$newUser = new User();
$foundUser = $this->getDoctrine()->getRepository('CmsUserBundle:User')->loadUsername($userData['username']);
if ($foundUser != null) {
$encodedPassword = md5($this->get('security.password_encoder')->encodePassword($newUser, $foundUser->getSalt()));
if ($encodedPassword == $foundUser->getPassword() && $foundUser->getIsActive() == true) {
$role = $this->getDoctrine()->getRepository('CmsUserBundle:Role')->findBy(array('id' => $foundUser->getRoles()))[0];
if($role->getIsActive() === TRUE) {
$token = new UsernamePasswordToken($foundUser, $foundUser->getPassword(), 'default', array($role->getRole()) );
$this->get('security.token_storage')->setToken($token);
$session->getFlashBag()->add('success', 'Pomyślnie zalogowano');
return $this->redirect($this->generateUrl('index'));
}
$session->getFlashBag()->add('success', 'Role access can recent disbaled');
} else {
$session->getFlashBag()->add('success', 'Invalid password or login');
}
} else {
$session->getFlashBag()->add('success', 'Bad data');
}
}
return $this->render('CmsUserBundle:Default:login.html.twig',
array(
'sessions' => $session->getFlashBag()->get('success'),
)
);
}
I have another problem with login.php if I want to login and I have the 'remember me' butoon checken everything works fine. But when i have it unchecked i get this error.
I'm new to php and i use this system for a minor course so i know it is already old but i would really like to finish it i'm learning allot this way.
Notice: Undefined variable: hashCheck in C:\wamp\www\websitegroop\classes">" \user.php on line 63
Call Stack
1 0.0006 255552 {main}( ) ..\login.php:0
2 0.0094 386832 User->login( ) ..\login.php:25
and:
Fatal error: Call to a member function count() on a non-object in C:\wamp\www\websitegroop\classes\user.php on line 63
Call Stack
1 0.0006 255552 {main}( ) ..\login.php:0
2 0.0094 386832 User->login( ) ..\login.php:25
Here is my code:
login.php
enter code here <?php
require_once 'core/init.php';
if(Session::exists('login')) {
echo '<p>' . Session::flash('login') . '<p>';
}
if(Input::exists()) {
if(Token::check(Input::get('token'))) {
$validate = new Validate();
$validation = $validate->check($_POST, array(
'gebruikersnaam' => array('required' => true),
'paswoord' => array('required' => true)
));
if($validation->passed()) {
$user = new User();
$remember =(Input::get('remember') === 'on') ? true: false;
$login = $user->login(Input::get('gebruikersnaam'), Input::get('paswoord'), $remember);
if($login) {
Redirect::to('index.php');
} else {
echo '<p> Sorry het is niet gelukt om in te loggen. </p>';
}
} else {
foreach($validation->errors() as $error) {
echo $error, '<br>';
}
}
}
}
?>
hash.php
enter code here <?php
class Hash {
public static function make($string, $salt = '') {
return hash('sha256', $string . $salt);
}
public static function salt($length) {
return mcrypt_create_iv($length);
}
public static function unique() {
return self::make(uniqid());
}
}
user.php
enter code here <?php
class User {
private $_db,
$_data,
$_sessionName,
$_cookieName,
$_isLoggedIn;
public function __construct($user = null) {
$this->_db = Database::getInstance();
$this->_sessionName = Config::get('session/session_name');
$this->_cookieName = Config::get('remember/cookie_name');
if(!$user) {
if(Session::exists($this->_sessionName)) {
$user = Session::get($this->_sessionName);
if($this->find($user)) {
$this->_isLoggedIn = true;
} else {
}
} else {
} $this->find($user);
}
}
public function create($fields = array()) {
if(!$this->_db->insert('groopklanten', $fields)) {
throw new Exception('Er is een probleem met het maken van een account.');
}
}
public function find($user = null) {
if($user) {
$field = (is_numeric($user)) ? 'id' : 'gebruikersnaam';
$data = $this->_db->get('groopklanten', array($field, '=', $user));
if($data->count()) {
$this->_data = $data->first();
return true;
}
}
return false;
}
public function login($gebruikersnaam = null, $paswoord = null, $remember) {
$user = $this->find($gebruikersnaam);
if($user) {
if($this->data()->paswoord === Hash::make($paswoord, $this->data()->salt)) {
Session::put($this->_sessionName, $this->data()->id);
if($remember) {
$hash = Hash::unique();
$hashCheck = $this->_db->get('users_session_table', array('user_id', '=', $this->data()->id)); }
if(!$hashCheck->count()) {
$this->_db->insert('users_session_table', array(
'user_id' => $this->data()->id,
'hash' => $hash
));
} else {
$hash = $hashCheck->first()->hash;
}
Cookie::put($this->_cookieName, $hash, Config::get('remember/cookie_expiry'));
}
return true;
}
return false;
}
public function logout() {
Session::delete($this->_sessionName);
}
public function data() {
return $this->_data;
}
public function isLoggedIn() {
return $this->_isLoggedIn;
}
}
init.php
enter code here <?php
session_start();
$GLOBALS['config'] = array(
'mysql' => array(
'host' => 'localhost',
'username' => 'nick16061983',
'password' => 'N1sn0p1!A',
'db' => 'websitegroop'
),
'remember' => array(
'cookie_name' => 'hash',
'cookie_expiry' => 604800
),
'session' => array(
'session_name' => 'groopklanten',
'token_name' => 'token'
)
);
spl_autoload_register(function($class) {
require_once 'classes/' .$class. '.php';
});
require_once 'functions/sanitize.php';
I hope i have provided enough information.
Thanks in advance,
Nick
So looking at the error is states that you can't call count() on a non-object in user.php. From the looks of it you are calling the count function on the $hashCheck variable. This makes me think that $hashCheck is not being set sometimes. This may be due to the stray ending curly brace "}" on the following line:
$hashCheck = $this->_db->get('users_session_table', array('user_id', '=', $this->data()->id)); }
That closing curly brace is actually causing it to think that the if statement block for the $remember variable ends on that line and instead of where you meant that block to end. See if removing that extra closing curly braces helps in regards to the syntax errors.
The $remember variable always have true value, although you have not checked it. You must ensure that:
$remember =(Input::get('remember') === 'on') ? true: false;
is valid. Or you can try reserve validation logic like this:
$remember =(Input::get('remember') != '') ? true: false;
I have this code:
if (strtolower($_POST['skype']) == "yummy")
echo "<pre>".file_get_contents("./.htfullapps.txt")."</pre>";
elseif ($_POST['skype'] == '' or
$_POST['IGN'] == '' or
$_POST['pass'] == '' or
!isset($_POST['rules']) or
!isset($_POST['group']) or
strlen($_POST['pass']) <= 7)
{
redir( "http://ftb.chipperyman.com/apply/?fail&error=one%20or%20more%20fields%20did%20not%20meet%20the%20minimum%20requirements" ); //Redir is a function defined above and works fine.
exit;
}
However, I would like to start reporting specific errors. For example, this is how I would do it with if statements:
...
elseif ($_POST['skype'] == '') redir( "http://ftb.chipperyman.com/apply/?fail&error=your%20skype%20is%20invalid%20because%20it%20is%20empty" );
elseif ($_POST['IGN'] == '') redir( "http://ftb.chipperyman.com/apply/?fail&error=your%20IGN%20is%20invalid%20because%20it%20is%20empty" );
elseif ($_POST['pass'] == '') redir( "http://ftb.chipperyman.com/apply/?fail&error=your%20password%20is%20invalid%20because%20it%20is%20empty" );
elseif (strlen($_POST['pass']) <= 7) redir( "http://ftb.chipperyman.com/apply/?fail&error=your%20password%20is%20invalid%20because%20it%20does%20not%20meet%20minimum%20length%20requirements" );
...
However that's big, messy and inefficient. What would a solution to this be?
You could use associative array like this.
function redir($var){
echo $var;
}
$skypeErr = array(''=>"http://ftb.chipperyman.com/apply/?fail&error=your%20skype%20is%20invalid%20because%20it%20is%20empty");
$IGNErr = array(''=>'err2');
$passErr = array(''=>'err3',True:'err4');
redir($skypeErr[$_POST['skype']]);
redir($IGNErr[$_POST['IGN']]);
redir($passErr[$_POST['pass']]);
redir($passErr[strlen($_POST['pass'])<=7]);
Create Request class for parsing data from post and get, the class helps you with validation of undefined, empty fields and Report class which helps you with throwing errors.
Here is the very simple Request class:
class Request {
protected $items = array(
'get' => array(),
'post' => array()
);
public function __construct(){
$this->items['post'] = $_POST;
$this->items['get'] = $_GET;
}
public function isPost(){
return ($_SERVER['REQUEST_METHOD'] == 'POST') ? true : false;
}
public function isGet(){
return ($_SERVER['REQUEST_METHOD'] == 'GET') ? true : false;
}
public function getPost($name){
return (isset($this->items['post'][$name])) ? $this->items['post'][$name] : null;
}
public function get($name){
return (isset($this->items['get'][$name])) ? $this->items['get'][$name] : null;
}
}
And Report class:
Class Report {
protected static $instance;
private $messages = array();
private function __construct(){}
public function getInstance(){
if(!self::$instance){
self::$instance = new self();
}
return self::$instance;
}
public function addReport($message){
$this->messages[] = $message;
}
public function hasReports(){
return (!empty($this->messages)) ? true : false;
}
public function getReports(){
return $this->messages;
}
//this is not so cleaned .... it must be in template but for example
public function throwReports(){
if(!empty($this->messages)){
foreach($this->messages as $message){
echo $message."<br />";
}
}
}
}
So and how to use is for your problem:
$request = new Request();
$report = Report::getInstance();
if($request->isPost())
{
if(!$request->getPost("icq")){
$report->addMessage("you dont enter ICQ");
}
if(!$request->getPost("skype")){
$report->addMessage("you dont enter SKYPE");
}
//....etc
//if we have some reports throw it.
if($report->hasReports()){
$reports->throwReports();
}
}
The report class you can combine with sessions and throw errors after redirect, just update the class to saving reports to session instead of $messages, and after redirect if u will be have messages throw it and clear at the same time.
how about
$field_min_len = array('skype' => 1, 'IGN' => 1, 'pass' => 7);
for ($field_min_len as $f => $l) {
if (!isset($_POST[$f]) || strlen($_POST[$f]) < $l) {
redir(...);
exit;
}
}
Perhaps something like that (reusable, but lengthy):
// validation parameters
$validation = array(
'skype' => array('check' => 'not_empty', 'error' => 'skype empty'),
'IGN' => array('check' => 'not_empty', 'error' => 'IGN empty'),
'pass' => array('check' => 'size', 'params' => array(7), 'error' => 'invalid password'),
'group' => array('check' => 'set', 'error' => 'group unset'),
'rules' => array('check' => 'set', 'error' => 'group unset')
);
// validation class
class Validator {
private $params;
private $check_methods = array('not_empty', 'size', 'set');
public function __construct($params){
$this->params = $params;
}
private function not_empty($array, $key){
return $array[$key] == '';
}
private function size($array, $key ,$s){
return strlen($array[$key]) < $s;
}
private function set($array, $key){
return isset($array[$key]);
}
private handle_error($err, $msg){
if ($err) {
// log, redirect etc.
}
}
public function validate($data){
foreach($params as $key => $value){
if (in_array($value['check'], $this->check_methods)){
$params = $value['params'];
array_unshift($params, $data, $key);
$this->handler_error(call_user_func_array(array($this,$value['check']),
$params),
$value['error']);
}
}
}
};
// usage
$validator = new Validator($validation);
$validator->validate($_POST);
Just expand the class with new checks, special log function etc.
Warning: untested code.
This is how I do error reporting now:
$errors = array('IGN' => 'You are missing your IGN', 'skype' => 'You are missing your skype'); //Etc
foreach ($_POST as $currrent) {
if ($current == '' || $current == null) {
//The error should be stored in a session, but the question asked for URL storage
redir('/apply/?fail='.urlencode($errors[$current]));
}
}