How can use setstate in Yii - php

I want create random session after successful sign in and destroy it after log out.
How can do it? I used $this->user->setState
I added this code
class UserIdentity extends CUserIdentity {
protected $_id;
public function authenticate(){
$user = User::model()->find('LOWER(username)=?', array(strtolower($this->username)));
if(($user===null) || ($this->password!==$user->password)) {
$this->errorCode = self::ERROR_USERNAME_INVALID;
} else {
$this->_id = $user->id;
$this->username = $user->username;
$this->user->setState('random',Yii::app()->user->random);
$this->errorCode = self::ERROR_NONE;
}
return !$this->errorCode;
}
public function getId(){
return $this->_id;
}
}

Use $this->setState instead of $this->user->setState

Related

PHP error printing inside class

I'm trying to play with a class and not understand how it works. Some people explained how to pass variables between a function. My problem at the moment is errors. And how to extract errors from the class and print to the screen. My output is username only. How to get errors?
class form
{
protected $username;
protected $password;
protected $errors = array();
function __construct($username, $password){
$this->username = $username;
$this->password = $password;
}
public function get_errors()
{
return $this->errors;
}
public function getPassword(){
return $this->password;
}
public function getUserName() {
return $this->username;
return $this->errors = "No MySQL connection.";
}
}
$test = new form('name1', 'passw2');
echo $test->getUserName();
You can not return two time inside a function. But you can achieve what you want like below:-
public function getUserName() {
$this->errors = "No MySQL connection.";
return $this->username.'<br/>'.$this->errors;
}
Note:- this is the solution but your code have no mean. You have to do some useful stuff
try throw exception
public function getUserName() {
if($this->errors) {
throw new Exception($this->errors);
}
return $this->username;
}
$test = new form('name1', 'passw2');
try {
echo $test->getUserName();
} catch(Exception $error) {
echo 'Error:'.$error->getMessage();
}
If you get error you can simple catching this error and output to web,console or error log;
class form
{
protected $username;
protected $password;
protected $errors = array();
function __construct($username, $password){
$this->username = $username;
$this->password = $password;
}
public function getErrors()
{
return $this->errors;
}
public function getPassword()
{
return $this->password;
}
public function getUserName()
{
/* Add some an error to an error's array */
$this->errors[] = "No MySQL connection.";
return $this->username;
}
}
$test = new form('name1', 'passw2');
echo $test->getUserName();
var_dump($test->getErrors()); /* Get errors from a class */

Php - Password hashing

I've made this password class as you can see below:
<?php
namespace lib\Api;
class Password{
private $password;
private $salt;
private $hash;
public function __construct($password,$salt = ""){
$this->password = $password;
$this->salt = $salt;
$this->generateHash($this->password,$this->salt);
}
public function generateHash($password,$salt = ""){
$this->hash = hash('sha256',$password.$salt);
return $this->hash;
}
public function get(){
return $this->hash;
}
public function equals($password){
if($this->hash == $password){
return true;
}
return false;
}
}
?>
So i use this to register a user in a user.php file/class
$this->password = (new Password($password,$this->getSalt()))->get();
, i also use this too again check this in a login.php file/class
if((new Password($this->password,$salt))->equals($password)){
return true;
}
return false;
. Now i know that if you hash something that it depends in wich file it is, how it hashes the value. In this partical case it confuses me very much, as i both officialy hash it in the password.php file/class. How does this work and how can i solve it easily and nicely?
It's hard to understand what you're asking, but I bet you want to hash the value of $password before you check it's equality.
<?php
namespace lib\Api;
class Password{
private $password;
private $salt;
private $hash;
public function __construct($password,$salt = ""){
$this->password = $password;
$this->salt = $salt;
$this->hash = $this->generateHash($this->password);
}
public function generateHash($password){
return hash('sha256',$password.$this->salt);
}
public function get(){
return $this->hash;
}
public function equals($password){
if($this->hash == $this->generateHash($password){
return true;
}
return false;
}
}

access $this in extended class

I've been following a tutorial about OOP programming. And I got this class named User:
class User {
private $_db,
$_data,
$_sessionName,
$_isLoggedIn;
public function __construct($user = null) {
$this->_db = DB::getInstance();
$this->_sessionName = Config::get('session/session_name');
if (!$user) {
if (Session::exists($this->_sessionName)) {
$user = Session::get($this->_sessionName);
if ($this->find($user)) {
$this->_isLoggedIn = true;
} else {
// Process logout
}
}
} else {
$this->find($user);
}
}
public function update($fields = array(), $id = null) {
if (!$id && $this->isLoggedIn()) {
$id = $this->data()->id;
}
if (!$this->_db->update('users', $id, $fields)) {
throw new Exception('De gegevens konden niet gewijzigd worden');
}
}
public function create($fields = array()) {
if (!$this->_db->insert('users', $fields)) {
throw new Exception('Het account is niet aangemaakt');
}
}
public function find($user = null) {
if ($user) {
$field = (is_numeric($user)) ? 'id' : 'email';
$data = $this->_db->get('users', array($field, '=', $user));
if ($data->count()) {
$this->_data = $data->first();
return true;
}
}
}
public function login($email = null, $password = null) {
$user = $this->find($email);
if ($user) {
if ($this->data()->password === hash::make($password)) {
session::put($this->_sessionName, $this->data()->id);
return true;
}
}
return false;
}
public function logout() {
session::delete($this->_sessionName);
}
public function hasPermission($key) {
$group = $this->_db->get('user_role', array('id', '=', $this->data()->rank));
if ($group->count()) {
$permissions = json_decode($group->first()->permission, true);
if ($permissions[$key] == true) {
return true;
}
}
return false;
}
public function data() {
return $this->_data;
}
public function isLoggedIn() {
return $this->_isLoggedIn;
}
}
Each user has different quicklinks stored in the database. I tried to extend the class User with class Link like this:
class Link extends User {
public static function getUserLinks($user) {
if ($user) {
$data = $this->_db->get('user_links', array('uid', '=', $user));
if ($data->count()) {
$this->_data = $data->results();
return $this->_data;
} else {
echo 'No matches found';
}
}
return false;
}
But I get an error message :
Fatal error: Using $this when not in object context in ... on line 153
I thought that when extending a class I can access all the parents details?
What am I doing wrong? Also, is my logic correct behind class Link extends User?
Thanks for the help.
you are trying to access the class pointer within a static method, that's impossible since static methods belongs to the class itself and not to the instance.
you could have a static property that will hold your instance, then you could do that like so: (You'll have to make sure you got an instance of Link)
class Link extends User {
public static $instance;
public function __construct() {
parent::__construct();
self::$instance = $this;
}
public static function getUserLinks($user) {
if (self::$instance instanceof Link && $user) {
$data = self::$instance->_db->get('user_links', array('uid', '=', $user));
if ($data->count()) {
self::$instance->_data = $data->results();
return self::$instance->_data;
} else {
echo 'No matches found';
}
}
return false;
}
}

Wordpress screwing up PHP Session and form validation token not matching

For some reason when it generates a token it stores another token in the session and it is a completely random token.
Here is my code for the Token class -
class Token {
protected static $token;
public static function generate() {
if(!self::$token){
self::$token = md5(uniqid());
}
return Session::put(Config::get('session/token_name'), self::$token);
}
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;
}
}
And here is my code from my Session class -
class Session {
public static function exists($name) {
return (isset($_SESSION[$name])) ? true : false;
}
public static function get($name) {
return $_SESSION[$name];
}
public static function put($name, $value) {
return $_SESSION[$name] = $value;
}
public static function delete($name) {
if(self::exists($name)) {
unset($_SESSION[$name]);
}
}
public static function flash($name, $string = null) {
if(self::exists($name)) {
$session = self::get($name);
self::delete($name);
return $session;
} else if ($string) {
self::put($name, $string);
}
}
}
Config::get('session/token_name') just returns 'token'
No where else am I generating a new token, and it wouldn't matter anyways as it will just return one token because of the static variable.
Why is WordPress doing this?
Please help I have been trying to get this to work for over 10 straight hours!
For the generate function -
public static function generate() {
if(!Session::get(Config::get('session/token_name'))){
return Session::put(Config::get('session/token_name'), md5(mt_rand()));
}
else{
return Session::put(Config::get('session/token_name'), Session::get(Config::get('session/token_name')));
}
}
This ensures that you only create one for each session.

How to pass data from model to view(or to controller)

The question is simple:
How can i pass data from model to view(or back to the controller) to display errors like "your password is too short"
Here is the controller
class UsersController extends Controller {
private $username;
private $password;
function register()
{
if($_POST)
{
$this->User->username = $_POST['username'];
$this->User->password = $_POST['password'];
$this->User->register();
}
}
}
the model
class User extends Model {
public $username;
public $password;
function register()
{
$username = $this->username;
$password = $this->password;
if (!empty($username) && !empty($password))
{
// registration process
}
else
{
// "you must provide a username and password" or something like that
}
}
Just have your register function in your model return "PASSWORD"; to the controller and have your controller take the return from the model and return it to the view. Let the view interpret what the error output for "PASSWORD" is.
Example:
the controller
class UsersController extends Controller {
private $username;
private $password;
function register()
{
if($_POST)
{
$this->User->username = $_POST['username'];
$this->User->password = $_POST['password'];
return $this->User->register();
}
}
}
the model
class User extends Model {
public $username;
public $password;
function register()
{
$username = $this->username;
$password = $this->password;
if (!empty($username) && !empty($password))
{
// ...
return "SUCCESS";
}
else
{
return "PASSWORD";
}
}
}
the view
$responses = array("SUCCESS" => "Registered Successfully!", "PASSWORD" => "You must provide a username and password!");
$result = $this->UsersController->register();
echo $responses[$result];
Simply have your model methods to return a value, or throw exceptions, like any normal method. Then handle it in the controller. The view shouldn't touch the data directly from the model, that's the controller's job.
public function addAction()
{
$form = $this->_getForm();
$this->view->form = $form;
$this->render('add', null, true);
}
public function editAction()
{
$id = $this->getRequest()->getParam(0);
$Model = DI::get('yourclass_Model');
$form = $this->_getForm();
$data = $Model->getData();
$form->populate($data);
$this->view->flashMessages = $this->_helper->FlashMessenger->getMessages();
$this->view->form = $form;
$this->render('add', null, true);
}
public function saveAction()
{
$form = $this->_getForm();
$Model = DI::get('yourclass_Model');
try{
$saved = $Model->saveForm($form, $_POST);
} catch (Exception $e) {
echo "<pre>";
print_r($e);
exit;
}
if($saved)
{
$this->_helper->FlashMessenger('Record Saved!');
$this->_redirect("edit".$form->id->getValue(), array('exit'=>true));
}
$this->view->errorMessage = 'There were some errors';
$this->view->form = $form;
$this->render('add', null, true);
}
Create a class which implements Singleton pattern and ArrayAccess interface.
Or create something similar with dependency injection.
The ultimate solution would be if you create some validation architecture. (The model validates its self and it's error state is available in the views.)

Categories