Laravel: Sentry permissions not working properly - php

I have got the following in my sentry seeder:
<?php
use App\Models\User;
class SentrySeeder extends Seeder {
public function run()
{
DB::table('users')->delete();
DB::table('groups')->delete();
DB::table('users_groups')->delete();
Sentry::getUserProvider()->create(array(
'email' => 'admin#admin.com',
'password' => "admin#admin.com",
'first_name' => 'Kamran',
'last_name' => 'Ahmed',
'activated' => 1,
));
Sentry::getUserProvider()->create(array(
'email' => 'user#user.com',
'password' => "user#user.com",
'first_name' => 'New',
'last_name' => 'User',
'activated' => 1,
));
Sentry::getGroupProvider()->create(array(
'name' => 'Admin',
'permissions' => array(
'blog' => 1
),
));
Sentry::getGroupProvider()->create(array(
'name' => 'Blogger',
'permissions' => array(
'blog.add' => 1,
'blog.update' => 1,
'blog.trash' => 1,
'blog.remove' => 1
),
));
// Assign user permissions
$adminUser = Sentry::getUserProvider()->findByLogin('admin#admin.com');
$adminGroup = Sentry::getGroupProvider()->findByName('Admin');
$normalUser = Sentry::getUserProvider()->findByLogin('user#user.com');
$normalGroup = Sentry::getGroupProvider()->findByName('Blogger');
$adminUser->addGroup($adminGroup);
}
}
As you can see, I have defined two groups Admin and Blogger. Admin has all the permissions defined by blog, while blogger can only blog.add, blog.update, blog.trash and blog.remove. In my post view, I have got a button called Delete Permanently for which I have used the permission blog.remove. I want to show this button only if Sentry::getUser()->hasAnyAccess(array('blog', 'blog.remove')):
#if (Sentry::getUser()->hasAnyAccess(array('blog', 'blog.remove')))
<a class="btn btn-danger" href="{{URL::to('post/delete/' . $post->id)}}">Delete Permanently</a>
#endif
Now when I login using the admin#admin.com, it works fine that is remove button is shown as expected, because the admin has the access to blog permission. But, when I login using user#user.com, the button is not being shown. What is the reason that the button is not being shown although I have assigned the permission of blog.remove to user#user.com. Also I did a var_dump(..) and it's return false. Can any one please tell me what's wrong with my implementation? Why is the removal button not being shown for the user#user.com user?

In your seeder your not assigning the user to the blogger group.
$normalUser->addGroup($normalGroup);

Related

Trying to store login history inside laravels basic exampel for "manually authenticating users"

I used Laravel's guide to authenticating users manually at this link:
https://laravel.com/docs/7.x/authentication#remembering-users
and now I want to log every login's browser, version, platform, and ip.
My function on login:
public function store(Request $request)
{
$this->validate($request, [
'username' => 'required',
'password' => 'required'
]);
if (Auth::guard('admin')->attempt(['username' => $request->username, 'password' => $request->password, 'status' => 1], $request->remember)) {
$browserDetails = get_browser($request->header('User-Agent'), true);
LoginHistory::create([
'user_id' => auth()->guard('admin')->user()->id,
'user_type' => '2', // Admin = 2
'browser' => $browserDetails['browser'],
'browser_version' => $browserDetails['version'],
'platform' => $browserDetails['platform'],
'ip_address' => $request->ip()
]);
return redirect()->route('admin.dashboard');
}
return redirect()->back()->withErrors('Username or password incorrect.');
}
but I am getting:
ErrorException
Trying to get property 'id' of non-object
on this line:
'user_id' => auth()->guard('admin')->user()->id,
What should I do? The authentication works if I try to access login it will redirect me to dashboard so the session is created, but why can I not access the user id inside this function? It works on the edit admins page showing user id and all information.
use auth()->user()->id. when attempt () is executed and this is successful it performs the authentication

View Referencing it's self - Laravel 5.5

So I am new to laravel. I am trying to use a view but it keeps referencing its self with links.
See below what I mean
So I have a route "customers"
Route::get('customers/{cid?}', [
'uses' => 'customers#getCustomerView'
])->name('customers');
In this route as you can see I reference a controller getCustomerView. With an optional CID as someone might just want to see a list of customers. Then choose their customer. So here is the controller function
public function getCustomerView($cid = null){
$activeCustomer = array();
if(!empty($cid)){
// do middleware to get customer active detail
$activeCustomer = array(
'company' => 'Company '.$cid,
'fname' => 'Test',
'lname' => 'test'
);
}
return view('customers.view', [
'title' => 'Customer List',
'cid' => $cid,
'activeCustomer' => $activeCustomer,
'clist' => [
['company'=>'Company 1', 'fname' => 'Bob', 'lname' => 'Smith'],
['company'=>'Company 2', 'fname' => 'Julie', 'lname' => 'Reid'],
['company'=>'Company 3', 'fname' => 'Tony', 'lname' => 'Tima']
]
]);
}
When I load http://domain/customers - Everything works fine.
In my customers.view I have the following that loops and put's the array into a table. Later I will be using some middle ware or self function to get data from database. For now I am just using a harden array.
#foreach($clist as $key=>$customer)
<tr>
<td>{{$key+1}}</td>
<td>{{$customer['company']}}</td>
<td>{{$customer['fname']}}</td>
<td>{{$customer['lname']}}</td>
</tr>
#endforeach
The problem lies. Once I click on a customer. Page loads fine. http://domain/customers/1 - But if I go to click on another customer it does this
http://domain/customers/1/customers/2 - obviously this would cause an error. So why is it doing this?
How can I prevent it?
use this :
<td>{{$customer['company']}}</td>
it will generate a full url like http://domain/customers/1
but you can simply do that :
<td>{{$customer['company']}}</td>

Created admin's users doesn't work

I have a big problem with creating users from the admin panel;
Users are created correctly, but they do not work on the main page ..
Then I create an admin type user and I will log in with the main page and I get an error: 'those credentials do not match our records'
which is the error?
admin/userController
public function store(SaveUserRequest $request)
{
$data = [
'name' => $request->get('name'),
'last_name' => $request->get('last_name'),
'email' => $request->get('email'),
'user' => $request->get('user'),
'password' => $request->get('password'),
'type' => $request->get('type'),
'active' => $request->has('active') ? 1 : 0,
'address' => $request->get('address')
];
$user = User::create($data);
$message = $user ? 'Usuario agregado correctamente!' : 'El usuario NO pudo agregarse!';
return redirect()->route('admin.user.index')->with('message', $message);
}
It seems you do not hash your password, when saving the user (you can verify this by looking in the users table in your database and check if you can see the clear text in the passwords column for your users).
To correct this, just replace
'password' => $request->get('password'),
with
'password' => bcrypt($request->get('password')),
in your $data array.
Hope that helps!

Use the user.module API to create user in Drupal 7

I am trying to use user_save() in Drupal 7 to add new accounts to the system.
The function is defined as user_save($account, $edit = array(), $category = 'account').
According to the documentation, the variable $account is a user object. How do I put together a user object that the function can process?
Here is a comment that may help you out a little regarding the user object: User Object. Another way to see what the user object holds is to do:
<?php
global $user;
print_r($user);
?>
Here is a very basic example of creating a new user with user_save():
<?php
$edit = array(
'name' => 'New User',
'pass' => 'password',
'mail' => 'myemail#example.com',
'status' => 1,
'language' => 'en',
'init' => 'myemail#example.com',
'roles' => array(2 => 'authenticated user'),
);
user_save(NULL, $edit);
?>

Cakephp testing login

I want to test login function if it works propperly and only lets valid and active users in.
My user fixture contains:
array(
'password' => '*emptyPasswordHash*', // empty password
'username' => 'Lorem',
'balance' => 0,
'currency' => 'USD',
'id' => 1,
'user_group_id' => 3, //Customer
'active' => 1,
'hash' => 'LoremHash'
),
My test function looks like this:
function testLogin() {
//test valid login
$result = $this->testAction('/users/login', array(
'data' => array(
'User' => array(
'username' => 'Lorem',
'pass' => '',
'remember' => true
)),
'method' => 'post',
'return' => 'view'
));
debug($result);
}
The login form has 3 inputs: username, password and remember
I have set $this->Auth->autoRedirect = false; in the UsersController::beforeFilter and I am doing some cookie setting stuff
when I debug($this->data); in UsersController::login() it shows the exact same data when testing and when logging normaly. But while testing the login fails and I get $this->Auth->loginError message instead of a login.
How do I test login action propperly?
if you use cakes Auth component and dont hack it up you dont need to...
https://github.com/cakephp/cakephp/blob/master/cake/tests/cases/libs/controller/components/auth.test.php#L545
and if you really want to, look at how the pro's do it :)
Did you also set your custom function, like described in The CakePHP manual:
Normally, the AuthComponent will
attempt to verify that the login
credentials you've entered are
accurate by comparing them to what's
been stored in your user model.
However, there are times where you
might want to do some additional work
in determining proper credentials. By
setting this variable to one of
several different values, you can do
different things.

Categories