Skip to content

A free open source IT asset/license management system

LDAP sync improvements and DB query fix. (#4148)

Richard Hofmanf2be40991430
diff --git a/app/Console/Commands/LdapSync.php b/app/Console/Commands/LdapSync.php
index 48b7697356..827de4e55e 100755
--- a/app/Console/Commands/LdapSync.php
+++ b/app/Console/Commands/LdapSync.php
@@ -16,7 +16,7 @@ class LdapSync extends Command
*
* @var string
*/
- protected $signature = 'snipeit:ldap-sync {--location=} {--location_id=} {--summary}';
+ protected $signature = 'snipeit:ldap-sync {--location=} {--location_id=} {--summary} {--json_summary}';
/**
* The console command description.
@@ -55,14 +55,14 @@ class LdapSync extends Command
try {
$ldapconn = Ldap::connectToLdap();
- } catch (\Exception $e) {
- LOG::error($e);
- }
-
- try {
Ldap::bindAdminToLdap($ldapconn);
} catch (\Exception $e) {
+ if ($this->option('json_summary')) {
+ $json_summary = [ "error" => true, "error_message" => $e->getMessage(), "summary" => [] ];
+ $this->info(json_encode($json_summary));
+ }
LOG::error($e);
+ return [];
}
$summary = array();
@@ -70,12 +70,12 @@ class LdapSync extends Command
$results = Ldap::findLdapUsers();
$ldap_ou_locations = Location::whereNotNull('ldap_ou')->get();
-
+
if (sizeof($ldap_ou_locations) > 0) {
LOG::debug('Some locations have special OUs set. Locations will be automatically set for users in those OUs.');
}
- $results = Ldap::findLdapUsers();
+ // Inject location information fields
for ($i = 0; $i < $results["count"]; $i++) {
$results[$i]["ldap_location_override"] = false;
$results[$i]["location_id"] = 0;
@@ -90,8 +90,8 @@ class LdapSync extends Command
LOG::debug('Location ID '.$this->option('location_id').' passed');
LOG::debug('Importing to '.$location->name.' ('.$location->id.')');
} else {
- $location = NULL;
- }
+ $location = NULL;
+ }
if (!isset($location)) {
LOG::debug('That location is invalid or a location was not provided, so no location will be assigned by default.');
@@ -135,6 +135,14 @@ class LdapSync extends Command
$item["ldap_location_override"] = isset($results[$i]["ldap_location_override"]) ? $results[$i]["ldap_location_override"]:"";
$item["location_id"] = isset($results[$i]["location_id"]) ? $results[$i]["location_id"]:"";
+ if ( array_key_exists('useraccountcontrol', $results[$i]) ) {
+ $enabled_accounts = [
+ '512', '544', '66048', '66080', '262656', '262688', '328192', '328224'
+ ];
+ $item['activated'] = ( in_array($results[$i]['useraccountcontrol'][0], $enabled_accounts) ) ? 1 : 0;
+ } else {
+ $item['activated'] = 0;
+ }
// User exists
$item["createorupdate"] = 'updated';
@@ -145,14 +153,12 @@ class LdapSync extends Command
}
// Create the user if they don't exist.
-
-
$user->first_name = e($item["firstname"]);
$user->last_name = e($item["lastname"]);
$user->username = e($item["username"]);
$user->email = e($item["email"]);
$user->employee_num = e($item["employee_number"]);
- $user->activated = 1;
+ $user->activated = $item['activated'];
if ($item['ldap_location_override'] == true) {
$user->location_id = $item['location_id'];
@@ -190,11 +196,11 @@ class LdapSync extends Command
}
}
+ } else if ($this->option('json_summary')) {
+ $json_summary = [ "error" => false, "error_message" => "", "summary" => $summary ];
+ $this->info(json_encode($json_summary));
} else {
return $summary;
}
-
-
-
}
}
diff --git a/app/Http/Controllers/UsersController.php b/app/Http/Controllers/UsersController.php
index 31f3741445..0a8eb4c0fa 100755
--- a/app/Http/Controllers/UsersController.php
+++ b/app/Http/Controllers/UsersController.php
@@ -33,6 +33,7 @@ use URL;
use View;
use Illuminate\Http\Request;
use Gate;
+use Artisan;
/**
* This controller handles all actions related to Users for
@@ -1029,128 +1030,20 @@ class UsersController extends Controller
*/
public function postLDAP(Request $request)
{
- $this->authorize('update', User::class);
- ini_set('max_execution_time', 600); //600 seconds = 10 minutes
- ini_set('memory_limit', '500M');
-
- $ldap_result_username = Setting::getSettings()->ldap_username_field;
- $ldap_result_last_name = Setting::getSettings()->ldap_lname_field;
- $ldap_result_first_name = Setting::getSettings()->ldap_fname_field;
+ // Call Artisan LDAP import command.
+ $location_id = $request->input('location_id');
+ Artisan::call('snipeit:ldap-sync', ['--location_id' => $location_id, '--json_summary' => true]);
- $ldap_result_active_flag = Setting::getSettings()->ldap_active_flag_field;
- $ldap_result_emp_num = Setting::getSettings()->ldap_emp_num;
- $ldap_result_email = Setting::getSettings()->ldap_email;
+ // Collect and parse JSON summary.
+ $ldap_results_json = Artisan::output();
+ $ldap_results = json_decode($ldap_results_json, true);
- try {
- $ldapconn = Ldap::connectToLdap();
- } catch (\Exception $e) {
- return redirect()->back()->withInput()->with('error', $e->getMessage());
- }
-
- try {
- Ldap::bindAdminToLdap($ldapconn);
- } catch (\Exception $e) {
- return redirect()->back()->withInput()->with('error', $e->getMessage());
- }
-
- $summary = array();
-
- $ldap_ou_locations = Location::whereNotNull('ldap_ou')->get();
-
- $results = Ldap::findLdapUsers();
-
- // Inject location information fields
- for ($i = 0; $i < $results["count"]; $i++) {
- $results[$i]["ldap_location_override"] = false;
- $results[$i]["location_id"] = 0;
- }
-
- // Grab subsets based on location-specific DNs, and overwrite location for these users.
- foreach ($ldap_ou_locations as $ldap_loc) {
- $location_users = Ldap::findLdapUsers($ldap_loc->ldap_ou);
- $usernames = array();
- for ($i = 0; $i < $location_users["count"]; $i++) {
- $location_users[$i]["ldap_location_override"] = true;
- $location_users[$i]["location_id"] = $ldap_loc->id;
- $usernames[] = $location_users[$i][$ldap_result_username][0];
- }
-
- // Delete located users from the general group.
- foreach ($results as $key => $generic_entry) {
- if (in_array($generic_entry[$ldap_result_username][0], $location_users)) {
- unset($results[$key]);
- }
- }
-
- $global_count = $results['count'];
- $results = array_merge($location_users, $results);
- $results['count'] = $global_count;
- }
-
- $tmp_pass = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 20);
- $pass = bcrypt($tmp_pass);
-
- for ($i = 0; $i < $results["count"]; $i++) {
- if (empty($ldap_result_active_flag) || $results[$i][$ldap_result_active_flag][0] == "TRUE") {
-
- $item = array();
- $item["username"] = isset($results[$i][$ldap_result_username][0]) ? $results[$i][$ldap_result_username][0] : "";
- $item["employee_number"] = isset($results[$i][$ldap_result_emp_num][0]) ? $results[$i][$ldap_result_emp_num][0] : "";
- $item["lastname"] = isset($results[$i][$ldap_result_last_name][0]) ? $results[$i][$ldap_result_last_name][0] : "";
- $item["firstname"] = isset($results[$i][$ldap_result_first_name][0]) ? $results[$i][$ldap_result_first_name][0] : "";
- $item["email"] = isset($results[$i][$ldap_result_email][0]) ? $results[$i][$ldap_result_email][0] : "" ;
- $item["ldap_location_override"] = isset($results[$i]["ldap_location_override"]) ? $results[$i]["ldap_location_override"]:"";
- $item["location_id"] = isset($results[$i]["location_id"]) ? $results[$i]["location_id"]:"";
-
- if( array_key_exists('useraccountcontrol', $results[$i]) ) {
- $enabled_accounts = [
- '512', '544', '66048', '66080', '262656', '262688', '328192', '328224'
- ];
- $item['activated'] = ( in_array($results[$i]['useraccountcontrol'][0], $enabled_accounts) ) ? 1 : 0;
- } else {
- $item['activated'] = 0;
- }
-
- // User exists
- $item["createorupdate"] = 'updated';
- if (!$user = User::where('username', $item["username"])->first()) {
- $user = new User;
- $user->password = $pass;
- $item["createorupdate"] = 'created';
- }
-
- // Create the user if they don't exist.
- $user->first_name = $item["firstname"];
- $user->last_name = $item["lastname"];
- $user->username = $item["username"];
- $user->email = $item["email"];
- $user->employee_num = e($item["employee_number"]);
- $user->activated = $item['activated'];
-
- if ($item['ldap_location_override'] == true) {
- $user->location_id = $item['location_id'];
- } else if ($request->input('location_id')!='') {
- $user->location_id = e($request->input('location_id'));
- }
- $user->notes = 'Imported from LDAP';
- $user->ldap_import = 1;
-
- $errors = '';
-
- if ($user->save()) {
- $item["note"] = $item["createorupdate"];
- $item["status"]='success';
- } else {
- foreach ($user->getErrors()->getMessages() as $key => $err) {
- $errors .='<li>'.$err[0];
- }
- $item["note"] = $errors;
- $item["status"]='error';
- }
- array_push($summary, $item);
- }
+ // Direct user to appropriate status page.
+ if ($ldap_results['error']) {
+ return redirect()->back()->withInput()->with('error', $ldap_results['error_message']);
+ } else {
+ return redirect()->route('ldap/user')->with('success', "LDAP Import successful.")->with('summary', $ldap_results['summary']);
}
- return redirect()->route('ldap/user')->with('success', "LDAP Import successful.")->with('summary', $summary);
}
diff --git a/app/Models/Location.php b/app/Models/Location.php
index bb0e80e53a..37348bd4a8 100755
--- a/app/Models/Location.php
+++ b/app/Models/Location.php
@@ -83,6 +83,11 @@ class Location extends SnipeModel
// return $this->hasMany('\App\Models\Asset', 'assigned_to')->withTrashed();
}
+ public function setLdapOuAttribute($ldap_ou)
+ {
+ return $this->attributes['ldap_ou'] = empty($ldap_ou) ? null : $ldap_ou;
+ }
+
public static function getLocationHierarchy($locations, $parent_id = null)
{
diff --git a/resources/views/locations/edit.blade.php b/resources/views/locations/edit.blade.php
index 6bed6e96aa..ee65d69339 100755
--- a/resources/views/locations/edit.blade.php
+++ b/resources/views/locations/edit.blade.php
@@ -47,11 +47,11 @@
<!-- LDAP Search OU -->
@if ($snipeSettings->ldap_enabled == 1)
- <div class="form-group {{ $errors->has('currency') ? ' has-error' : '' }}">
+ <div class="form-group {{ $errors->has('ldap_ou') ? ' has-error' : '' }}">
<label for="ldap_ou" class="col-md-3 control-label">
{{ trans('admin/locations/table.ldap_ou') }}
</label>
- <div class="col-md-7{{ (\App\Helpers\Helper::checkIfRequired($item, 'currency')) ? ' required' : '' }}">
+ <div class="col-md-7{{ (\App\Helpers\Helper::checkIfRequired($item, 'ldap_ou')) ? ' required' : '' }}">
{{ Form::text('ldap_ou', Input::old('ldap_ou', $item->ldap_ou), array('class' => 'form-control')) }}
{!! $errors->first('ldap_ou', '<span class="alert-msg">:message</span>') !!}
</div>