/**
  * Execute the command.
  *
  * @return void
  */
 public function handle()
 {
     \Debugbar::disable();
     //Get a list of allDuo Users subscribed to the DuoRegisteredUsersReport
     $users = User::whereHas('reports', function ($query) {
         $query->where('name', 'DuoRegisteredUsersReport');
     })->get();
     //Loop each user to generate report
     foreach ($users as $recipient) {
         $this->dispatch(new GenerateRegisteredDuoUsersReport($recipient));
         //            \Log::debug('Message will be sent to:',[$recipient->email]);
     }
 }
 /**
  * Execute the job.
  *
  * @return void
  */
 public function handle()
 {
     set_time_limit(0);
     ini_set('memory_limit', '2048M');
     //Create the Duo Admin Client and set the timeout higher than default
     $duoAdmin = new DuoAdmin();
     $duoAdmin->setRequesterOption('timeout', '6000000');
     // Set the log $count value to 1000
     $count = 1000;
     $backoff = NULL;
     while ($count >= 1000) {
         \Log::debug('Start Log gathering', ['count' => $count, 'backoff' => $backoff]);
         //Query Duo REST API
         $response = $duoAdmin->logs($this->getMinTime());
         if (isset($response['response']['code']) && $response['response']['code'] == '42901') {
             $backoff += 10;
             \Log::debug('Received backoff notice', ['response' => $response, 'set-backoff' => $backoff]);
             sleep($backoff);
             continue;
         }
         //Duo SDK puts results in nested array [response][response]
         $logs = $response['response']['response'];
         $backoff = NULL;
         \Log::debug('Received Duo Response Object.  Adding new entries ', ['object-count' => count($logs), 'set-backoff' => $backoff]);
         // Loop each log to save
         foreach ($logs as $log) {
             // Get the DuoUser ID to create a relation
             $duoUserId = User::where('username', $log['username'])->first();
             // Sometimes the 'username' from Duo doesn't exist locally....
             if ($duoUserId) {
                 $log['duo_user_id'] = $duoUserId->id;
             } else {
                 $log['duo_user_id'] = NULL;
             }
             // Save the log
             Log::create($log);
         }
         // Set the count to number of logs returned in the last call.
         // If it's less than 1000, we've reached the end of the logs
         \Log::debug('Added new log entries.  Setting count: ', ['count' => count($logs)]);
         $count = count($logs);
     }
 }
 /**
  * @param $freshDuoUserList
  */
 private function removeStaleAccounts($freshDuoUserList)
 {
     \Log::debug('Removing stale accounts from UC Insight (soft delete)');
     //Move the fresh list of usernames from Duo API to an array
     $newDuoUsers = [];
     foreach ($freshDuoUserList as $user) {
         $newDuoUsers[] = $user['user_id'];
     }
     // If there's only 1 user, we're just doing an on-demand
     // user sync, so we shouldn't worry about stale accounts.
     if (count($newDuoUsers) == 1) {
         \Log::debug('We are syncing a single user, no need to remove stale accounts.  Exiting function.');
         return;
     }
     //Get a list of local Duo usernames
     $localDuoUsers = User::lists('user_id')->toArray();
     \Log::debug('Got a list of local DuoUsers - ', [count($localDuoUsers)]);
     //Compare the two arrays
     $staleUsers = array_diff($localDuoUsers, $newDuoUsers);
     \Log::debug('Local DuoUser stale accounts - ', [count($staleUsers)]);
     //Remove the 'stale' user accounts from the local database
     foreach ($staleUsers as $dead) {
         \Log::debug('Removing stale local DuoUser account - ', [$dead]);
         User::where('user_id', $dead)->delete();
     }
 }
 /**
  * @throws \PHPExcel_Exception
  * @throws \PHPExcel_Writer_Exception
  */
 public function handle()
 {
     //Create the reporting Excel Object
     $objPHPExcel = new PHPExcel();
     //Check if the recipient is assigned to a group.  If not, log and continue.
     if ($this->user->duoGroups()->count()) {
         $groups = $this->user->duoGroups()->get();
     } else {
         \Log::debug($this->user->username . ' has no groups:', [$this->user]);
     }
     //Set timestamp for file names
     $timeStamp = Carbon::now('America/New_York')->toDateTimeString();
     //Get our Report object
     $duoReport = Report::where('name', 'DuoRegisteredUsersReport')->first();
     $fileName = storage_path() . '/' . $duoReport->path . $timeStamp . '-' . $duoReport->name . '-' . $this->user->username . '.xlsx';
     //Loop each Duo Group
     foreach ($groups as $group) {
         //Explode csv_headers to array
         $duoReportHeaders = explode(',', $duoReport->csv_headers);
         //Create the group main worksheet
         $this->createWorksheet($objPHPExcel, $group->name, $duoReportHeaders);
         //Create the 'not enrolled' worksheet
         $notEnrolledWorksheetName = $group->name . ' - Not Enrolled';
         $this->createWorksheet($objPHPExcel, $notEnrolledWorksheetName, $duoReportHeaders);
         //Create an array to track users that haven't enrolled.
         $usersNotEnrolled = [];
         //Set the active sheet to the main group sheet
         $objPHPExcel->setActiveSheetIndexByName($group->name);
         //Get all users that belong to this group
         $duoGroupMembers = $group->duoUsers()->get();
         /*
          * Write User data
          */
         $row = 2;
         foreach ($duoGroupMembers as $member) {
             //Check if the user has a registered phone or token
             if ($member->duoPhones()->count() || $member->duoTokens()->count()) {
                 //Record the user details in the main worksheet
                 $objPHPExcel->getActiveSheet()->setCellValue('A' . $row, $member->username);
                 $objPHPExcel->getActiveSheet()->setCellValue('B' . $row, $member->email);
                 $objPHPExcel->getActiveSheet()->setCellValue('C' . $row, $member->status);
                 $objPHPExcel->getActiveSheet()->setCellValue('D' . $row, $member->last_login);
                 $objPHPExcel->getActiveSheet()->setCellValue('E' . $row, $member->duoGroups()->first()->name);
                 $row++;
             } else {
                 //This user hasn't enrolled.
                 //We'll write their info to another worksheet.
                 array_push($usersNotEnrolled, $member);
             }
         }
         //Set the active sheet to the 'not enrolled' group sheet
         $objPHPExcel->setActiveSheetIndexByName($notEnrolledWorksheetName);
         /*
          * Write 'not enrolled' data
          */
         $row = 2;
         foreach ($usersNotEnrolled as $user) {
             //Record the user details in the 'not enrolled' worksheet
             $objPHPExcel->getActiveSheet()->setCellValue('A' . $row, $user->username);
             $objPHPExcel->getActiveSheet()->setCellValue('B' . $row, $user->email);
             $objPHPExcel->getActiveSheet()->setCellValue('C' . $row, $user->status);
             $objPHPExcel->getActiveSheet()->setCellValue('D' . $row, 'Not Enrolled');
             $objPHPExcel->getActiveSheet()->setCellValue('E' . $row, $user->duoGroups()->first()->name);
             $row++;
         }
         unset($usersNotEnrolled);
     }
     //Remove the default sheet (there's gotta be a better way to do this....)
     $objPHPExcel->removeSheetByIndex(0);
     //Write the document
     $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
     $objWriter->save($fileName);
     //Reports are done running, let's email to results
     $beautymail = app()->make(\Snowfire\Beautymail\Beautymail::class);
     $beautymail->send('emails.duo-registered-users', [], function ($message) use($fileName) {
         //TODO: Create system for users to manage report subscriptions.
         $message->from('*****@*****.**', 'Duo Reporting')->to($this->user->email)->subject('Duo Registered Users Report')->attach($fileName);
     });
 }
 public function registeredUsersReport()
 {
     ini_set('memory_limit', '248M');
     //Get the users that have a phone or token
     $phoneUsers = \App\Models\Duo\User::has('duoPhones')->get();
     $tokenUsers = \App\Models\Duo\User::has('duoTokens')->get();
     $users = $phoneUsers->merge($tokenUsers);
     return view('duo.registered-report', compact('users'));
 }