I'm trying to store a database value to a variable in a controller. But i'm getting this error "Object of class Illuminate\Support\Collection could not be converted to int", i know what it means but i don't know how to fix it.
What i want is that if user is banned, then change $banned to true and return it.
private function isBanned() {
$banned = false;
$getBanned = DB::table('Uzivatele')->select('banned')->where('id', Auth::id())->get();
if ($getBanned == 1) $banned = true;
return $banned;
}
if you want to set it directly you can do this way
$getBanned = DB::table('Uzivatele')->where('id', Auth::id())
->update(['banned' => true])->get();
if you want to check the user is banned or not then you can check like this.
private function isBanned() {
$banned = false;
$getBanned = DB::table('Uzivatele')->select('banned')->where('id', Auth::id())->first();
if ($getBanned->banned == 1) $banned = true;
return $banned;
}
Related
I'm trying to modify the json output of authenticate method of JWT in laravel to make it to display roles as an array.
So here i
created_at
:
"2016-08-18 12:33:14"
email
:
"dhenn.espiritu#gmail.com"
id
:
1
last_logged_in
:
"2016-09-21 16:37:35"
name
:
"Dhenn"
roles
:
"{0: admin,
1: user"}
updated_at
:
"2016-09-21 16:37:35"
But I can't. I tried to modify my jwt.auth php file but it returned me an error that i am setting a non property object.
Here's current setup of the jwt-auth.php
public function authenticate($token = false)
{
$id = $this->getPayload($token)->get('sub');
if (! $this->auth->byId($id)) {
return false;
}
$user = $this->auth->user();
return $user;
}
While, I'm having error trying this:
public function authenticate($token = false)
{
$id = $this->getPayload($token)->get('sub');
if (! $this->auth->byId($id)) {
return false;
}
$user = $this->auth->user();
foreach ($user as $roles) {
$roles->roles = explode(",", $roles->roles);
}
return $user;
}
You said this is your user object:
{ email : "dhenn.espiritu#gmail.com"
id : 1
last_logged_in : "2016-09-21 16:37:35"
name : "Dhenn"
roles : "{0: admin, 1: user"}
updated_at : "2016-09-21 16:37:35" }
Assuming $this->auth->user(); returns this, your iteration foreach ($user as $roles) { is not correct, since $user should be an object not an array. This way you try to go through each property of this object, but I figure you want to iterate of the roles array.
This should be something like:
foreach($user->roles as $role) ... // assuming roles is an array
But roles seems to be a encoded JSON string, so you need to decode it too.
foreach(json_decode($user->roles) as $role) ...
Or directly: $user->roles = json_decode($user->roles)
Try to add
protected $casts = ['roles' => 'array'];
to your User model. That should ensure that the attributes are parsed correctly.
Here is the link to the docs https://laravel.com/docs/5.3/eloquent-mutators#attribute-casting
OK, thanks all for your help. I figured out the answer.
Here's my code that worked finally.
public function authenticate($token = false)
{
$id = $this->getPayload($token)->get('sub');
if (! $this->auth->byId($id)) {
return false;
}
$user = $this->auth->user();
$user->roles = explode(",", $user->roles);
return $user;
}
I am writing a method that uses POST variables posted by AJAX to add a user to a certain course in the database, but I can't get the callback to work correctly:
public function enroll()
{
$package = array();
$this->load->library('form_validation');
$this->form_validation->set_rules('course', 'Vak', 'required|callback_not_enrolled');
$fields = array("course");
if ($this->form_validation->run($this) === FALSE) {
$errors = array();
$success = array();
foreach ($fields as $field) {
$error = form_error($field);
if ($error !== "") {
$errors[$field] = $error;
} else {
$success[$field] = True;
}
}
$package["field_errors"] = $errors;
$package["field_success"] = $success;
$package["success"] = False;
} else {
$package["database"] = $this->course_model->enroll_user($this->data["user"], $this->input->post("course"));
$package["success"] = True;
}
echo json_encode($package);
}
I wrote the callback not_enrolled to check if the user is not already enrolled to the database. Note that I can't use is_unique because I have to test the combined uniqueness of two fields (so just one or two separate ones don't do the trick) and the id of the user is not included in the form (because it's part of the Code Igniter session).
The callback function:
public function _not_enrolled($course)
{
$exists = ($this->user->is_enrolled($course, $this->data["user_id"]) != False);
if ($exists != False) {
$this->form_validation->set_message("not_enrolled", "Already enrolled");
return False;
} else {
return True;
}
}
And finally the method is_enrolled from the model:
public function is_enrolled($course, $user=False) {
if($user==False){
$user = $this->data["user_id"];
}
$this->db->select()->from("course_participant")->where("user_id", $user)->where("course_id", $course);
$query = $this->db->get();
return($query->num_rows()>0);
}
Through a call to var_dump($this->_not_enrolled($existing_course_id)); I know that both the callback function and the method from the model work, as it correctly returned true.
When I var_dump the $package array or validation_errors() I don't get any validation errors except that it says Unable to access an error message corresponding to your field name Vak(not_enrolled).
I tried removing the initial _ from the function name but that gives me a Server Status 500 error.
I have another setup exactly like this, albeit other database calls, with a callback using the same syntax. This method works perfectly.
For my project I need to check if some variables are empty and if they are then:
The user gets a custom view with a message on which variable is missing.
The developer/me must be able to see the query which was sent to check if there are no failure's in the query.
My question is how can I assign a variable (for example $checkQuery) to my query so that it has all the values and I can check it within the error log.
Query
function createUser($data){
$this->firstname = $data['firstname'];
$this->lastname = $data['surname1'].' '.$data['surname2'];
$this->address = $data['adres'];
$this->zipcode = $data['zipcode'];
$this->mail = $data['mail'];
$this->phonenumber = $data['phonenumber'];
$this->db->insert('User',$this);
//Check if the change was succesfull
return ($this->db->affected_rows() != 1) ? false : true;
}
Function for errorLog
function errorLog($var){ //Get the variable that you have passed from your helper
$mail = "Email was empty";
$firstname ="Firstname was empty";
if($var == 'mail') //Change the error function based on what has been passed
{
return log_message('error', $mail); //Here use the return type
}
if($var == 'firstname')
{
return log_message('error', $firstname); //Here use the return type
}
}
The view for the user is done which I've done with just a simple array but the only thing I see at the moment is just if firstname or email is was empty.
So is it possible to use a PHP variable in which I can assign the submitted values and can put these into my error log preferably using log_message
I found this great code snippet that works wonderfully during circumstances that change a user’s credentials during that user’s session. The hasCredential() method defaults to looking at the database rather than the user’s session - which meets my needs perfectly (as a user’s credentials are often changed programmatically during a user’s session). So I really need to keep this functionality.
However, for circumstances that have multiple credentials, either an OR circumstance: [[A, B]] or an AND circumstance: [A, B] the code snippet fails as it only checks for the one instance and does not read the yaml security file for AND OR instances.
I’m looking for help with how to tweak the code snippet to take into account AND OR yaml credential permissions. Here’s the code snippet:
public function hasCredential($permission_name)
{
//this overrides the default action (hasCredential) and instead of checking
//the user's session, it now checks the database directly.
if (!$this->isAuthenticated()) {
return false;
}
$gu = $this->getGuardUser();
$groups = $gu->getGroups();
$permissions = $gu->getPermissions();
$permission_names = array();
foreach($permissions as $permission) {
$permission_names[] = $permission->getName();
}
foreach($groups as $group) {
$group_permissions = $group->getPermissions();
foreach($group_permissions as $group_permission) {
$permission_names = array_merge($permission_names, array($group_permission->getName()));
}
}
$permission_names = array_unique($permission_names);
return (in_array($permission_name, $permission_names)) ? true : false;
}
EDIT:
I think I need to merge the above code with the original hasCredential() below but I'm struggling with the logic:
public function hasCredential($credentials, $useAnd = true)
{
if (null === $this->credentials)
{
return false;
}
if (!is_array($credentials))
{
return in_array($credentials, $this->credentials);
}
// now we assume that $credentials is an array
$test = false;
foreach ($credentials as $credential)
{
// recursively check the credential with a switched AND/OR mode
$test = $this->hasCredential($credential, $useAnd ? false : true);
if ($useAnd)
{
$test = $test ? false : true;
}
if ($test) // either passed one in OR mode or failed one in AND mode
{
break; // the matter is settled
}
}
if ($useAnd) // in AND mode we succeed if $test is false
{
$test = $test ? false : true;
}
return $test;
}
I think I found the correct implementation of the hasCredential method that overrides the original code found in the sfGuardSecurityUser Class. The code asks the underlying GuardUser model to reload all the permissions and groups from the database and adds theses credentials to the SecurityUser object before checking the credentials.
/**
* Returns whether or not the user has the given credential.
*
* EXTENDED to reload all permission so that changes take
* immediate effect and user does not have to log out
*
* #param string $credential The credential name
* #param boolean $useAnd Whether or not to use an AND condition
* #return boolean
*/
public function hasCredential($credential, $useAnd = true)
{
if (empty($credentials))
{
return true;
}
if (!$this->getGuardUser())
{
return false;
}
if ($this->getGuardUser()->getIsSuperAdmin())
{
return true;
}
if (!$this->isAuthenticated()) {
return false;
}
$gu = $this->getGuardUser();
$groups = $gu->getGroups();
$permissions = $gu->getPermissions();
$permission_names = array();
foreach($permissions as $permission) {
$permission_names[] = $permission->getName();
}
foreach($groups as $group) {
$group_permissions = $group->getPermissions();
foreach($group_permissions as $group_permission) {
$permission_names = array_merge($permission_names, array($group_permission->getName()));
}
}
$permission_names = array_unique($permission_names);
if (!is_array($credentials))
{
return in_array($credentials, $permission_names);
}
// now we assume that $credentials is an array
$test = false;
foreach ($credentials as $credential)
{
// recursively check the credential with a switched AND/OR mode
$test = $this->hasCredential($credential, $useAnd ? false : true);
if ($useAnd)
{
$test = $test ? false : true;
}
if ($test) // either passed one in OR mode or failed one in AND mode
{
break; // the matter is settled
}
}
if ($useAnd) // in AND mode we succeed if $test is false
{
$test = $test ? false : true;
}
return $test;
}
Im trying to test a pin number in the database compared to one entered by a user, whenever i run it i get a 'Trying to get property on non-object' error ... I cant seem to spot where im going wrong, could someone please help me out ... Its saying the error is on the $thepin = $pins->pin; line
The code i have in my controller is as follows:
function check_pin()
{
$pin = md5($this->input->post('oldpin'));
$email = $this->input->post('email');
$existingpin = $this->users->get_pin_by_email($email);
foreach($existingpin as $pins){
$thepin = $pins->pin;
}
if($pin != $thepin){
$this->form_validation->set_message('check_pin', 'The Old Pin Number does not match the existing one');
return FALSE;
} else {
return TRUE;
}
}
and the following is the code in my model
function get_pin_by_email($emailaddress)
{
$this->db->where('LOWER(email)=', strtolower($emailaddress));
$query = $this->db->get($this->table_name);
if ($query->num_rows() == 1) return $query->row();
return NULL;
}
The Controller code should be:-
function check_pin()
{
$pin = md5($this->input->post('oldpin'));
$email = $this->input->post('email');
$existingpin = $this->users->get_pin_by_email($email);
foreach($existingpin as $pins){
// Check for the NULL return
if ($pins != NULL && is_object($pins)) {
$thepin = $pins->pin;
}
}
if($pin != $thepin){
$this->form_validation->set_message('check_pin', 'The Old Pin Number does not match the existing one');
return FALSE;
} else {
return TRUE;
}
}
If you look closely in the model code, you will find that you are returning two data types - one is Object & another is NULL. So in your controller code, you should also check that accordingly.
Hope it helps.