authorisation based on values not on verb - laravel

I'm implementing an authorisation process based on values not on verb.
Example:
all users/groups are allowed to update a db field
admin can set status to all possible values (confirmed | pending | cancelled)
supplier can set to 'confirmed'
All examples I find go around a user/group being able or not to insert,update or delete something.
Is there something out there to deal with situations like this out of the box, or this has be hard coded?

Basically what you need is something hard to maintain in any application: granular permissions.
You can get this to work easily using Cartalyst's Sentry. Here's how I do it:
All my routes are hierarchically organized and named as such:
<?php
Route::get('login', array('as'=>'logon.login', 'uses'=>'LogonController#login'));
Route::get('logged/out', array('as'=>'logon.loggedOut', 'uses'=>'LogonController#loggedOut'));
Route::group(array('before' => 'auth'), function()
{
Route::get('logout', array('as'=>'logon.logout', 'uses'=>'LogonController#logout'));
Route::group(array('before' => 'permissions'), function()
{
Route::get('store/checkout/shipping/address', array('as'=>'store.checkout.shipping.address', 'uses'=>'StoreController#shippingAddress'));
Route::get('store/checkout/payment/confirmed', array('as'=>'store.checkout.payment.confirmed', 'uses'=>'StoreController#confirmed'));
Route::get('profile', array('as'=>'profile.show', 'uses'=>'ProfileController#show'));
});
});
Those under the filter 'permissions' are subject to check if user has rights to use them:
Route::filter('permissions', function()
{
$name = Route::current()->getName();
$name = 'system' . ( ! empty($name) ? '.' : '') . $name;
if (!Permission::has($name)) {
App::abort(401, 'You are not authorized to access route '.$name);
}
});
Basically here I get the current route name, add 'system.' to it and check if the user has this particular permission.
Here's how I create my groups and populate permissions:
<?php
public function seedPermissions()
{
DB::table('groups')->truncate();
$id = 1;
Sentry::getGroupProvider()->create(array(
'id' => $id++,
'name' => 'Super Administrators',
'permissions' => array(
'system' => 1,
),
));
Sentry::getGroupProvider()->create(array(
'id' => $id++,
'name' => 'Administrators',
'permissions' => array(
'system.users' => 1,
'system.products' => 1,
'system.store' => 1,
'system.profile' => 1,
),
));
Sentry::getGroupProvider()->create(array(
'id' => $id++,
'name' => 'Managers',
'permissions' => array(
'system.products' => 1,
'system.store' => 1,
'system.profile' => 1,
),
));
Sentry::getGroupProvider()->create(array(
'id' => $id++,
'name' => 'Users',
'permissions' => array(
'system.store.checkout' => 1,
'system.profile' => 1,
),
));
}
So if a user is trying to add some shipping address, the route 'store.checkout.payment.confirmed', as every user has access to 'system.store.checkout', everything inside that route will available to him.
And this is how I check for permissions:
public static function has($permission)
{
$all = [];
$parts = explode('.',$permission);
$permission = '';
foreach($parts as $part) {
$permission .= (!empty($permission) ? '.' : '') . $part;
$all[] = $permission;
}
return Sentry::check() and Sentry::getUser()->hasAnyAccess($all);
}
It basically builds a list of routes:
system
system.store
system.store.checkout
system.store.checkout.payment
system.store.checkout.payment.confirmed
And if Sentry finds one of those in the users granular permissions it will return true.
Now I just have to add users to groups:
Sentry::findUserById(1)->addGroup( Sentry::getGroupProvider()->findByName('Users') );
And if I need to go granular on a particular user/permission I just need to:
$user = Sentry::findUserById(1);
$user->permissions['store.checkout.payment'] = false;
$user->save();
And the user will never be able to pay for anything in the store again. :)

Related

Updating a document in laravel firestore

Hi I've been trying out things in updating aa document in firestore from laravel 9. But it doesn't seem to work at all.
What I have tried so far:
$product = app('firebase.firestore')
->database()
->collection('Products')
->document('15da5077cf8940f797db')
->update([
'path' => 'status',
'value' => 'archive'
]);
and
$status = "archive";
$currentData = json_decode(json_encode([
'status' => $status,
]));
$newData = [
'status' => $status,
];
$postData = app('firebase.firestore')
->database()
->collection('Products')
->document('15da5077cf8940f797db');
$postData->update([[
'path' => 'Products',
'value' => FieldValue::arrayRemove([$currentData])
]]);
$postData->set([
'Products' => FieldValue::arrayUnion($newData)
], ['merge' => true]);
and, javascript
const app = initizalizeApp(firebaseConfig);
const db = getFirestore(app);
btnArchive.addEventListener('click', (e) =>{
archiveDoc(doc(db, "Products", "15da5077cf8940f797db"), {
status: archive,
})
alert('Product archived!')
});
I want to update the status of a product from active to archive. But this doesn't work at all. Also is there another way to edit a document without specifying it?
this is how my collection looks like, each document has its own product details:

How make a register form codeigniter with different database table

I tried to make a register form on a multiuser website with a different database table.
Eg when user1 registers, the data will be entered in table "user1",
when user2 registers, entered in table "user2".
I can only enter user1 and user2 into the same table.
This is my code using role_id
$data = [
'name' => htmlspecialchars($this->input->post('nama', true)),
'username' => htmlspecialchars($this->input->post('username', true)),
'photo' => 'default.jpg',
'password' => password_hash($this->input->post('password1'), PASSWORD_DEFAULT),
'role_id' => 2,
'is_active' => 1,
'is_date' => time()
];
You can do this by applying condition on role_id but this is only possible if there are only a number of users. If there are many users and you want to make a separate table for each one of them, try Database Forge Class(Bad practice)
I've written a possible solution for your question, comments are mentioned wherever necessary. See if it helps you.
Controller
$data = [
'name' => htmlspecialchars($this->input->post('nama', true)),
'username' => htmlspecialchars($this->input->post('username', true)),
'photo' => 'default.jpg',
'password' => password_hash($this->input->post('password1'), PASSWORD_DEFAULT),
'role_id' => 2,
'is_active' => 1,
'is_date' => time()
];
$this->xyz_model->xyz_function($data); // load xyz_model and call xyz_function with $data parameters
Xyz_model
function xyz_function($data){
$table = 'user1'; // default value
if($data['role_id'] != 1){ // other value is 2 -- assuming only 2 users are there(if not user if else or switch)
$table = 'user2';
}
$this->db->insert($table, $data);
return $this->db->insert_id();
}

Laravel 4 and Sentry 2 ACL structure and access control levels

I am developing a site using laravel 4, and trying to implement my ACL using Sentry 2. I need help on how to structure the following:
I have the following permissions for role HR:
Staffs|View staff details
Staffs|Register new staff
Staffs|Edit staff details
Staffs|Delete staff details
Corresponding to the following routes:
//get route to staffs landing page
Route::get('staffs/view-staffs', 'UsersController#getManageStaffs');
//post routes
Route::post('staffs/add-staff', 'UsersController#postAddStaff');
Route::post('staffs/update-staff', 'UsersController#postUpdateStaff');
Route::post('staffs/delete-staff', 'UsersController#postDeleteStaff');
I need access control for the following:
link on my menu for view-staffs: if all staff permission are disabled, disable link. This is how i am doing it:
if($user->hasAnyAccess(array('Staffs|View staff details', 'Staffs|Register new staff', 'Staffs|Edit staff details', 'Staffs|Delete staff details')))
{
//display menu link
}
my routes: if all staff permissions are disabled, disable all routes that fall under "staffs/"
//For this, i have no idea how to restrict routes based on my permissions
//But i don't want to do it like i did in (1) within my controllers
disable action buttons that corresbond to a disabled permission
//same as no (1)
You can do something like the following:
In app/filters.php, create a filter as follows.
Route::filter('permissions', function()
{
$name = Route::current()->getName();
$name = 'system' . ( ! empty($name) ? '.' : '') . $name;
if (!UserHelper::hasPermission($name)) {
App::abort(401, 'You are not authorized to access route '.$name);
}
});
You can apply the filter by putting a before filter on your route, e.g.
Route::group(array('before' => 'permissions'), function()
{
// routes
}
With this system, you could create permission groups like these:
Sentry::getGroupProvider()->create(array(
'id' => 1,
'name' => 'Super Administrators',
'permissions' => array(
'system' => 1,
),
));
Sentry::getGroupProvider()->create(array(
'id' => 2,
'name' => 'Administrators',
'permissions' => array(
'system.users' => 1,
'system.products' => 1,
'system.store' => 1,
'system.profile' => 1,
),
));
Sentry::getGroupProvider()->create(array(
'id' => $id++,
'name' => 'Managers',
'permissions' => array(
'system.products' => 1,
'system.store' => 1,
'system.profile' => 1,
),
));
So if a user has the system.products permission, he'd be able to use every products route.
Now, for the part where you wish to show links to certain groups, you can do that with a helper like this:
public static function has($permission)
{
$all = [];
$parts = explode('.',$permission);
$permission = '';
foreach($parts as $part) {
$permission .= (!empty($permission) ? '.' : '') . $part;
$all[] = $permission;
}
return Sentry::check() and Sentry::getUser()->hasAnyAccess($all);
}
You'd simply pass the route name (e.g. system.products) to the function and it'll return whether the user has access to it.
Source: https://laracasts.com/forum/conversation/post/2819
There is a cool package for sentry ACL that implements a fully featured admin panel https://github.com/intrip/laravel-authentication-acl

CodeIgniter 2 and Ion Auth - edit own user account

I am using the latest Ion Auth files along with the latest version of CodeIgniter 2.
There is a function called edit_user within the auth.php Controller file. This function is restricted to use only by members within the "Admin" group, and any Admin member can edit any other member using the function via this URL...
/auth/edit_user/id
The problem is that I don't see any Controller function or View that allows a regular (non-Admin) user to edit their own account details.
Would this be a new Controller function I'd need to write (modify edit_user function?) or is this something that Ion Auth should already do? If so, how?
Here is the stock Ion Auth edit_user function contained within the auth.php Controller...
function edit_user($id)
{
$this->data['title'] = "Edit User";
if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin())
{
redirect('auth', 'refresh');
}
$user = $this->ion_auth->user($id)->row();
//process the phone number
if (isset($user->phone) && !empty($user->phone))
{
$user->phone = explode('-', $user->phone);
}
//validate form input
$this->form_validation->set_rules('first_name', 'First Name', 'required|xss_clean');
$this->form_validation->set_rules('last_name', 'Last Name', 'required|xss_clean');
$this->form_validation->set_rules('phone1', 'First Part of Phone', 'required|xss_clean|min_length[3]|max_length[3]');
$this->form_validation->set_rules('phone2', 'Second Part of Phone', 'required|xss_clean|min_length[3]|max_length[3]');
$this->form_validation->set_rules('phone3', 'Third Part of Phone', 'required|xss_clean|min_length[4]|max_length[4]');
$this->form_validation->set_rules('company', 'Company Name', 'required|xss_clean');
if (isset($_POST) && !empty($_POST))
{
// do we have a valid request?
if ($this->_valid_csrf_nonce() === FALSE || $id != $this->input->post('id'))
{
show_error('This form post did not pass our security checks.');
}
$data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'company' => $this->input->post('company'),
'phone' => $this->input->post('phone1') . '-' . $this->input->post('phone2') . '-' . $this->input->post('phone3'),
);
//update the password if it was posted
if ($this->input->post('password'))
{
$this->form_validation->set_rules('password', 'Password', 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[password_confirm]');
$this->form_validation->set_rules('password_confirm', 'Password Confirmation', 'required');
$data['password'] = $this->input->post('password');
}
if ($this->form_validation->run() === TRUE)
{
$this->ion_auth->update($user->id, $data);
//check to see if we are creating the user
//redirect them back to the admin page
$this->session->set_flashdata('message', "User Saved");
redirect("auth", 'refresh');
}
}
//display the edit user form
$this->data['csrf'] = $this->_get_csrf_nonce();
//set the flash data error message if there is one
$this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
//pass the user to the view
$this->data['user'] = $user;
$this->data['first_name'] = array(
'name' => 'first_name',
'id' => 'first_name',
'type' => 'text',
'value' => $this->form_validation->set_value('first_name', $user->first_name),
);
$this->data['last_name'] = array(
'name' => 'last_name',
'id' => 'last_name',
'type' => 'text',
'value' => $this->form_validation->set_value('last_name', $user->last_name),
);
$this->data['company'] = array(
'name' => 'company',
'id' => 'company',
'type' => 'text',
'value' => $this->form_validation->set_value('company', $user->company),
);
$this->data['phone1'] = array(
'name' => 'phone1',
'id' => 'phone1',
'type' => 'text',
'value' => $this->form_validation->set_value('phone1', $user->phone[0]),
);
$this->data['phone2'] = array(
'name' => 'phone2',
'id' => 'phone2',
'type' => 'text',
'value' => $this->form_validation->set_value('phone2', $user->phone[1]),
);
$this->data['phone3'] = array(
'name' => 'phone3',
'id' => 'phone3',
'type' => 'text',
'value' => $this->form_validation->set_value('phone3', $user->phone[2]),
);
$this->data['password'] = array(
'name' => 'password',
'id' => 'password',
'type' => 'password'
);
$this->data['password_confirm'] = array(
'name' => 'password_confirm',
'id' => 'password_confirm',
'type' => 'password'
);
$this->load->view('auth/edit_user', $this->data);
}
Unless I'm missing something, I ended up modifying the edit_user function within the auth.php Controller as follows.
I changed this line which checks to see that the user is "not logged in" OR "not an admin" before dumping them out...
if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin())
{
redirect('auth', 'refresh');
}
...into this, which check to see that the user is "not logged in" OR ("not an admin" AND "not the user") before dumping them out...
if (!$this->ion_auth->logged_in() || (!$this->ion_auth->is_admin() && !($this->ion_auth->user()->row()->id == $id)))
This seems to be working...
Admin can edit all accounts
User can only edit his own account
and somebody not logged in, can't edit any account.
Edit: However, the user also has access to the "groups" setting and could simply put themself into the "admin" group. Not good.
Ion Auth's developer refers to the files he provides as working "examples". Therefore, it's up to the end-developer to edit Ion Auth to suit the needs of the project.
To prevent the user from being able to make himself an "admin" requires a simple change to the edit_user.php view file.
Verifies the user is already an "admin" before creating the checkboxes...
<?php if ($this->ion_auth->is_admin()): ?>
// code that generates Groups checkboxes
<?php endif ?>
Then you'll also need to thoroughly test and adjust as needed. For example, after editing a user profile, you're redirected to the auth view. Since the user doesn't have permission to see the auth view, there is a "must be an admin" error. In the controller file, you'll have to add the appropriate logic to properly redirect the user when they're not an "admin".
No Ion Auth doesn't do this as is - it's pretty light weight. But it's not hard to do and your on the right track, just grab that edit_user method and take out the admin checks and make it so the user can only edit their own account, just alter it so that it only updates user details for the currently logged in user.
Check the ion auth docs, have a crack at it and come back with some code if you have any problems.

cookie not being set straight away

I have a basket cookie, before adding a product to the basket the function checks to see if a cookie exists or if a new cookie is required. This works fine when adding one item at a time but there are occasions when more than one item is added at the same time. Again if an old basket cookie exists this works fine. The problem is when no basket cookie exists and the function had to create one.
The first time it goes through, the cookie is created a database record is added ect.
The second time round the function we check for the cookie no cookie is found and another cookie is created etc.
$this->db->select('basket_id');
$this->db->from($this->basket_table);
$this->db->where('basket_id', get_cookie('basket_id'));
$check_basket = $this->db->get();
if($check_basket->num_rows > 0){
$basket_exists = 1;
}else{
$basket_exists = 0;
}
if($basket_exists == 0){
delete_cookie('basket_id');
$basket = array(
'lang_id' => $lang_id,
'currency_id' => $currency_id,
'customer_id' => $customer_id,
);
$this->db->insert($this->basket_table, $basket);
$basket_id = $this->db->insert_id();;
$cookie = array(
'name' => 'basket_id',
'value' => $basket_id,
'expire' => 60*60*24*30,
'domain' => 'REMOVED'
'path' => '/',
'prefix' => '',
);
set_cookie($cookie);
}else{
$basket_id = get_cookie('basket_id');
}
In order to set the cookie, you need to send it to the browser, - but this never happens if your function loops multiple times before you create a view.
So set the cookie prior to them using the basket, OR only check if the cookie needs to be set once, like this:
$this->db->select('basket_id');
$this->db->from($this->basket_table);
$this->db->where('basket_id', get_cookie('basket_id'));
$check_basket = $this->db->get();
if($check_basket->num_rows > 0) {
$basket = array(
'lang_id' => $lang_id,
'currency_id' => $currency_id,
'customer_id' => $customer_id,
);
$this->db->insert($this->basket_table, $basket);
$basket_id = $this->db->insert_id();
$cookie = array(
'name' => 'basket_id',
'value' => $basket_id,
'expire' => 60*60*24*30,
'domain' => 'REMOVED'
'path' => '/',
'prefix' => '',
);
set_cookie($cookie);
}
// Now run your basket logic here - knowing the cookie is setup
}

Resources