Using Laravel with Auth and Spatie\laravel-permission packages. I have a User with the Admin Role. Several other Permissions are also attached to this Role.
I noticed 'can:permission_name' and 'permission:permission_name' middlewares weren't functioning properly, so I started debugging. I realized that $user->getAllPermissions() only returns the permission with the highest id. In addition, when running $user->hasPermissionTo() on other permissions than the one previously mentioned, it returns false.
I would really appreciate the help. Also, I have tried to clear the cache as well.
Seeder function:
public function run() {
$permissions[0] = Permission::create(['guard_name' => 'web', 'name' => 'Access Admin Panel']);
$permissions[1] = Permission::create(['guard_name' => 'web', 'name' => 'Access Music']);
$permissions[2] = Permission::create(['guard_name' => 'web', 'name' => 'Edit Database']);
$permissions[3] = Permission::create(['guard_name' => 'web', 'name' => 'Login']);
$role[0] = Role::create(['guard_name' => 'web', 'name' => 'Administrator']);
$role[0]->permissions()->attach($permissions[0]);
$role[0]->permissions()->attach($permissions[1]);
$role[0]->permissions()->attach($permissions[2]);
$role[0]->permissions()->attach($permissions[3]);
$role[1] = Role::create(['guard_name' => 'web', 'name' => 'VIP']);
$role[1]->permissions()->attach($permissions[1]);
$role[1]->permissions()->attach($permissions[2]);
$role[1]->permissions()->attach($permissions[3]);
$role[2] = Role::create(['guard_name' => 'web', 'name' => 'Trusted']);
$role[2]->permissions()->attach($permissions[2]);
$role[2]->permissions()->attach($permissions[3]);
$role[3] = Role::create(['guard_name' => 'web', 'name' => 'User']);
$role[3]->permissions()->attach($permissions[3]);
$role[4] = Role::create(['guard_name' => 'web', 'name' => 'Disabled']);
$admin = User::create(['name' => 'Gandalfsdottir', 'email' => 'my#email.com', 'password' => Hash::make('demo')]);
$admin->markEmailAsVerified();
$admin->assignRole('Administrator');
$demo = User::create(['name' => 'Demo', 'email' => 'my#secondemail.fr', 'password' => Hash::make('demo')]);
$demo->markEmailAsVerified();
$demo->assignRole('User');
}
Related
in my app the user can update the info of stripe connected account, however I ONLY want to actullay update the value of the fields that appear in the request payload, I could do this with a simple if check but the way I update the stripe array method makes this issue more complicated .
Is there any syntax sugar or trick to make this easier.
How my update method looks;
public function editConnectedAccount(Request $request)
{
$account = Account::retrieve($request->connectedAccountId);
Account::update(
$request->connectedAccountId,
[
'type' => 'custom',
'country' => 'ES',
'email' => $request->userEmail,
'business_type' => 'individual',
'tos_acceptance' => [ 'date' => Carbon::now()->timestamp, 'ip' => '83.46.154.71' ],
'individual' =>
[
'dob' => [ 'day' => $request->userDOBday, 'month' => $request->userDOBmonth, 'year' => $request->userDOByear ],
'first_name' => $request->userName,
'email' => $request->userEmail,
'phone' => $request->userPhone,
'last_name' => $request->userSurname,
//'ssn_last_4' => 7871,
'address' => [ 'city' => $request->userBusinessCity, 'line1' => $request->userBusinessAddress, 'postal_code' => $request->userBusinessZipCode, 'state' => $request->userBusinessCity ]
],
'business_profile' =>
[
'mcc' => 5812, //got it
'description' => '',
//'url' => 'https://www.youtube.com/?hl=es&gl=ES', //got it
],
'capabilities' => [
'card_payments' => ['requested' => true],
'transfers' => ['requested' => true],
],
]
);
return response()->json([
'account' => $account,
], 200);
Consider using a Form Request where you preform validation. This will neaten up your controller for a start and also make validation (never trust user input!) reusable.
Assuming validation is successful, calling $request->validated() from inside your controller method will return only the fields present and validated. You can then use either fill($request->validated()) or update($request->validated()).
I would like to change the password of a user in AD since there are no attribute for password in AD.
Currently running laravel framework with Adldap2-laravel package in order to manage ADLDAP operations.
Here's my ldap_auth.php
<?php
return [
'connection' => env('LDAP_CONNECTION', 'default'),
'provider' => Adldap\Laravel\Auth\DatabaseUserProvider::class,
'model' => App\User::class,
'rules' => [
Adldap\Laravel\Validation\Rules\DenyTrashed::class,
],
'scopes' => [
Adldap\Laravel\Scopes\UidScope::class
],
'identifiers' => [
'ldap' => [
'locate_users_by' => 'uid',
'bind_users_by' => 'dn',
],
'database' => [
'guid_column' => 'objectguid',
'username_column' => 'username',
],
'windows' => [
'locate_users_by' => 'samaccountname',
'server_key' => 'AUTH_USER',
],
],
'passwords' => [
'sync' => env('LDAP_PASSWORD_SYNC', false),
'column' => 'password',
],
'login_fallback' => env('LDAP_LOGIN_FALLBACK', false),
'sync_attributes' => [
'username' => 'uid',
'password' => 'userPassword',
'name' => 'cn',
'role' => 'l',
'category' => 'businessCategory',
'telephone_number' => 'telephoneNumber',
'email' => 'mail'
],
'logging' => [
'enabled' => env('LDAP_LOGGING', true),
'events' => [
\Adldap\Laravel\Events\Importing::class => \Adldap\Laravel\Listeners\LogImport::class,
\Adldap\Laravel\Events\Synchronized::class => \Adldap\Laravel\Listeners\LogSynchronized::class,
\Adldap\Laravel\Events\Synchronizing::class => \Adldap\Laravel\Listeners\LogSynchronizing::class,
\Adldap\Laravel\Events\Authenticated::class => \Adldap\Laravel\Listeners\LogAuthenticated::class,
\Adldap\Laravel\Events\Authenticating::class => \Adldap\Laravel\Listeners\LogAuthentication::class,
\Adldap\Laravel\Events\AuthenticationFailed::class => \Adldap\Laravel\Listeners\LogAuthenticationFailure::class,
\Adldap\Laravel\Events\AuthenticationRejected::class => \Adldap\Laravel\Listeners\LogAuthenticationRejection::class,
\Adldap\Laravel\Events\AuthenticationSuccessful::class => \Adldap\Laravel\Listeners\LogAuthenticationSuccess::class,
\Adldap\Laravel\Events\DiscoveredWithCredentials::class => \Adldap\Laravel\Listeners\LogDiscovery::class,
\Adldap\Laravel\Events\AuthenticatedWithWindows::class => \Adldap\Laravel\Listeners\LogWindowsAuth::class,
\Adldap\Laravel\Events\AuthenticatedModelTrashed::class => \Adldap\Laravel\Listeners\LogTrashedModel::class,
],
],
];
Here is my LdapController.php where I include function to reset password
public function resetPassword(Request $req)
{
$req->validate([
'userid' => 'required',
'password' => 'required|min:6|confirmed'
]);
$userLdap = Adldap::search()->where('uid', $req->userid)->firstOrFail();
$newPassword = "{SHA}" . base64_encode(pack("H*", sha1($req->password)));
$res = $userLdap->update([
'userpassword' => $newPassword
]);
//Force change AD Password
// $adPassword = str_replace("\n", "", shell_exec("echo -n '\"" . $req->password . "\"' | recode latin1..utf-16le/base64"));
// $provider = Adldap\Models\User::connect('ad');
// $dn = $provider->search()->where('cn', $req->userid)->get();
// $res = $dn->setPassword($adPassword);
if ($res) {
return back()->withSuccess('<strong>Success!</strong> Your password has been changed');
} else {
return back()->withErrors('<strong>Failed!</strong> Your password was unable to changed');
}
}
Unfortunately $res = $dn->setPassword($adPassword); returns error 'Method Adldap\Query\Collection::setPassword does not exist.'
I found an example here when I searched Google for "Adldap2-laravel change password".
$user = Adldap::users()->find('jdoe');
if ($user instanceof Adldap\Models\User) {
$oldPassword = 'password123';
$newPassword = 'correcthorsebatterystaple';
$user->changePassword($oldPassword, $newPassword);
}
If you want to reset the password, then it seems like this should work:
$user->setPassword("correcthorsebatterystaple");
$user->save();
If you want to know what's going on underneath, or how it can be done without Adldap2-laravel:
The attribute is unicodePwd. You can either "change" the password, or "reset" it.
Changing the password requires knowing the old password. This is what a user would do themselves.
Resetting a password requires the "Reset password" permission on the account, which is usually given to administrative accounts.
The documentation for unicodePwd tells you how to do both. For a "change", you send a delete instruction with the old password and an add instruction with the new one, all in the same request.
For a reset, you send a single replace instruction.
In both cases, the passwords have to be sent in a specific format.
The PHP documentation for 'ldap_modify_batch` shows an example of how to change a password.
On the documentation page for ldap_mod_replace, there is a comment that shows you how to reset a password.
I clone braintree project from https://github.com/braintree/braintree_php_example. Than I created account https://www.braintreepayments.com/sandbox. I must to return client_token. I debug this code
$result = Braintree\Transaction::sale([
'amount' => $amount,
'paymentMethodNonce' => $nonce,
'options' => [
'submitForSettlement' => true
]
]);
var_dump($result->transaction);
But token = null. Maybe my steps are incorrect?
////////////////////////////////
I did it!
I create user
$result = Braintree_Customer::create([
'firstName' => 'Mike',
'lastName' => 'Jones',
'company' => 'Jones Co.',
'email' => 'mike.jones#example.com',
'phone' => '281.330.8004',
'fax' => '419.555.1235',
'website' => 'http://example.com']);
Than I get customer_id
$result->customer->id;
Than I get token
$clientToken = Braintree_ClientToken::generate([
"customerId" => $result->customer->id
]);
Maybe problem with custom register in https://www.braintreepayments.com/sandbox.
Maybe I didn't put all information
I am working on laravel Demo application and i am using login authentication for frontend and backend both are using different tables users and admin respectively.
To achieved multiauth in laravel 4 i have used https://github.com/ollieread/multiauth library.
Now my problem is i don't know how to handle both-side login authentication. I have followed all the instructions as provided in github. its working fine for me as frontend side with users table but its not working for admin table for backend
I am getting error for backend login.
Call to undefined method Admin::newQuery()
Here i am providing my code snippest what i have done so far.
auth.php
'multi' => array(
'admin' => array(
'driver' => 'eloquent',
'model' => 'Admin'
),
'user' => array(
'driver' => 'database',
'table' => 'users'
)
)
userController.php frontend
public function doLogin() {
$input = Input::all();
$credentials = array(
'email' => $input['email'],
'password' => $input['password']
);
if(Auth::user()->attempt($credentials)){
return Redirect::intended('/');
}
// authentication failure! lets go back to the login page
return Redirect::to('login')->with('error_message', 'Invalid email or password')->withInput();
}
adminLoginController.php backend
public function doLogin() {
$input = Input::all();
$credentials = array(
'username' => $input['username'],
'password' => $input['password']
);
if (Auth::admin()->attempt($credentials)) {
return Redirect::route('dashboard');
}
// authentication failure! lets go back to the login page
return Redirect::to('admin/')->with('error_meessage', 'Invalid username or password')->withInput();
}
Try this:
Instead of this:
'multi' => array(
'admin' => array(
'driver' => 'eloquent',
'model' => 'Admin'
),
'user' => array(
'driver' => 'database',
'table' => 'users'
)
)
Use this:
'multi' => array(
'admin' => array(
'driver' => 'database',
'model' => 'Admin',
'table' => 'admin'
),
'user' => array(
'driver' => 'eloquent',
'model' => 'User',
'table' => 'users'
)
)
I want to add a custom rule to PhpManager RBAC in Yii 2.0.
Here is the custom rule (#app/rbac/OwnerRule.php):
<?php
namespace app\rbac;
use yii\rbac\Rule;
/**
* Checks if userID matches user passed via params
*/
class OwnerRule extends Rule
{
public $name = 'isOwner';
public function execute($user, $item, $params)
{
$access = false;
if(isset($params['id'])){
// My custom logic used to set $access
}
return $access;
}
}
Here is the RBAC hierarchy file (#app/data/rbac.php)
<?php
use yii\rbac\Item;
return [
'manageThing0' => ['type' => Item::TYPE_OPERATION, 'description' => '...', 'bizRule' => NULL, 'data' => NULL],
'manageThing1' => ['type' => Item::TYPE_OPERATION, 'description' => '...', 'bizRule' => NULL, 'data' => NULL],
'manageThing2' => ['type' => Item::TYPE_OPERATION, 'description' => '...', 'bizRule' => NULL, 'data' => NULL],
// AND THE ROLES
'guest' => [
'type' => Item::TYPE_ROLE,
'description' => 'Guest',
'bizRule' => NULL,
'data' => NULL
],
'user' => [
'type' => Item::TYPE_ROLE,
'description' => 'User',
'children' => [
'guest',
'manageThing0', // User can edit thing0
],
'bizRule' => 'return !Yii::$app->user->isGuest;',
'data' => NULL
],
'moderator' => [
'type' => Item::TYPE_ROLE,
'description' => 'Moderator',
'children' => [
'user', // Can manage all that user can
'manageThing1', // and also thing1
],
'bizRule' => NULL,
'data' => NULL
],
'admin' => [
'type' => Item::TYPE_ROLE,
'description' => 'Admin',
'children' => [
'moderator', // can do all the stuff that moderator can
'manageThing2', // and also manage thing2
],
'bizRule' => NULL,
'data' => NULL
],
];
How do I use my custom rule in the hierarchy file?
See these links hope you will find what you are looking for,
http://www.yiiframework.com/doc-2.0/guide-security-authorization.html
http://yii2-user.dmeroff.ru/docs/custom-access-control
RBAC for basic yii2 template