Get permission data from Database - codeigniter

I'm having problems to do a simple permission system on my Webapp. My DB has a table called "usuario" that has informations about the users of the system. One of these columns is called "privilegio" that has value '0' for administrators and 1 for regular users. An administrator has the power to Add and edit users on the system. Im trying to take this behavior querying my database with the cod of the logged user and getting its permission. If the user is not on the administrator group (privilegio=1) then the add/edit/delete buttons will be unset.
public function usuario() {
if($this->session->userdata('logged')){
$crud = new grocery_CRUD();
$crud->set_subject("Usuário");
$crud->set_theme('datatables');
$crud->set_table("usuario");
(...)
$crud->field_type('privilegio','dropdown',array('0'=>'Administrador','1'=>'Usuario'));
(...)
$this->db->select('privilegio');
$this->db->get('usuario');
$result = $this->db->where('cod_func',$this->session->userdata('cod_func'));
if(!$result){
$crud->unset_add();
$crud->unset_edit();
$crud->unset_delete();
}
(...)
The problem (and the question) is that this code only list the user that is logged on, not the others already registered on the system and stored on "usuario" table. I wonder that the list is been made by my query (what is not the behavior I would like) I hope you could undestand my doubt. Sorry for my bad english.
Thank you!

you're having trouble with the active record functions...
When you use the function
$this->db->get('usuario');
This translates to the query:
SELECT * FROM usuario
So try changing your code to something like this:
$this->db->select('privilegio');
$this->db->from('usuario');
$this->db->where('cod_func',$this->session->userdata('cod_func'));
$this->db->limit(1); //You're only expecting one result
$result = $this->db->get(); // Save the result to the variable result
//Edited for the comment, something like
$result = $result->first_row('array'); //Here I'm fetching only the first row into an array
$privilegio = $result['privilegio']; //Im saving the result from the query in the variable $privilegio
This translates to:
SELECT priviliegio FROM usuario WHERE cod_func = 'some_value' LIMIT 1;
Then you can do whatever you want with the $result variable, please refer to documentation to see what you can do...
Generating Query Results

Related

View data according to class and class group

I had an admin panel where 3 types of user are there Admin, Teacher and Student. Now I want that when student logged in he/she only see data uploaded by admin
According to his/her class and class group like class=10th and group=computer science. I have no idea how can i get this type of thing. I had used following code
$paper = Paper::where('paper_type','PaperSolution' && 'class',Auth::user()->class)->get();
this is not working properly as I am dumping data
dd($paper);
it is giving me null as answer.
you can use more granular wheres passed as array:
$query->where([
['column_1', '=', 'value_1'],
['column_2', '<>', 'value_2'],
[COLUMN, OPERATOR, VALUE],
...
])
Try this
$paper = Paper::where([['paper_type','PaperSolution'],['class', Auth::user()->class]])->get();
dd($paper);
OR
$paper = Paper::where([['paper_type','=','PaperSolution'],['class','=', Auth::user()->class]])->get();
dd($paper);
Reference for where query using array
ReferenceLink
Please refer to Laravel collection docs to correct syntax.
$paper = Paper::where('paper_type','PaperSolution')
->where('class', Auth::user()->class)
->get();
I did not exactly understand structure of your DB, but at first you need to have corresponding columns to then write any query. Your first option is uploaded by admin so in your uploads table (which is Paper model as I can see from your text) you should have something like uploader_role. Then you have student_class and student_group options. I want to get your attention in fact that this 2 options are users table columns NOT uploads (Paper). So you need to check some permissions of users, then get papers uploaded by admins. You can do that with middleware or just in your controller
$user = Auth::user();
if ($user->class == 10 && $user->group == 'computer_science') {
$papers = Paper::where('uploader_role', 'admin')
// you can add extra where options if that columns exist in papers table and you need to filter them also by class and group
->where( 'class_that_has_permissions', $user->class)
->where( 'group_that_has_permissions', $user->group)
->get();
return $papers;
}
abort(404);
Also be careful with columns that have name class that can return real user class name like App\User, try to use class_name or class_number.

Select Md5 combination of 2 rows from mysql

I have md5 some of the user information (lets say id and email for simplicity) and would like to use those information to find that user in my database.
The code in it's simplest form looks something like this
return $this->db->get_where('table', array('MD5(id,email)='=>$token ) ,1);
Not sure why but its returning false;
Update: trying to do this in sql
Just found out in when i try to do this in mysql I get an error
#1582 - Incorrect parameter count in the call to native function 'md5'
Is this mean you cant md5 multiple rows ? if so how do I do this!
Update: Again it returns false
$this->db->select('md5(id,email) as token');
$this->db->where('token', $token);
$this->db->limit(1);
$result = $this->db->get('table->customers');
Try concat in the where clause.
$this->db->where("md5(CONCAT(id,email)) = '".$token."'");

Laravel Eloquent and combing data to send to View

I'm trying to figure out a way to combine data from two tables into a single variable that I can then send to my view. I'm using Authority as my authentication bundle and so I have the following tables set up: users, roles, role_user. I want to get the following data into a single variable.
From the users table:
id, name, email
From the roles table:
name
The following returns all the user data in the users table:
$users = User::all();
But, I want to make a chain that can get the related data stored in the roles table? I want all users and all of each users roles together.
And while I can find examples that help get related data for a single record I haven't been able to find any reference to retrieving entire tables with related data.
Thanks.
$users = User::with('roles')->get()
Eager loading is what you are looking for, read the docs :)
Im not 100% sure what you are after, I think you should make relations with Eloquents methods. But if you are looking for a way to just merge the data returned by two models you could do the following:
$users = User::all();
$roles = Roles::all();
$array = array_merge($users->toArray(), $roles->toArray());
return Response::json($array);
You could make the model calls so that they return exactly what you are after and then merge them together. If you want one Model to return something specific just make a function for it.
You need to use something like that:
$user = User::get();
$roles = Roles::get();
$user .= (object) $roles; //because of that both them are object array and we have to combine them as object array...
than you can pass the data to View
return View:make('templatefile')//or Redirect to_route whatever
->with('user', $user);
But the best way is belongs_to in your case. Please read the documentation:
http://laravel.com/docs/database/eloquent#relationships

Preventing Doctrine's query cache in Symfony

In my Symfony/Doctrine app, I have a query that orders by RANDOM(). I call this same method several times, but it looks like the query's result is being cached.
Here's my relevant code:
$query = $table->createQuery('p')
->select('p.*, RANDOM() as rnd')
->orderBy('rnd')
->limit(1)
->useQueryCache(null)
->useResultCache(null);
$result = $query->fetchOne();
Unfortunately, the same record is returned every time, regardless of me passing null to both useQueryCache and useResultCache. I tried using false instead of null, but that didn't work either. Lastly, I also tried calling both setResultCacheLifeSpan(0) and setResultCacheLifeSpan(-1), but neither call made a difference.
Any insight on how to prevent caching since I want a different random row to be selected each time I call this method?
Edit: I also tried calling clearResultCache(), but that just ended up causing an error stating: "Result Cache driver not initialized".
Edit 2: As requested, here's the SQL generated by calling $query->getSqlQuery():
SELECT c.id AS c__id, c.name AS c__name, c.image_url AS c__image_url,
c.level AS c__level, c.created_at AS c__created_at, c.updated_at
AS c__updated_at, RANDOM() AS c__0 FROM cards c ORDER BY c__0 LIMIT 1
It turns out I'm a moron. I tried to simplify my query for this question, and in doing so, I didn't capture the true cause. I had a where() and andWhere() call, and the combination of conditions resulted in only one possible record being matched. Thanks for taking the time to respond, everyone, sorry to have wasted your time!
Doctrine also caches entities you created in the same request/script run.
For instance:
$order = new Order();
$order->save();
sleep(10); // Edit this record in de DB in another procces.
$q = new Doctrine_Query();
$result = $q->select()
->from('Order o')
->where('o.id = '.$order->id);
$order = $result->getFirst();
print_r($order->toArray());
The print_r will not contain the changes you made during the sleep.
The following code will remove that kind of memory cache:
$manager = Doctrine_Manager::getInstance();
$connection = $manager->getCurrentConnection();
$tables = $connection->getTables();
foreach ( $tables as $table ) {
$table->clear();
}
PS: Added this answer because I found this topic trying to resolve above issue.

Doctrine toarray does not convert relations

I followed doctrine documnetation to get started. Here is the documentation.
My code is
$User = Doctrine_Core::getTable("User")->find(1);
when I access relations by $User->Phonenumbers, it works. When I convert User object to array by using toArray() method, it does not convert relations to array. It simply display $User data.
Am I missing something?
By using the find method you've only retrieved the User data which is why the return of toArray is limited to that data. You need to specify the additional data to load, and the best place to do this is usually in the original query. From the example you linked to, add the select portion:
$q = Doctrine_Query::create()
->select('u.*, e.*, p.*') // Example only, select what you need, not *
->from('User u')
->leftJoin('u.Email e')
->leftJoin('u.Phonenumbers p')
->where('u.id = ?', 1);
Then when toArray'ing the results from that, you should see the associated email and phonenumber data as well.
I also noticed an anomaly with this where if you call the relationship first then call the ToArray, the relationship somehow gets included. what i mean is that, taking your own eg,
$User = Doctrine_Core::getTable("User")->find(1);
$num= $User->Phonenumbers->office; // assumed a field 'office' in your phone num table
$userArray = $user->toArray(true);
In the above case, $userArray somehow contains the whole relationship. if we remove the $num assignment it doesn't.
am guessing this is due to doctrine only fetching the one record first, and it's only when you try to access foreign key values that it fetches the other related tables

Resources