I write a method, that which checks whether the user is an administrator in file UserController.php:
public function create(){
$chackIsAdmin = Auth::user()->permissions;
if ($chackIsAdmin === 1) {
return view('users.adduser');
} else {
return redirect('warehouse');
}
In table "users" I have column "permissions". Each user is assigned a number 1 or 0. 1 - is admin, 0 is NOT an admin.
I wrote also instruction if, which displays option "Add user" only the user administrator:
#if (Auth::user()->permissions === 1)
<li>Add new user</li>
#endif
It all works correctly, but I wonder whether in Laravel I can do it in a different way ??
Whether my way is safe?
I think the better way is to write the function on the User model.
class User extends Model
{
public function isAdmin()
{
return $this->attributes['permissions'] == 1;
}
}
Then it's very easy to use...
return Auth::user()->isAdmin() ? view('users.adduser') : redirect('warehouse');
Related
The debugbar reads
368 statements were executed, 360 of which were duplicated, 8 unique
It turns out that with every check on my user, via auth()->user()->isCustomer() and other similar functions, it's actually looking up the user every time.
i.e.
public function hasRole($role)
{
// If the user has the 'admin' role, always authorize
if ($this->roles()->where('name', 'customer')->first() !== null) {
return true;
}
return null !== $this->roles()->where('name', $role)->first();
}
// Check for admin
public function isCustomer()
{
return $this->hasRole('customer');
}
How do I safely cache this information on the user object so the database isn't being hounded every time?
I also use the 404labfr/laravel-impersonate function on this project (so when you are an Admin, you can impersonate other users).
I think you can decrease queries by half using:
public function hasRole($role)
{
return null !== $this->roles()->whereIn('name', ['customer', $role])->first();
}
I am front of reflexion about my php developments. I'm trying to optimize my code.
I have often condition like this :
if($userConnected->getType() == User::BUYER_ACCOUNT_TYPE || $userConnected->getType() == User::ADMIN_ACCOUNT_TYPE){//Mycode}
My question is : Is it possible to have something like this :
if($userConnected->getType() == User::BUYER_ACCOUNT_TYPE || User::ADMIN_ACCOUNT_TYPE)
Actually the best way I found to do this is :
if(in_array($userConnected->getType(), array(User::BUYER_ACCOUNT_TYPE, User::ADMIN_ACCOUNT_TYPE)))
And I want to know if there is a better way ?
Thank you in advance
Thomas
You can add some public methods to your User class to check if the user is a buyer or an admin:
public function isBuyer()
{
return $this->type === self::BUYER_ACCOUNT_TYPE;
}
public function isAdmin()
{
return $this->type === self::ADMIN_ACCOUNT_TYPE;
}
Having these methods you can simply check:
if ($userConnected->isBuyer() || $userConnected->isAdmin())
You can go further and do a single method if the condition above is used very often:
public function isAllowed() // just an example of a method name
{
return $this->isBuyer() || $this->isAdmin();
}
I'm trying to create a check for the field member is equal to 1.
I've created a helper class and added it in my app.blade.php
Here is my code.
Helper Class:
function checkMember() {
$stmt = DB::table('users')->where('member', '=', 1);
if ($stmt) {
return True;
}
return False;
}
app.blade.php
#if (checkMember() == True)
<li><i class="fa fa-btn fa-terminal"></i>Member Panel</li>
#endif
The error is that it displays the <li> even when member == 0 in the DB
Your checkMember() method is incomplete - it doesn't launch the query, it only builds it, so it will always be true. Try this:
function checkMember() {
$stmt = DB::table('users')->where('member', 1)->first();
return $stmt ? true : false;
}
I'm also concerned about your query a little bit - this will check if there is any user with 'member' field set to true. So, if you have at least one member - it will return true for all your web users.
Don't you want to do this check against current, logged in user?
Im using laravel 4.0 im tyring to display a layout only if a variable ==0 (just in case a user tries to navigate to the url instead of clicking through) (i know I can redirect instead of extending but this is undesirable for now)
I am trying to get the layout to only extend when the user navigates to the page manually, noajax is set to true if their is no ajax request being sent when it goes to the function, so if the user where to navigate to the url manually it will still display the page but extend the layout.
#if ($noajax==1)
#extends('layouts.master')
#endif
#section('content')
//controller
public function test($id,$model)
{
if (Request::ajax())
{
//$foreign_key and $model must be <> null
if ($id == null || $model == null) {
$this->render('../Errors/missing_arg', 'error');
return;
}
if($model=="ArtObj")
{
$partable = "art_objects";
$path='img/art-objects/';
}
$parid=$id;
$noajax=0;
$mediaimgs = Media::where('parent_id' , $id )->where('parent_table', $partable)->paginate(15);
$response = Response::Json($mediaimgs);
return View::make('/Admin/manageimage/manage_image',compact('parid','mediaimgs','model','path','noajax'));
}
else{
if($model=="ArtObj")
{
$partable = "art_objects";
$path='img/art-objects/';
}
$parid=$id;
$mediaimgs = Media::where('parent_id' , $id )->where('parent_table', $partable)->paginate(15);
$response = Response::Json($mediaimgs);
$noajax = 1;
return View::make('/Admin/manageimage/manage_image',compact('parid','mediaimgs','model','path','noajax'));
}
}
In this case you should use 2 views in controller.
In controller you should use:
if ($noajax) {
return View::make('noajax');
}
else {
return View::make('ajax');
}
In noajax view you can extend from any other view and if noajax and ajax have common code, you should put it in separate file and use #include in those both views to include common part of code.
How can I create a PHP function or class that checks if a user who is a half-admin (set from a MySQL database) has some rights such as creating a new page, editing, or deleting?
I need a function that checks the user permissions and then display the code like this:
if ($he_can_create_page){
//continue the script.....
}else{
//don`t continue
}
In present I use sessions like this:
If($_SESSION['user_type']=='Admin'||$_SESSION['user_type']=='premium'){
//do stuff
}else if()......... {
// ..............
}
but they become too many if statements, and I want a cleaner code :)
interface User {
public function canCreatePage();
public function canDeletePage();
public function canEditPage();
....
}
class Admin implements User {
public function canCreatePage(){
return true;
}
public function canEditPage(){
return true;
}
...
}
class Editor implements User {
public function canCreatePage() {
return false;
}
public function canEditPage(){
return true;
}
...
}
then from what you get in the data base
if ($row['user_type'] == 'Admin') {
$user = new Admin();
} else if $row['user_type'] == 'Editor') {
$user = new Editor();
} ....
in all your pages :
if ($user->canCreatePage()){
//continue the script.....
}else{
//don`t continue
}
If you want to store your user in session the first time you get it from the dataBase
$_SESSION['user'] = serialize($user);
in the next page
$user = unserialize($_SESSION['user']);
Or you can also just store the id of the user in session and get it back from de
DB on every page.
Create a generic function an put it in a file which is common for all files something like this
function pageCreatePermission() {
if($_SESSION['user_type']=='Admin'||$_SESSION['user_type']=='premium'){
return true;
} else {
return false;
}
then use this function something like this in your file
if (pageCreatePermission()) {
//do your stuff
} else {
//show error you want
}
Add columns in your users table like:
| canEdit | canDelete | canCreate |
with flags 1/0. 1 for true, 0 for false.
select the fields and make checks i.e.:
if($row['canEdit'] = 1) {
//continue (return true)
}
else {
//stop (return false)
}
You can make it a function with params, so you will give the param to the function i.e. $canDelete (which is your $row data) and it checks only that permission
function userPermissions($type)
if($type=1) {
return true;
}
else {
return false;
}
$canCreate = $row['canCreate'];
if(userPermissions($canCreate)) { ...
The answer is to use an access control system. There are many different types. The most used (in web development) are ACL (Access control list) and RBAC (Role based access control). The rules can be filled from database or hardcoded.
To give you an idea of how they work look at the examples from Zend Framework: ACL and RBAC.
In Zend Framework the ACL is not very different from a RBAC because it also has roles. But normally an ACL is user based and not role based. If you like you can integrate the ACL/RBAC from Zend or other frameworks into your own project.
Read about how yii do it: yii RBAC