Checking if user is logged in before inserting into database
Checking if user is logged in before inserting into database
globalplane
Posts: 70Questions: 12Answers: 0
What would be the best place to add a check that the user is logged in before performing an INSERT? If I have a variable set to true if logged in, then something like this:
if($_SESSION['loggedin']==true) {
$db->insert( 'staff-log', array(
'user' => $_SESSION['username'],
'action' => $action,
'values' => json_encode( $values ),
'row' => $id,
'when' => date('c')
) );
}
I'd prefer something built-in which gives feedback to the client-side, but I couldn't really understand the example in the Security section (I couldn't find where get() and set() are explained):
Editor::inst( $db, 'staff' )
->fields(
Field::inst( 'name' )
->set( $_SESSION['access']['editing'] )
Field::inst( 'location' )
->set( $_SESSION['access']['editing'] )
Field::inst( 'salary' )
->get( $_SESSION['access']['admin'] )
->set( $_SESSION['access']['admin'] )
);
This question has an accepted answers - jump to answer
Answers
Are they allowed to read the data if not logged in? If not, then you could to
header('Location: ...');
if they aren't logged in, effectively never allowing them to interact with this script.If they can read the data, and it is just the insert / edit / delete actions you want to do the authentication check on, then you could use a custom validation method. Check if the user is logged in and access rights for the action being performed. If not, throw back an error message.
Allan
Ok, I've mostly got this working, but I have a global validator on all three fields. And even though I'm submitting only one at a time, all three errors appear every time.
Here's the request that gets sent, showing that only one field is being submitted:
And the error:
Server code snippet:
Also, just to mention, the documentation says:
But if I do any of those things, it says "Error" on the client. If I
return true
, then it works.Full server code:
It looks like you've got the parameter named for a global validator on your field validators. It would be worth fixing that I reckon - it confused be a fair bit when looking at it. For example
$editor
in those functions is actually the value submitted.Your validator will run regardless of if the field is submitted or not (to allow for required validators). If
$val
isnull
then it was not submitted and in this case you should allow the validation to pass - i.e.:Allan
Oh, oops, sorry! Well, now I know I can just set a single global validator instead of three field validators and only get one error. Thanks!