Adding a 'fake' field to grocerycrud add/edit form - codeigniter

On my users table I have a 128 char 'hashed_password' field. In my User_model I have functions to encrypt and decrypt the password. When encrypting I randomly generate a salt and it gets stored in the first 64 chars of hashed_password field. The hashed pw result gets stored in the last 64 chars. When decrypting I do the reverse.
As I guess is almost universal, there is never a plaintext password to display.
So, when my users (through grocery_CRUD) are adding/editing a user I thought it was possible to include fake fields: "password" and "passconf" to the add & edit forms with the following:
$crud->fields('username', ... <other fields> ... 'password', 'passconf');
Just to be crystal clear - the "password" and "passconf" fields DO NOT exist on my users table. I just want my users to input the new password there then deal with it in my own way.
But it doesn't work. By that I mean the add/edit form renders with the two fake fields correctly (validation below works correctly) but if I try to update any other user information then 'Update Changes', that action fails with "Loading" graphic spinning briefly but not updating the database.
I have tried replicating this on a VERY simply grocery_CRUD form with no other complexity and get the same behaviour: the form renders correctly but will not update the db.
Is it even possible to use fake fields? Am I missing something?
Is grocery_CRUD trying to do something with these fields behind the scenes that is causing the db update to fail?
I had then hoped to do the following:
$crud->set_rules('password', 'Password', 'callback_valid_password');
$crud->set_rules('passconf', 'Password Confirmation', 'matches[password]');
$crud->callback_before_insert(array($this,'encrypt_password_callback'));
$crud->callback_before_update(array($this,'encrypt_password_callback'));
function encrypt_password_callback($post_array, $primary_key = null){
if ($post_array['password'] <> '') {
$this->User_model->set_password($post_array['username'], $post_array['password']);
}
}
function valid_password($str) {
//do some pw validation
return TRUE;
}

I have solved this problem using insert and update callbacks then encrypting the password then unset(ing) the offending 'password' & 'passconf' fields before the insert or update db call.

Related

How can update and save column in ruby activerecord in one command?

i'm doing this:
work_status.progress = 90
work_status.save!
and i'd like to do this:
work_status.progress.set! 90
Do you know of a way to do this elegantly?
Just do as
work_status.update_attribute(progress: 90)
update_attribute
Updates a single attribute and saves the record without going through the normal validation procedure.
If you want to perform validations when updating, use #update_attributes instead.
You can also do :-
work_status.update(progress: 90)
update
Updates the attributes of the model from the passed-in hash and saves the record, all wrapped in a transaction. If the object is invalid, the saving will fail and false will be returned.
There are two methods to do this update_attribute and update_column. They both have the same signature:
work_status.update_attribute(:progress, 90)
work_status.update_column(:progress, 90)
There is however one important difference between those methods. update_attribute is evil - it is saving the whole model, not only given attribute and it skips all the validations. Imagine following snippet of code:
user.email = 'invalid email'
user.update_attribute(:points, 90)
This will save an email attribute as well, even though it is invalid (since update_attribute do not validate model)
Instead, you should use update_column which only saves a single attribute to a database leaving the rest as they are:
user.email = 'invalid email'
user.update_column(:points, 90) # this updates points column in database
user.email # => 'invalid email'
user.reload.email # 'invalid email' has not been saved in database

Is it possible to set user parametr in joomla without session?

The default JUser::setParam() method sets parameters only to the session. Is is possible somehow to store parameters not in the session, that they would be always available? I also found in users table field params, which stores some parameters for current user, but don't know how to add data there...
Have you tried to save the object after adding your param?
$user = JFactory::getUser();
$user->setParam($key, $value);
$user->save;
An easy and comfortable approach would be to use the popular Community Builder Extension which lets you define custom user fields in the administrator backend. It has an API to obtain the CB User Object and to write and read those fields which get stored in the DB as opposed to the session. Simple example without knowing your Joomla/CB version (works with Joomla 2.5 and CB 1.8) and the place (site, admin, external) where this should be executed (assuming your parameter is named customParam and the user id is 42):
cbimport( 'cb.field' );
$mosCbUser = CBUser::getUserDataInstance(42);
// read value
$customParameter = $mosCbUser->customParam;
// write value
$mosCbUser->customParam = 'newnew';
$mosCbUser->store();
/* write value to DB directly with optional boolean third parameter
specifing whether to trigger the user update plugins
like onBeforeUserUpdate or onAfterUserUpdate
*/
$mosCbUser->storeDatabaseValue('cb_adresse', 'new address', false);
be sure to be in CB plugin context, if not already the case, include e.g. like
global $_CB_framework, $_CB_database, $ueConfig;
$app = JFactory::getApplication();
include_once( $app->getCfg( 'absolute_path' ) . '/administrator/components/com_comprofiler/plugin.foundation.php' );

Checking if specific user is online through php session variable

I'm currently trying to display all online users on my webpage using the php session variables. To do this, whenever a user logs in or out, a column in a database gets set to "online" or "offline".. However this doesn't entirely work since the database doesn't get updated when the user closes their browser (and therefor destroys the session).
So is there another way of checking if a certain sessionid is set??
Currently I am setting the session like this:
session_start();
$_SESSION['username']="Example Username";
To check from the current users page if there is a session variable set we can simply use:
if(isset($_SESSION['username']))
{
//username is set
}
But if we need to check if a specific user is online, how do we get for instance an array of all the session variables that have been set? e.g.
//Get all $_SESSION['username'] vars
//loop through array and check for specific $_SESSION
for($i=0; ... )
{
if( $_SESSION['username'][$i] == "User 1" )
{
//do something
}
}
From all that I've read so far, there doesn't seem to be a way to get an array of all sessions on your page..
So is there a better way of doing it, e.g. how do facebook, twitter, etc handle this stuff?
Thanks for your help!
One solution is to store a timestamp in your database in addition to the online/offline flag that records the last time a user accessed any of your website resources. Then you might just consider them offline after 15 minutes or some other constant value.
The other solution is to play with the callbacks here http://php.net/manual/en/function.session-set-save-handler.php where I think you can handle the gc callback and set the offline flag in your database.
If you search on that page for class SessionDB or go here it looks like somebody has implemented some version of this already in a custom class!
you can use a simple update query
for example you have a table users and in that you have a column called status(online/offline)
on your login.php use
<?php
//your user verification code
if(variable that holds your sql query){
$user_status=('UPDATE user SET status= online WHERE email="'your user email selector'")
}
then on the logout do a similar script just change the online value to offline
You could try this:
foreach ($_SESSION as $sessionKey => $sessionValue)
{
if( $sessionKey == 'username' ) && ( $sessionValue == 'User 1' )
{
//do something
}
}

Propel ORM Version 1.6.4 -understanding validators

(reworded the question hours later to be more descriptive)
I need a little advice on understanding Propel setters/validators in a standalone (non-framework) development.
The documentation on validation states:
Validators help you to validate an input before persisting it to the database.
... and in validator messages we can provided coherent advice on where users can correct entries that don't pass Propel validation.
The sample usage of a validator reads:
$user = new User();
$user->setUsername("foo"); // only 3 in length, which is too short...
if ($objUser->validate()) {
...
The problem I have found with this is 'what if you cannot setXXX() in order to validate it?'
I have a column type DATE and I invite a visitor to enter a date in a web form. They mistype the date and submit 03/18/20q2
I would hope that one of my custom validators would be able to report a validator message and return the form once more to the user to be amended, however this occurs first:
Fatal error: Uncaught exception 'PropelException' with message 'Error parsing date/time value: '03/18/20q2' [wrapped: DateTime::__construct() [<a href='datetime.--construct'>datetime.--construct</a>]: Failed to parse time string (03/18/aaa) at position 5 (/):
In my tests I couldn't get any simple or CustomValidator to fire once I'd written (for example):
$event= new Event();
$event->setDateStart($form_value_for_date); // where values is "03/18/20q2"
I understand why this is so - it would not make sense to be able to create and try to manipulate a new object if you cannot rely on its fields, even before you save it.
The dilemma this gives me is:
If a fatal error can result from invalid entry preventing Propel validation from handling it for me (and therefore the user) and sending back a useful message, should I bother with Propel validation as well as my own security/courtesy validation ?
I cannot find any mention in the docs of what happens if you give Propel - for whatever reason - a value it doesn't anticipate for the field, or how to handle it.
I do hope this makes sense and that someone can point me at a method that will mean I only need to validate input in one place.
I've hacked together a rough ready solution that will allow me to:
Pre-validate a field against a CustomValidator without setting it in the new object
Retrieve the validator's message for return to the user
I take the form input, sanitise it of course, and then create an object:
$event = new Event();
With my user form in mind, I then pre-check the field I know will fatally fall over if the content's bad, and only set the field in my new object if it would validate:
if ($check = $event->flightCheckFail('StartingDate','DateValidator',$sanitisedFormVal))
echo $check;
else
$event->setStartingDate($sanitisedFormVal);
Method flightCheckFail() will return false if the data from the form would validate against the field, it returns the validator's error message if it would fail.
The method's added to my Event class as follows. Its arguments are the field name, the class of the CustomValidator (which simply runs an strtotime check), and the sanitised form value:
public function flightCheckFail($name,$validatorClass,$value) {
$colname = $this->getPeer()->getTableMap()->getColumnByPhpName($name)->getName();
$validators = $this->getPeer()->getTableMap()->getColumn($colname)->getValidators();
foreach($validators as $validatorMap)
if ($validatorMap->getClass() == $validatorClass) {
$validator = BasePeer::getValidator($validatorMap->getClass());
if ( $validator->isValid($validatorMap, $value) === false)
$failureMessage = $validatorMap->getMessage();
} // if $validatorMap->getClass() == $validatorClass
if($failureMessage)
return $failureMessage;
else
return false;
}
I should be able to use this to work around handling dates in forms, but I'll need to check what other types in Propel might require this sort of handling.
I can stop the form handling wherever this reports a validator error message and send it back. When the user enters valid data, Propel (and normal Propel Validation) gets to continue as normal.
If anyone can improve on this I'd love to see your results.
You could also use a MatchValidator, with a date RegExp, no need for extra functions

CakePHP validation rule to match field1 and field2

I am making a password reset form, which contains two fields: password1 and password2. The user enters their new password and then re-types their new password again.
I'm not sure how to make a validation rule that will compare the two values from the fields and see if they're the same.
IMHO it's more trouble than worth to create a separate rule in this case. You could, if you want to code "pure" CakePHP, but it's easier to just compare the fields in the controller and invalidate one of them manually if they don't match:
if( $this->data[ 'User' ][ 'password1' ] != $this->data[ 'User' ][ 'password2' ] ) {
$this->User->invalidate( 'password2', "The passwords don't match." );
}
if you are using Auth component then you need to hash the second password in the controller, because the password will be automatically hashed.
To compare 2 fields, you need to write a custom validation rule: http://bakery.cakephp.org/articles/aranworld/2008/01/14/using-equalto-validation-to-compare-two-form-fields (read the comments also, because the tutorial itself is kind of old)
I just happen to have written a behavior for this 2 days ago:
https://github.com/dereuromark/tools/blob/master/Model/Behavior/PasswordableBehavior.php
some sample code how to use it:
http://www.dereuromark.de/2011/08/25/working-with-passwords-in-cakephp/

Resources