Laratrust 6x- problems with db:seed - laravel-7

I need help about php artisan db:seed.
I installed Laratrust 5.2 for Laravel 7 and than i make upgrade from 5.2 to 6.
I follow this steps: https://laratrust.santigarcor.me/docs/6.x/upgrade.html;
This is how it works, everything is ok.
Later, I ran the command: php artisan migrate:fresh to get the new tables but I have a problem:
sviluppo#Mac-mini-di-sviluppo prova % php artisan migrate:fresh
Dropped all tables successfully.
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_000000_create_users_table (0.04 seconds)
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated: 2014_10_12_100000_create_password_resets_table (0.04 seconds)
Migrating: 2019_08_19_000000_create_failed_jobs_table
Migrated: 2019_08_19_000000_create_failed_jobs_table (0.02 seconds)
Migrating: 2022_09_26_102236_laratrust_setup_tables
Migrated: 2022_09_26_102236_laratrust_setup_tables (0.39 seconds)
Migrating: 2022_09_26_102709_create_roles_table
Illuminate\Database\QueryException
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'roles' already exists (SQL: create table `roles` (`id` bigint unsigned not null auto_increment primary key, `created_at` timestamp null, `updated_at` timestamp null) default character set utf8mb4 collate 'utf8mb4_unicode_ci')
at vendor/laravel/framework/src/Illuminate/Database/Connection.php:671
667| // If an exception occurs when attempting to run a query, we'll format the error
668| // message to include the bindings with SQL, which will make this exception a
669| // lot more helpful to the developer instead of just the database's errors.
670| catch (Exception $e) {
> 671| throw new QueryException(
672| $query, $this->prepareBindings($bindings), $e
673| );
674| }
675|
+9 vendor frames
10 database/migrations/2022_09_26_102709_create_roles_table.php:19
Illuminate\Support\Facades\Facade::__callStatic("create")
+32 vendor frames
43 artisan:37
Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
sviluppo#Mac-mini-di-sviluppo visan-day-app %
And if i run:
sviluppo#Mac-mini-di-sviluppo prova % php artisan db:seed
Seeding: LaratrustSeeder
Truncating User, Role and Permission tables
The configuration has not been published. Did you run `php artisan vendor:publish --tag="laratrust-seeder"`
Seeded: LaratrustSeeder (0.03 seconds)
Database seeding completed successfully.
Info:
My file in laratrust.php e laratrust_seeder.php are config;
There are tables in the database/migrations;
It is present within database/seed/DatabaseSeeder.php => $this->call(LaratrustSeeder::class);
My file laratrustSeeder.php:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;
class LaratrustSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$this->truncateLaratrustTables();
$config = Config::get('laratrust_seeder.roles_structure');
if ($config === null) {
$this->command->error("The configuration has not been published. Did you run `php artisan vendor:publish --tag=\"laratrust-seeder\"`");
$this->command->line('');
return false;
}
$mapPermission = collect(config('laratrust_seeder.permissions_map'));
foreach ($config as $key => $modules) {
// Create a new role
$role = \App\Role::firstOrCreate([
'name' => $key,
'display_name' => ucwords(str_replace('_', ' ', $key)),
'description' => ucwords(str_replace('_', ' ', $key))
]);
$permissions = [];
$this->command->info('Creating Role '. strtoupper($key));
// Reading role permission modules
foreach ($modules as $module => $value) {
foreach (explode(',', $value) as $p => $perm) {
$permissionValue = $mapPermission->get($perm);
$permissions[] = \App\Permission::firstOrCreate([
'name' => $module . '-' . $permissionValue,
'display_name' => ucfirst($permissionValue) . ' ' . ucfirst($module),
'description' => ucfirst($permissionValue) . ' ' . ucfirst($module),
])->id;
$this->command->info('Creating Permission to '.$permissionValue.' for '. $module);
}
}
// Attach all permissions to the role
$role->permissions()->sync($permissions);
if (Config::get('laratrust_seeder.create_users')) {
$this->command->info("Creating '{$key}' user");
// Create default user for each role
$user = \App\User::create([
'name' => ucwords(str_replace('_', ' ', $key)),
'email' => $key.'#app.com',
'password' => bcrypt('password')
]);
$user->attachRole($role);
}
}
}
/**
* Truncates all the laratrust tables and the users table
*
* #return void
*/
public function truncateLaratrustTables()
{
$this->command->info('Truncating User, Role and Permission tables');
Schema::disableForeignKeyConstraints();
DB::table('permission_role')->truncate();
DB::table('permission_user')->truncate();
DB::table('role_user')->truncate();
if (Config::get('laratrust_seeder.truncate_tables')) {
DB::table('roles')->truncate();
DB::table('permissions')->truncate();
if (Config::get('laratrust_seeder.create_users')) {
$usersTable = (new \App\User)->getTable();
DB::table($usersTable)->truncate();
}
}
Schema::enableForeignKeyConstraints();
}
}
Thanks!

Related

Get all the blobs inside sub directory inside container

So I'm having issues on getting the blobs inside my container - I'm able to successfully grab all the blobs inside a container, but not inside a folder in the container - How would I be able to successfully do that?
Problem:
I have a folder inside my container called 'big/' - How would I be able to grab all the blobs from that folder instead of just the generic container as I'm doing below?
All help would be appreciated!
So here is the getBlobs() method that I have (View the image and code below):
/**
* Get all blobs from container
*
* #param int $max
* #return array
*/
public function getBlobs(int $max = 5000) : array
{
// Check if a container is set
if (!$this->containerName) {
return [];
}
try {
$blobMeta = [];
$blobOptions = new ListBlobsOptions();
// Set the max results at 5000 (Default: 5000)
$blobOptions->setMaxResults($max);
do {
// Grab the defined container
$blob_list = $this->connect()->listBlobs(
$this->containerName,
$blobOptions
);
var_dump($blob_list);
die();
// Loop through all the
foreach ($blob_list->getBlobs() as $blob) {
$blobMeta[] = [
'name' => $blob->getName(),
'url' => $blob->getUrl(),
];
}
$blobOptions->setContinuationToken($blob_list->getContinuationToken());
} while ($blob_list->getContinuationToken());
return $blobMeta;
} catch (ServiceException $e) {
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code . ": " . $error_message . PHP_EOL;
return [];
}
}
If you want to list blobs under a folder, you can use ListBlobsOptions to setPrefix("YourFolderName/") to do this. You can find a detailed code sample in listBlobsSample function at line 430 here.

Codeigniter 4 Query Builder loses SELECT and WHERE condition while executing once more

I am using Codeigniter 4 Query Builder.
Following is code to retrieve data from the database
public function get_data()
{
$where = [
'username' => 'admin'
];
$this->_builder = $this->_db->table('pf_user_master s');
$this->_builder->join('pf_role_master r', 'r.role_id = s.role_id');
$this->_builder->select('username, first_name, last_name, mobile, email, r.role_name, s.status');
if (is_array($where) && !empty($where)) {
$this->_builder->where($where);
}
$first= $this->_builder->get()->getResultArray();
print_r($first);
$second= $this->_builder->get()->getResultArray();
print_r($second);
exit;
}
I am getting the following output:
In variable $first I am getting output as expected
Array
(
[0] => Array
(
[username] => admin
[first_name] => Fisrt
[last_name] => Last
[mobile] =>
[email] => first.last#gmail.com
[role_name] => Admin
[status] => 1
)
)
But in variable $second it Query Builder loses SELECT, WHERE condition and also JOIN.
And prints the output as follows:
Array
(
[0] => Array
(
[user_id] => 1
[username] => admin
[password] => 21232f297a57a5a743894a0e4a801fc3
[first_name] => First
[last_name] => Last
[mobile] =>
[email] => first.last#gmail.com
[role_id] => 1
[status] => 1
[created_by] =>
[created_date] => 2020-09-08 19:30:52
[updated_by] =>
[updated_date] => 2020-09-08 19:32:42
)
[1] => Array
(
[user_id] => 2
[username] => superadmin
[password] => 21232f297a57a5a743894a0e4a801fc3
[first_name] => NewFirst
[last_name] => NewLast
[mobile] =>
[email] => new.new#gmail.com
[role_id] => 1
[status] => 1
[created_by] =>
[created_date] => 2020-09-08 21:51:42
[updated_by] =>
[updated_date] =>
)
)
I've not tested this and it comes from reading the documentation only.
In the CodeIgniter documentation get() has the following parameters
get([$limit = NULL[, $offset = NULL[, $reset = TRUE]]]])
Reference: https://codeigniter.com/user_guide/database/query_builder.html#get
If you were to use
$first= $this->_builder->get(NULL,NULL,FALSE)->getResultArray();
Then your code would become:
public function get_data()
{
$where = [
'username' => 'admin'
];
$this->_builder = $this->_db->table('pf_user_master s');
$this->_builder->join('pf_role_master r', 'r.role_id = s.role_id');
$this->_builder->select('username, first_name, last_name, mobile, email, r.role_name, s.status');
if (is_array($where) && !empty($where)) {
$this->_builder->where($where);
}
$first= $this->_builder->get(NULL,NULL,FALSE)->getResultArray();
print_r($first);
$second= $this->_builder->get()->getResultArray();
print_r($second);
exit;
}
Of course if you were to perform this a 3rd time, the 2nd instance should cause a reset.
The Code is the Documentation ( in most cases ) so we have
In CodeIgniter 4.04 - /system/Database/BaseBuilder.php - Line 1824
The code is
/**
* Get
*
* Compiles the select statement based on the other functions called
* and runs the query
*
* #param integer $limit The limit clause
* #param integer $offset The offset clause
* #param boolean $reset Are we want to clear query builder values?
*
* #return ResultInterface
*/
public function get(int $limit = null, int $offset = 0, bool $reset = true)
{
if (! is_null($limit))
{
$this->limit($limit, $offset);
}
$result = $this->testMode
? $this->getCompiledSelect($reset)
: $this->db->query($this->compileSelect(), $this->binds, false);
if ($reset === true)
{
$this->resetSelect();
// Clear our binds so we don't eat up memory
$this->binds = [];
}
return $result;
}
So the default for $reset, will "clear" what you have observed.
As mentioned by TimBrownlaw
I changed
$first= $this->_builder->get()->getResultArray();
to
$first= $this->_builder->get(NULL, 0 , false)->getResultArray();
and it worked for me as it didn't reset the query as third parameter of get() is for resetting the query

Password is expired just after user is added to FreeIPA?

I have set up a FreeIPA server. I am facing an issue which is password is expired when a user is first created. So a new user should always set his password when he logs in for the first time which is defined in here. but I don't want this feature.
I am using this library to create or add user in FreeIPA.
So, I connect with FreeIPA like this-
private function getIPA()
{
$host = env('FREEIPA_HOST', 'cloud-host-ipa.com');
$certificate = database_path(env('FREEIPA_CERTIFICATE', 'ca.crt'));
try {
return new \FreeIPA\APIAccess\Main($host, $certificate);
} catch (Exception $e) {
throw new \ErrorException("Error {$e->getCode()}: {$e->getMessage()}");
return false;
}
}
private function getIPAConnection() //Ged authinticated admin IPA connection
{
$ipa = $this->getIPA();
try {
$auth = $ipa->connection()->authenticate(env('FREEIPA_ADMIN_NAME', 'oc-ipa-connector'), env('FREEIPA_ADMIN_PASS', 'ADMIN_PASS'));
if ($auth) {
return $ipa;
} else {
$auth_info = $ipa->connection()->getAuthenticationInfo();
$auth_info = implode(' ', $auth_info);
throw new \ErrorException("\nLogin Failed : {$auth_info}");
//return false;
}
} catch (Exception $e) {
throw new \ErrorException("\nError {$e->getCode()}: {$e->getMessage()}");
//return false;
}
}
Then add a user like this-
$ipa = $this->getIPAConnection();
try {
$new_user_data = array(
'givenname' => $givenname,
'sn' => $sn,
'uid' => $uid,
//'userpassword' => $_POST["userpassword"],
'mail' => $mail,
'mobile' => $phone
);
$add_user = $ipa->user()->add($new_user_data);
if ($add_user) {
return true;
}
} catch (Exception $e) {
throw new \ErrorException("Error {$e->getCode()}: {$e->getMessage()}");
return false;
}
This code works fine and user is added.
Then I am setting password with this code-
$ipa = $this->getIPAConnection();
try {
$user_info = $ipa->user()->get($uid);
if($user_info != false)
{
try {
$new_user_data = array(
'userpassword' => $password,
);
$mod_user = $ipa->user()->modify($uid, $new_user_data);
if ($mod_user) {
return true;
}
else
{
return false;
}
} catch (Exception $e) {
throw new \ErrorException("Error {$e->getCode()}: {$e->getMessage()}");
}
}
} catch (Exception $e) {
throw new \ErrorException("Error {$e->getCode()}: {$e->getMessage()}");
}
Password is also set perfectly. But the set password is expired automatically just after it is set.
I want my users to have this password for at least 1 week. So, I want to disable this feature. Is there any practical way?
Re-
I have created this issue in FreeIPA to provide us with a workaround, but the issue is closed and marked as - Closed: wontfix . So, I wonder if there exists a workaround?
The answer was provided in the link https://www.redhat.com/archives/freeipa-users/2012-June/msg00360.html.
There is a global policy for passwords that you can see from the command below:
[server]$ ipa pwpolicy-show
Group: global_policy
Max lifetime (days): 90
Min lifetime (hours): 1
History size: 0
Character classes: 0
Min length: 8
Max failures: 6
Failure reset interval: 60
Lockout duration: 600
You can create a new policy override for the group to which you are adding the user by running the command:
[server]$ ipa pwpolicy-add sysadmin --minlife=0
Priority: 50
Group: sysadmin
Min lifetime (hours): 0
Priority: 50
Now this policy overrides the global password policy and creates a policy just for the group.
If you want to modify the global policy, you can do the same with the command:
[server]$ ipa pwpolicy-mod global_policy --minlife=0
Group: global_policy
Max lifetime (days): 90
Min lifetime (hours): 0
History size: 0
Character classes: 0
Min length: 8
Max failures: 6
Failure reset interval: 60
Lockout duration: 600
Note the change in Min lifetime(hours) to 0 which causes password to never expire.
After you create the user you need to run this code from a script in the server:
echo -e $PASSWORD\n$PASSWORD\n$PASSWORD | kinit $username
kdestroy
Note that you need to send PASSWORD and username as parameters to the script and execute this script remotely.
See https://www.freeipa.org/page/New_Passwords_Expired - basically FreeIPA have a policy that admin-set passwords are immediately expired. I believe the "password lifetime" then only applies once the user has themselves changed their password.

How can I reset the cron task with elysia cron?

I can't reset the cron task.
I did force run than ran the cron and nothing. mymodule_queue_function - doesn't execute and the $count always increases.
I was trying reset count in maintenance settings (reset statistics) but it doesn't work.
How can I fix it?
mymodule_cronapi($op, $job = NULL) {
$items['functions_cron_month_prepare'] = array(
'description' => 'users pay for services',
'rule' => '4 0 24 * *',
'arguments' => array(5),
'callback' => 'mymodule_select_month_prepare',
);
return $items;
}
// /** * Implementation of hook_cron_queue_info() */
function tariffing_cron_queue_info() {
$queues['mymodule_queue_main'] = array(
'worker callback' => 'mymodule_queue_function',
'time' => 3600,
);
return $queues;
}
function mymodule_select_month_prepare() {
if($users) {
foreach ($users as $usr) {
$usr_s[$usr['uid']][] = $usr['service_name'];
}
$n = round(count($usr_s)/4);
$items = count($usr_s) > 4 ? array_chunk($usr_s, $n, true) : array(0 => $usr_s);
$queue = DrupalQueue::get('mymodule_queue_main');
foreach ($items as $item) {
$count = $queue->numberOfItems();
$queue->createItem($item);
}
}
}
function mymodule_queue_function($data) {
watchdog('$data_users', print_r($data,true));
}
The problem was resolved by replacing the name of the function. But appeared another problem:
The time of my cron task is (4 0 1 * *) but now 25th day, and the job task was executed. Why?? What did I wrong?
Could did it happen case I deleted all cron execution statistics?

login to modx from external/other server revolution 2.2.5

I am pissed off with this problem from 2 days.
I am using MODx Revolution 2.2.5 (traditional) and want to login to modx from external server just to fetch some user details.
1) I know that runprocessor method works only if i am logged in to manager (unfortunately, that's the only way i know to login user in) So i tried IFRAME method to avoid (cross scripting) it worked perfectly but i am not able to read the data from IFRAME using javascript because of same issue, cross domain access policy.
When i try to post data using some other method like CURL, Ajax using
header("Access-Control-Allow-Origin: *");
I am able to login (I see $response->response['success'] == 1) but cant access any data and it says
Fatal error: Call to a member function get() on a non-object
Below is the snippet code i am using
if(isset($_POST) && count($_POST)){
$c = array(
'username' => $_POST['username'],
'password' => $_POST['password']
);
$response = $modx->runProcessor('security/login',$c);
if($response->response['success'] == 1){
$user['id'] = $modx->user->get('id');
$profile = $modx->user->getOne('Profile');
$user['fullname'] = $profile->get('fullname');
$user['email'] = $profile->get('email');
echo json_encode($user);
}else{
echo json_encode($response->response);
}
}
2) I can use login snippet but it doesnt return output what i expect. We have ready site and we are already using login plugin so i cant even modify login plugin to respond with expected data
How can i login to modx using api or any other method ??
You are really attacking this problem completely wrong in my opinion. If you want to access a server/webpage from another, you don't iFrame and do it the way you are. That is hacking, and this hole will most likely be fixed in a future version.
What you SHOULD do is connecting to the database and just gather the information from the user-table.
No hacking, no "tricks", won't stop working and much safer.
Well, I sorted out this today, Below is the complete come that worked perfectly.
Pay attention to
header("Access-Control-Allow-Origin: http://www.xyz.com");
Using above CORS specification you can allow 2 servers to communication.
header("Access-Control-Allow-Origin: http://www.xyz.com");
if(isset($_POST['username']) && isset($_POST['password'])){
// get username and password from POST array
$username = $modx->sanitizeString($_POST['username']);
$password = $modx->sanitizeString($_POST['password']);
if(trim($username) != "" and trim($password) != ""){
// Load lexicons to show proper error messages
if (!isset($modx->lexicon) || !is_object($modx->lexicon)) {
$modx->getService('lexicon','modLexicon');
}
$modx->lexicon->load('login');
$loginContext= isset ($scriptProperties['login_context']) ? $scriptProperties['login_context'] :
$modx->context->get('key');
$addContexts= isset ($scriptProperties['add_contexts']) && !empty($scriptProperties['add_contexts']) ? explode(',', $scriptProperties['add_contexts']) : array();
$mgrEvents = ($loginContext == 'mgr');
$givenPassword = $password;
/** #var $user modUser */
$user= $modx->getObjectGraph('modUser', '{"Profile":{},"UserSettings":{}}', array ('modUser.username' => $username));
if (!$user) {
$ru = $modx->invokeEvent("OnUserNotFound", array(
'user' => &$user,
'username' => $username,
'password' => $password,
'attributes' => array(
'loginContext' => $loginContext,
)
));
if (!empty($ru)) {
foreach ($ru as $obj) {
if (is_object($obj) && $obj instanceof modUser) {
$user = $obj;
break;
}
}
}
if (!is_object($user) || !($user instanceof modUser)) {
//echo "cant locate account";
echo $modx->toJSON($modx->error->failure($modx->lexicon('login_cannot_locate_account')));
exit;
}
}
if (!$user->get('active')) {
//echo "inactivated accout";
echo $modx->toJSON($modx->error->failure($modx->lexicon('login_user_inactive')));
exit;
}
if (!$user->passwordMatches($givenPassword)) {
if (!array_key_exists('login_failed', $_SESSION)) {
$_SESSION['login_failed'] = 0;
}
if ($_SESSION['login_failed'] == 0) {
$flc = ((integer) $user->Profile->get('failedlogincount')) + 1;
$user->Profile->set('failedlogincount', $flc);
$user->Profile->save();
$_SESSION['login_failed']++;
} else {
$_SESSION['login_failed'] = 0;
}
//echo "wrong username pass";
echo $modx->toJSON($modx->error->failure($modx->lexicon('login_username_password_incorrect')));
exit;
}
$fullname = $user->Profile->get('fullname');
echo '{"success":true,"message":"Welcome '.$fullname.'!"}';
}else{
echo '{"success":false,"message":"Please enter username and password"}';
}
}

Resources