App\Http\Controllers\UsersController Class Reference

This controller handles all actions related to Users for the Snipe-IT Asset Management application. More...

Inheritance diagram for App\Http\Controllers\UsersController:
App\Http\Controllers\Controller

Public Member Functions

 getIndex ()
 Returns a view that invokes the ajax tables which actually contains the content for the users listing, which is generated in getDatatable(). More...
 
 getCreate ()
 Returns a view that displays the user creation form. More...
 
 postCreate (SetupUserRequest $request)
 Validate and store the new user data, or return an error. More...
 
 store ()
 JSON handler for creating a user through a modal. More...
 
 getEdit ($id=null)
 Returns a view that displays the edit user form. More...
 
 postEdit ($id=null)
 Validate and save edited user data from edit form. More...
 
 getDelete ($id=null)
 Delete a user. More...
 
 postBulkEdit ()
 Returns a view that confirms the user's a bulk delete will be applied to. More...
 
 postBulkSave ()
 Soft-delete bulk users. More...
 
 getRestore ($id=null)
 Restore a deleted user. More...
 
 getView ($userId=null)
 Return a view with user detail. More...
 
 getUnsuspend ($id=null)
 Unsuspend a user. More...
 
 getClone ($id=null)
 Return a view containing a pre-populated new user form, populated with some fields from an existing user. More...
 
 getImport ()
 Return user import view. More...
 
 postImport ()
 Handle user import file. More...
 
 getDatatable ($status=null)
 Return JSON response with a list of user details for the getIndex() view. More...
 
 postUpload (AssetFileRequest $request, $userId=null)
 Return JSON response with a list of user details for the getIndex() view. More...
 
 getDeleteFile ($userId=null, $fileId=null)
 Delete file. More...
 
 displayFile ($userId=null, $fileId=null)
 Display/download the uploaded file. More...
 
 getLDAP ()
 Return view for LDAP import. More...
 
 postLDAP ()
 LDAP form processing. More...
 
 getAssetList ($userId)
 Return JSON containing a list of assets assigned to a user. More...
 

Protected Attributes

 $ldapValidationRules
 

Detailed Description

This controller handles all actions related to Users for the Snipe-IT Asset Management application.

Version
v1.0

Definition at line 38 of file UsersController.php.

Member Function Documentation

App\Http\Controllers\UsersController::displayFile (   $userId = null,
  $fileId = null 
)

Display/download the uploaded file.

Author
[A. Gianotto] [snipe.nosp@m.@sni.nosp@m.pe.ne.nosp@m.t]
Since
[v1.6]
Parameters
int$userId
int$fileId
Returns
mixed

Definition at line 1017 of file UsersController.php.

1018  {
1019 
1020  $user = User::find($userId);
1021 
1022  // the license is valid
1023  if (isset($user->id)) {
1024  if (!Company::isCurrentUserHasAccess($user)) {
1025  return Redirect::route('users')->with('error', trans('general.insufficient_permissions'));
1026  } else {
1027  $log = Actionlog::find($fileId);
1028  $file = $log->get_src();
1029  return Response::download($file);
1030  }
1031  } else {
1032  // Prepare the error message
1033  $error = trans('admin/users/message.does_not_exist', compact('id'));
1034 
1035  // Redirect to the licence management page
1036  return Redirect::route('users')->with('error', $error);
1037  }
1038  }
static isCurrentUserHasAccess($companyable)
Definition: Company.php:96
App\Http\Controllers\UsersController::getAssetList (   $userId)

Return JSON containing a list of assets assigned to a user.

Author
[A. Gianotto] [snipe.nosp@m.@sni.nosp@m.pe.ne.nosp@m.t]
Since
[v3.0]
Returns
string JSON

Definition at line 1251 of file UsersController.php.

1252  {
1253  $assets = Asset::where('assigned_to', '=', $userId)->get();
1254  return response()->json($assets);
1255  //$foo = Asset::where('assigned_to','=',$userId)->get();
1256  //print_r($foo);
1257  }
App\Http\Controllers\UsersController::getClone (   $id = null)

Return a view containing a pre-populated new user form, populated with some fields from an existing user.

Author
[A. Gianotto] [snipe.nosp@m.@sni.nosp@m.pe.ne.nosp@m.t]
Since
[v1.0]
Parameters
int$id
Returns
Redirect

Definition at line 608 of file UsersController.php.

609  {
610  // We need to reverse the UI specific logic for our
611  // permissions here before we update the user.
612  $permissions = Input::get('permissions', array());
613  //$this->decodePermissions($permissions);
614  app('request')->request->set('permissions', $permissions);
615 
616 
617  try {
618  // Get the user information
619  $user_to_clone = User::find($id);
620  $user = clone $user_to_clone;
621  $user->first_name = '';
622  $user->last_name = '';
623  $user->email = substr($user->email, ($pos = strpos($user->email, '@')) !== false ? $pos : 0);
624  ;
625  $user->id = null;
626 
627  // Get this user groups
628  $userGroups = $user_to_clone->groups()->lists('group_id', 'name');
629 
630  // Get this user permissions
631  $userPermissions = null;
632  //$this->encodePermissions($userPermissions);
633 
634  // Get a list of all the available groups
635  //$groups = Sentry::getGroupProvider()->findAll();
636 
637  // Get all the available permissions
638  $permissions = config('permissions');
639  //$this->encodeAllPermissions($permissions);
640 
641  $location_list = Helper::locationsList();
642  $company_list = Helper::companyList();
643  $manager_list = array('' => 'Select a User') + DB::table('users')
644  ->select(DB::raw('concat(last_name,", ",first_name," (",email,")") as full_name, id'))
645  ->whereNull('deleted_at')
646  ->where('id', '!=', $id)
647  ->orderBy('last_name', 'asc')
648  ->orderBy('first_name', 'asc')
649  ->lists('full_name', 'id');
650 
651  // Show the page
652  return View::make('users/edit', compact('groups', 'userGroups', 'permissions', 'userPermissions'))
653  ->with('location_list', $location_list)
654  ->with('company_list', $company_list)
655  ->with('manager_list', $manager_list)
656  ->with('user', $user)
657  ->with('clone_user', $user_to_clone);
658  } catch (UserNotFoundException $e) {
659  // Prepare the error message
660  $error = trans('admin/users/message.user_not_found', compact('id'));
661 
662  // Redirect to the user management page
663  return Redirect::route('users')->with('error', $error);
664  }
665  }
static locationsList()
Definition: Helper.php:94
static companyList()
Definition: Helper.php:61
App\Http\Controllers\UsersController::getCreate ( )

Returns a view that displays the user creation form.

Author
[A. Gianotto] [snipe.nosp@m.@sni.nosp@m.pe.ne.nosp@m.t]
Since
[v1.0]
Returns
View

Definition at line 63 of file UsersController.php.

64  {
65 
66  // Selected groups
67  $userGroups = Input::old('groups', array());
68 
69  // Get all the available permissions
70  $permissions = config('permissions');
71 
72  // Selected permissions
73  $userPermissions = Input::old('permissions', array('superuser' => -1));
74  $location_list = Helper::locationsList();
75  $manager_list = Helper::managerList();
76  $company_list = Helper::companyList();
77 
78  /* echo '<pre>';
79  print_r($userPermissions);
80  echo '</pre>';
81  exit;
82  */
83 
84  // Show the page
85  return View::make('users/edit', compact('groups', 'userGroups', 'permissions', 'userPermissions'))
86  ->with('location_list', $location_list)
87  ->with('manager_list', $manager_list)
88  ->with('company_list', $company_list)
89  ->with('user', new User);
90  }
static locationsList()
Definition: Helper.php:94
static companyList()
Definition: Helper.php:61
static managerList()
Definition: Helper.php:115
App\Http\Controllers\UsersController::getDatatable (   $status = null)

Return JSON response with a list of user details for the getIndex() view.

Author
[A. Gianotto] [snipe.nosp@m.@sni.nosp@m.pe.ne.nosp@m.t]
Since
[v1.6]
See also
UsersController::getIndex() method that consumed this JSON response
Returns
string JSON

Definition at line 805 of file UsersController.php.

806  {
807 
808  if (Input::has('offset')) {
809  $offset = e(Input::get('offset'));
810  } else {
811  $offset = 0;
812  }
813 
814  if (Input::has('limit')) {
815  $limit = e(Input::get('limit'));
816  } else {
817  $limit = 50;
818  }
819 
820  if (Input::get('sort')=='name') {
821  $sort = 'first_name';
822  } else {
823  $sort = e(Input::get('sort'));
824  }
825 
826  $users = User::select(array('users.id','users.employee_num','users.email','users.username','users.location_id','users.manager_id','users.first_name','users.last_name','users.created_at','users.notes','users.company_id', 'users.deleted_at','users.activated'))
827  ->with('assets', 'accessories', 'consumables', 'licenses', 'manager', 'groups', 'userloc', 'company');
828  $users = Company::scopeCompanyables($users);
829 
830  switch ($status) {
831  case 'deleted':
832  $users = $users->withTrashed()->Deleted();
833  break;
834  }
835 
836  if (Input::has('search')) {
837  $users = $users->TextSearch(Input::get('search'));
838  }
839 
840  $order = Input::get('order') === 'asc' ? 'asc' : 'desc';
841 
842  switch (Input::get('sort')) {
843  case 'manager':
844  $users = $users->OrderManager($order);
845  break;
846  case 'location':
847  $users = $users->OrderLocation($order);
848  break;
849  default:
850  $allowed_columns =
851  [
852  'last_name','first_name','email','username','employee_num',
853  'assets','accessories', 'consumables','licenses','groups','activated'
854  ];
855 
856  $sort = in_array($sort, $allowed_columns) ? $sort : 'first_name';
857  $users = $users->orderBy($sort, $order);
858  break;
859  }
860 
861  $userCount = $users->count();
862  $users = $users->skip($offset)->take($limit)->get();
863  $rows = array();
864 
865  foreach ($users as $user) {
866  $group_names = '';
867  $inout = '';
868  $actions = '<nobr>';
869 
870  foreach ($user->groups as $group) {
871  $group_names .= '<a href="' . config('app.url') . '/admin/groups/' . $group->id . '/edit" class="label label-default">' . $group->name . '</a> ';
872  }
873 
874 
875  if (!is_null($user->deleted_at)) {
876 
877  $actions .= '<a href="' . route('restore/user', $user->id) . '" class="btn btn-warning btn-sm"><i class="fa fa-share icon-white"></i></a> ';
878  } else {
879 
880  if ($user->accountStatus() == 'suspended') {
881  $actions .= '<a href="' . route('unsuspend/user', $user->id) . '" class="btn btn-default btn-sm"><span class="fa fa-clock-o"></span></a> ';
882  }
883 
884  $actions .= '<a href="' . route('update/user', $user->id) . '" class="btn btn-warning btn-sm"><i class="fa fa-pencil icon-white"></i></a> ';
885 
886  if ((Auth::user()->id !== $user->id) && (!config('app.lock_passwords'))) {
887  $actions .= '<a data-html="false" class="btn delete-asset btn-danger btn-sm" data-toggle="modal" href="' . route('delete/user', $user->id) . '" data-content="Are you sure you wish to delete this user?" data-title="Delete ' . htmlspecialchars($user->first_name) . '?" onClick="return false;"><i class="fa fa-trash icon-white"></i></a> ';
888  } else {
889  $actions .= ' <span class="btn delete-asset btn-danger btn-sm disabled"><i class="fa fa-trash icon-white"></i></span>';
890  }
891  }
892  $actions .= '</nobr>';
893 
894  $rows[] = array(
895  'id' => $user->id,
896  'checkbox' =>'<div class="text-center hidden-xs hidden-sm"><input type="checkbox" name="edit_user['.e($user->id).']" class="one_required"></div>',
897  'name' => '<a title="'.e($user->fullName()).'" href="../admin/users/'.e($user->id).'/view">'.e($user->fullName()).'</a>',
898  'email' => ($user->email!='') ?
899  '<a href="mailto:'.e($user->email).'" class="hidden-md hidden-lg">'.e($user->email).'</a>'
900  .'<a href="mailto:'.e($user->email).'" class="hidden-xs hidden-sm"><i class="fa fa-envelope"></i></a>'
901  .'</span>' : '',
902  'username' => e($user->username),
903  'location' => ($user->userloc) ? e($user->userloc->name) : '',
904  'manager' => ($user->manager) ? '<a title="' . e($user->manager->fullName()) . '" href="users/' . e($user->manager->id) . '/view">' . e($user->manager->fullName()) . '</a>' : '',
905  'assets' => $user->assets->count(),
906  'employee_num' => e($user->employee_num),
907  'licenses' => $user->licenses->count(),
908  'accessories' => $user->accessories->count(),
909  'consumables' => $user->consumables->count(),
910  'groups' => $group_names,
911  'notes' => e($user->notes),
912  'activated' => ($user->activated=='1') ? '<i class="fa fa-check"></i>' : '<i class="fa fa-times"></i>',
913  'actions' => ($actions) ? $actions : '',
914  'companyName' => is_null($user->company) ? '' : e($user->company->name)
915  );
916  }
917 
918  $data = array('total'=>$userCount, 'rows'=>$rows);
919  return $data;
920  }
static scopeCompanyables($query, $column= 'company_id')
Definition: Company.php:130
App\Http\Controllers\UsersController::getDelete (   $id = null)

Delete a user.

Author
[A. Gianotto] [snipe.nosp@m.@sni.nosp@m.pe.ne.nosp@m.t]
Since
[v1.0]
Parameters
int$id
Returns
Redirect

Definition at line 329 of file UsersController.php.

330  {
331  try {
332  // Get user information
333  $user = User::find($id);
334 
335  // Check if we are not trying to delete ourselves
336  if ($user->id === Auth::user()->id) {
337  // Prepare the error message
338  $error = trans('admin/users/message.error.delete');
339 
340  // Redirect to the user management page
341  return Redirect::route('users')->with('error', $error);
342  }
343 
344 
345  // Do we have permission to delete this user?
346  if ((!Auth::user()->isSuperUser()) || (config('app.lock_passwords'))) {
347  // Redirect to the user management page
348  return Redirect::route('users')->with('error', 'Insufficient permissions!');
349  }
350 
351  if (count($user->assets) > 0) {
352 
353  // Redirect to the user management page
354  return Redirect::route('users')->with('error', 'This user still has ' . count($user->assets) . ' assets associated with them.');
355  }
356 
357  if (count($user->licenses) > 0) {
358 
359  // Redirect to the user management page
360  return Redirect::route('users')->with('error', 'This user still has ' . count($user->licenses) . ' licenses associated with them.');
361  }
362 
363  // Delete the user
364  $user->delete();
365 
366  // Prepare the success message
367  $success = trans('admin/users/message.success.delete');
368 
369  // Redirect to the user management page
370  return Redirect::route('users')->with('success', $success);
371  } catch (UserNotFoundException $e) {
372  // Prepare the error message
373  $error = trans('admin/users/message.user_not_found', compact('id'));
374 
375  // Redirect to the user management page
376  return Redirect::route('users')->with('error', $error);
377  }
378  }
App\Http\Controllers\UsersController::getDeleteFile (   $userId = null,
  $fileId = null 
)

Delete file.

Author
[A. Gianotto] [snipe.nosp@m.@sni.nosp@m.pe.ne.nosp@m.t]
Since
[v1.6]
Parameters
int$userId
int$fileId
Returns
Redirect

Definition at line 980 of file UsersController.php.

981  {
982  $user = User::find($userId);
983  $destinationPath = config('app.private_uploads').'/users';
984 
985  // the license is valid
986  if (isset($user->id)) {
987 
988  if (!Company::isCurrentUserHasAccess($user)) {
989  return Redirect::route('users')->with('error', trans('general.insufficient_permissions'));
990  } else {
991  $log = Actionlog::find($fileId);
992  $full_filename = $destinationPath . '/' . $log->filename;
993  if (file_exists($full_filename)) {
994  unlink($destinationPath . '/' . $log->filename);
995  }
996  $log->delete();
997  return Redirect::back()->with('success', trans('admin/users/message.deletefile.success'));
998  }
999  } else {
1000  // Prepare the error message
1001  $error = trans('admin/users/message.does_not_exist', compact('id'));
1002 
1003  // Redirect to the licence management page
1004  return Redirect::route('users')->with('error', $error);
1005  }
1006  }
static isCurrentUserHasAccess($companyable)
Definition: Company.php:96
App\Http\Controllers\UsersController::getEdit (   $id = null)

Returns a view that displays the edit user form.

Author
[A. Gianotto] [snipe.nosp@m.@sni.nosp@m.pe.ne.nosp@m.t]
Since
[v1.0]
Parameters
int$id
Returns
View

Definition at line 183 of file UsersController.php.

184  {
185  try {
186  // Get the user information
187  $user = User::find($id);
188 
189  if (!Company::isCurrentUserHasAccess($user)) {
190  return Redirect::route('users')->with('error', trans('general.insufficient_permissions'));
191  }
192 
193  // Get this user groups
194  //$userGroups = $user->groups()->lists('group_id', 'name');
195  $userGroups = null;
196 
197  // Get this user permissions
198  $userPermissions = null;
199  //$this->encodePermissions($userPermissions);
200 
201  // Get a list of all the available groups
202  //$groups = Sentry::getGroupProvider()->findAll();
203 
204  // Get all the available permissions
205  $permissions = config('permissions');
206  //$this->encodeAllPermissions($permissions);
207 
208  $location_list = Helper::locationsList();
209  $company_list = Helper::companyList();
210  $manager_list = array('' => 'Select a User') + DB::table('users')
211  ->select(DB::raw('concat(last_name,", ",first_name," (",email,")") as full_name, id'))
212  ->whereNull('deleted_at')
213  ->where('id', '!=', $id)
214  ->orderBy('last_name', 'asc')
215  ->orderBy('first_name', 'asc')
216  ->lists('full_name', 'id');
217  } catch (UserNotFoundException $e) {
218  // Prepare the error message
219  $error = trans('admin/users/message.user_not_found', compact('id'));
220 
221  // Redirect to the user management page
222  return Redirect::route('users')->with('error', $error);
223  }
224 
225  // Show the page
226  return View::make('users/edit', compact('user', 'groups', 'userGroups', 'permissions', 'userPermissions'))
227  ->with('location_list', $location_list)
228  ->with('company_list', $company_list)
229  ->with('manager_list', $manager_list);
230  }
static locationsList()
Definition: Helper.php:94
static companyList()
Definition: Helper.php:61
static isCurrentUserHasAccess($companyable)
Definition: Company.php:96
App\Http\Controllers\UsersController::getImport ( )

Return user import view.

Author
[A. Gianotto] [snipe.nosp@m.@sni.nosp@m.pe.ne.nosp@m.t]
Since
[v1.0]
Returns
View

Definition at line 674 of file UsersController.php.

675  {
676  // Get all the available groups
677  //$groups = Sentry::getGroupProvider()->findAll();
678  // Selected groups
679  $selectedGroups = Input::old('groups', array());
680  // Get all the available permissions
681  $permissions = config('permissions');
682  //$this->encodeAllPermissions($permissions);
683  // Selected permissions
684  $selectedPermissions = Input::old('permissions', array('superuser' => -1));
685  //$this->encodePermissions($selectedPermissions);
686  // Show the page
687  return View::make('users/import', compact('groups', 'selectedGroups', 'permissions', 'selectedPermissions'));
688  }
App\Http\Controllers\UsersController::getIndex ( )

Returns a view that invokes the ajax tables which actually contains the content for the users listing, which is generated in getDatatable().

Author
[A. Gianotto] [snipe.nosp@m.@sni.nosp@m.pe.ne.nosp@m.t]
See also
UsersController::getDatatable() method that generates the JSON response
Since
[v1.0]
Returns
View

Definition at line 51 of file UsersController.php.

52  {
53  return View::make('users/index');
54  }
App\Http\Controllers\UsersController::getLDAP ( )

Return view for LDAP import.

Author
Aladin Alaily
Since
[v1.8]
Returns
View

Definition at line 1047 of file UsersController.php.

1048  {
1049  // Get all the available groups
1050  //s$groups = Sentry::getGroupProvider()->findAll();
1051  // Selected groups
1052  $selectedGroups = Input::old('groups', array());
1053  // Get all the available permissions
1054  $permissions = config('permissions');
1055  //$this->encodeAllPermissions($permissions);
1056  // Selected permissions
1057  $selectedPermissions = Input::old('permissions', array('superuser' => -1));
1058  //$this->encodePermissions($selectedPermissions);
1059 
1060  $location_list = Helper::locationsList();
1061 
1062  // Show the page
1063  return View::make('users/ldap', compact('groups', 'selectedGroups', 'permissions', 'selectedPermissions'))
1064  ->with('location_list', $location_list);
1065 
1066  }
static locationsList()
Definition: Helper.php:94
App\Http\Controllers\UsersController::getRestore (   $id = null)

Restore a deleted user.

Author
[A. Gianotto] [snipe.nosp@m.@sni.nosp@m.pe.ne.nosp@m.t]
Since
[v1.0]
Parameters
int$id
Returns
Redirect

Definition at line 496 of file UsersController.php.

497  {
498  try {
499  // Get user information
500  //$user = Sentry::getUserProvider()->createModel()->withTrashed()->find($id);
501 
502  if (!Company::isCurrentUserHasAccess($user)) {
503  return Redirect::route('users')->with('error', trans('general.insufficient_permissions'));
504  } else {
505  // Restore the user
506  $user->restore();
507 
508  // Prepare the success message
509  $success = trans('admin/users/message.success.restored');
510 
511  // Redirect to the user management page
512  return Redirect::route('users')->with('success', $success);
513  }
514  } catch (UserNotFoundException $e) {
515  // Prepare the error message
516  $error = trans('admin/users/message.user_not_found', compact('id'));
517 
518  // Redirect to the user management page
519  return Redirect::route('users')->with('error', $error);
520  }
521  }
static isCurrentUserHasAccess($companyable)
Definition: Company.php:96
App\Http\Controllers\UsersController::getUnsuspend (   $id = null)

Unsuspend a user.

Author
[A. Gianotto] [snipe.nosp@m.@sni.nosp@m.pe.ne.nosp@m.t]
Since
[v1.0]
Parameters
int$id
Returns
Redirect

Definition at line 563 of file UsersController.php.

564  {
565  try {
566  // Get user information
567  //$user = User::find($id);
568 
569  // Check if we are not trying to unsuspend ourselves
570  if ($user->id === Auth::user()->id) {
571  // Prepare the error message
572  $error = trans('admin/users/message.error.unsuspend');
573 
574  // Redirect to the user management page
575  return Redirect::route('users')->with('error', $error);
576  }
577 
578  // Do we have permission to unsuspend this user?
579  if ($user->isSuperUser() and ! Auth::user()->isSuperUser()) {
580  // Redirect to the user management page
581  return Redirect::route('users')->with('error', 'Insufficient permissions!');
582  }
583 
584  // Prepare the success message
585  $success = trans('admin/users/message.success.unsuspend');
586 
587  // Redirect to the user management page
588  return Redirect::route('users')->with('success', $success);
589  } catch (UserNotFoundException $e) {
590  // Prepare the error message
591  $error = trans('admin/users/message.user_not_found', compact('id'));
592 
593  // Redirect to the user management page
594  return Redirect::route('users')->with('error', $error);
595  }
596  }
App\Http\Controllers\UsersController::getView (   $userId = null)

Return a view with user detail.

Author
[A. Gianotto] [snipe.nosp@m.@sni.nosp@m.pe.ne.nosp@m.t]
Since
[v1.0]
Parameters
int$userId
Returns
View

Definition at line 532 of file UsersController.php.

533  {
534 
535  $user = User::with('assets', 'assets.model', 'consumables', 'accessories', 'licenses', 'userloc')->withTrashed()->find($userId);
536 
537  $userlog = $user->userlog->load('assetlog', 'consumablelog', 'assetlog.model', 'licenselog', 'accessorylog', 'userlog', 'adminlog');
538 
539  if (isset($user->id)) {
540 
541  if (!Company::isCurrentUserHasAccess($user)) {
542  return Redirect::route('users')->with('error', trans('general.insufficient_permissions'));
543  } else {
544  return View::make('users/view', compact('user', 'userlog'));
545  }
546  } else {
547  // Prepare the error message
548  $error = trans('admin/users/message.user_not_found', compact('id'));
549 
550  // Redirect to the user management page
551  return Redirect::route('users')->with('error', $error);
552  }
553  }
static isCurrentUserHasAccess($companyable)
Definition: Company.php:96
App\Http\Controllers\UsersController::postBulkEdit ( )

Returns a view that confirms the user's a bulk delete will be applied to.

Author
[A. Gianotto] [snipe.nosp@m.@sni.nosp@m.pe.ne.nosp@m.t]
Since
[v1.7]
Returns
View

Definition at line 387 of file UsersController.php.

388  {
389 
390  if ((!Input::has('edit_user')) || (count(Input::has('edit_user')) == 0)) {
391  return Redirect::back()->with('error', 'No users selected');
392  } else {
393  $statuslabel_list = Helper::statusLabelList();
394  $user_raw_array = array_keys(Input::get('edit_user'));
395 
396  $users = User::whereIn('id', $user_raw_array)->with('groups');
397  $users = Company::scopeCompanyables($users)->get();
398 
399  return View::make('users/confirm-bulk-delete', compact('users', 'statuslabel_list'));
400  }
401  }
static statusLabelList()
Definition: Helper.php:87
static scopeCompanyables($query, $column= 'company_id')
Definition: Company.php:130
App\Http\Controllers\UsersController::postBulkSave ( )

Soft-delete bulk users.

Author
[A. Gianotto] [snipe.nosp@m.@sni.nosp@m.pe.ne.nosp@m.t]
Since
[v1.0]
Returns
Redirect

PhpUnreachableStatementInspection Known to be unreachable but kept following discussion: https://github.com/snipe/snipe-it/pull/1423

Definition at line 410 of file UsersController.php.

411  {
412 
413  if ((!Input::has('edit_user')) || (count(Input::has('edit_user')) == 0)) {
414  return Redirect::back()->with('error', 'No users selected');
415  } elseif ((!Input::has('status_id')) || (count(Input::has('status_id')) == 0)) {
416  return Redirect::route('users')->with('error', 'No status selected');
417  } else {
418 
419  $user_raw_array = Input::get('edit_user');
420  $asset_array = array();
421 
422  if (($key = array_search(Auth::user()->id, $user_raw_array)) !== false) {
423  unset($user_raw_array[$key]);
424  }
425 
426  if (!Auth::user()->isSuperUser()) {
427  return Redirect::route('users')->with('error', trans('admin/users/message.insufficient_permissions'));
428  }
429 
430  if (!config('app.lock_passwords')) {
431 
432  $assets = Asset::whereIn('assigned_to', $user_raw_array)->get();
433  $accessories = DB::table('accessories_users')->whereIn('assigned_to', $user_raw_array)->get();
434 
435  $users = User::whereIn('id', $user_raw_array);
436  $users = Company::scopeCompanyables($users)->delete();
437 
438  foreach ($assets as $asset) {
439 
440  $asset_array[] = $asset->id;
441 
442  // Update the asset log
443  $logaction = new Actionlog();
444  $logaction->asset_id = $asset->id;
445  $logaction->checkedout_to = $asset->assigned_to;
446  $logaction->asset_type = 'hardware';
447  $logaction->user_id = Auth::user()->id;
448  $logaction->note = 'Bulk checkin';
449  $log = $logaction->logaction('checkin from');
450 
451  $update_assets = Asset::whereIn('id', $asset_array)->update(
452  array(
453  'status_id' => e(Input::get('status_id')),
454  'assigned_to' => null,
455  )
456  );
457  }
458 
459  foreach ($accessories as $accessory) {
460  $accessory_array[] = $accessory->id;
461  // Update the asset log
462  $logaction = new Actionlog();
463  $logaction->accessory_id = $accessory->id;
464  $logaction->checkedout_to = $accessory->assigned_to;
465  $logaction->asset_type = 'accessory';
466  $logaction->user_id = Auth::user()->id;
467  $logaction->note = 'Bulk checkin';
468  $log = $logaction->logaction('checkin from');
469 
470  $update_accessories = DB::table('accessories_users')->whereIn('id', $accessory_array)->update(
471  array(
472  'assigned_to' => null,
473  )
474  );
475  }
476 
477 
478  return Redirect::route('users')->with('success', 'Your selected users have been deleted and their assets have been updated.');
479  } else {
480  return Redirect::route('users')->with('error', 'Bulk delete is not enabled in this installation');
481  }
482 
484  return Redirect::route('users')->with('error', 'An error has occurred');
485  }
486  }
static scopeCompanyables($query, $column= 'company_id')
Definition: Company.php:130
App\Http\Controllers\UsersController::postCreate ( SetupUserRequest  $request)

Validate and store the new user data, or return an error.

Author
[A. Gianotto] [snipe.nosp@m.@sni.nosp@m.pe.ne.nosp@m.t]
Since
[v1.0]
Returns
Redirect

Definition at line 99 of file UsersController.php.

100  {
101 
102  $user = new User;
103  $user->first_name = $data['first_name']= e(Input::get('first_name'));
104  $user->last_name = e(Input::get('last_name'));
105  $user->email = $data['email'] = e(Input::get('email'));
106  $user->activated = 1;
107  $user->locale = e(Input::get('locale'));
108  $user->username = $data['username'] = e(Input::get('username'));
109  $user->password = bcrypt(Input::get('password'));
110  $data['password'] = Input::get('password');
111 
112  if ($user->save()) {
113  if ((Input::get('email_user') == 1) && (Input::has('email'))) {
114  // Send the credentials through email
115  $data = array();
116  $data['email'] = e(Input::get('email'));
117  $data['username'] = e(Input::get('username'));
118  $data['first_name'] = e(Input::get('first_name'));
119  $data['password'] = e(Input::get('password'));
120 
121  Mail::send('emails.send-login', $data, function ($m) use ($user) {
122  $m->to($user->email, $user->first_name . ' ' . $user->last_name);
123  $m->subject('Welcome ' . $user->first_name);
124  });
125  }
126  return redirect::route('users')->with('success', trans('admin/users/message.success.create'));
127  } else {
128  Redirect::back()->withInput()->withInput()->withErrors($user->getErrors())->withErrors($settings->getErrors());
129  }
130 
131  return Redirect::route('create/user')->withInput()->with('error', $error);
132  }
App\Http\Controllers\UsersController::postEdit (   $id = null)

Validate and save edited user data from edit form.

Author
[A. Gianotto] [snipe.nosp@m.@sni.nosp@m.pe.ne.nosp@m.t]
Since
[v1.0]
Parameters
int$id
Returns
Redirect

Definition at line 240 of file UsersController.php.

241  {
242  // We need to reverse the UI specific logic for our
243  // permissions here before we update the user.
244  $permissions = Input::get('permissions', array());
245  //$this->decodePermissions($permissions);
246  app('request')->request->set('permissions', $permissions);
247 
248  // Only update the email address if locking is set to false
249  if (config('app.lock_passwords')) {
250  return Redirect::route('users')->with('error', 'Denied! You cannot update user information on the demo.');
251  }
252 
253  try {
254  // Get the user information
255  $user = User::find($id);
256 
257  if (!Company::isCurrentUserHasAccess($user)) {
258  return Redirect::route('users')->with('error', trans('general.insufficient_permissions'));
259  }
260  } catch (UserNotFoundException $e) {
261  // Prepare the error message
262  $error = trans('admin/users/message.user_not_found', compact('id'));
263 
264  // Redirect to the user management page
265  return Redirect::route('users')->with('error', $error);
266  }
267 
268 
269  // Update the user
270  $user->first_name = e(Input::get('first_name'));
271  $user->last_name = e(Input::get('last_name'));
272  $user->locale = e(Input::get('locale'));
273  $user->username = e(Input::get('username'));
274  $user->email = e(Input::get('email'));
275  $user->employee_num = e(Input::get('employee_num'));
276  $user->activated = e(Input::get('activated', $user->activated));
277  $user->jobtitle = e(Input::get('jobtitle'));
278  $user->phone = e(Input::get('phone'));
279  $user->location_id = e(Input::get('location_id'));
280  $user->company_id = e(Company::getIdForUser(Input::get('company_id')));
281  $user->manager_id = e(Input::get('manager_id'));
282  $user->notes = e(Input::get('notes'));
283 
284  if ($user->manager_id == "") {
285  $user->manager_id = null;
286  }
287 
288  if ($user->location_id == "") {
289  $user->location_id = null;
290  }
291 
292 
293  // Do we want to update the user password?
294  if ((Input::has('password')) && (!config('app.lock_passwords'))) {
295  $user->password = bcrypt(Input::get('password'));
296  }
297 
298  // Do we want to update the user email?
299  if (!config('app.lock_passwords')) {
300  $user->email = Input::get('email');
301  }
302 
303 
304  if (!config('app.lock_passwords')) {
305 
306  }
307 
308  // Was the user updated?
309  if ($user->save()) {
310  // Prepare the success message
311  $success = trans('admin/users/message.success.update');
312 
313  // Redirect to the user page
314  return Redirect::route('users')->with('success', $success);
315  }
316 
317  return Redirect::back()->withInput()->withErrors($user->getErrors());
318 
319  }
static getIdForUser($unescaped_input)
Definition: Company.php:121
static isCurrentUserHasAccess($companyable)
Definition: Company.php:96
App\Http\Controllers\UsersController::postImport ( )

Handle user import file.

Author
[A. Gianotto] [snipe.nosp@m.@sni.nosp@m.pe.ne.nosp@m.t]
Since
[v1.0]
Returns
Redirect

Definition at line 697 of file UsersController.php.

698  {
699 
700  if (!ini_get("auto_detect_line_endings")) {
701  ini_set("auto_detect_line_endings", '1');
702  }
703 
704  $csv = Reader::createFromPath(Input::file('user_import_csv'));
705  $csv->setNewline("\r\n");
706 
707  if (Input::get('has_headers') == 1) {
708  $csv->setOffset(1);
709  }
710 
711  $duplicates = '';
712 
713  $nbInsert = $csv->each(function ($row) use ($duplicates) {
714 
715  if (array_key_exists(2, $row)) {
716 
717  if (Input::get('activate') == 1) {
718  $activated = '1';
719  } else {
720  $activated = '0';
721  }
722 
723  $pass = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 15);
724 
725  // Location
726  if (array_key_exists('4', $row)) {
727  $user_location_id = trim($row[4]);
728  if ($user_location_id=='') {
729  $user_location_id = null;
730  }
731  }
732 
733 
734 
735  try {
736  // Check if this email already exists in the system
737  $user = DB::table('users')->where('username', $row[2])->first();
738  if ($user) {
739  $duplicates .= $row[2] . ', ';
740  } else {
741 
742  $newuser = array(
743  'first_name' => trim(e($row[0])),
744  'last_name' => trim(e($row[1])),
745  'username' => trim(e($row[2])),
746  'email' => trim(e($row[3])),
747  'password' => $pass,
748  'activated' => $activated,
749  'location_id' => trim(e($user_location_id)),
750  'phone' => trim(e($row[5])),
751  'jobtitle' => trim(e($row[6])),
752  'employee_num' => trim(e($row[7])),
753  //'company_id' => Company::getIdForUser($row[8]),
754  'permissions' => '{"user":1}',
755  'notes' => 'Imported user'
756  );
757 
758  DB::table('users')->insert($newuser);
759 
760  $updateuser = User::find($row[2]);
761 
762  // Update the user details
763  $updateuser->password = $pass;
764 
765  // Update the user
766  $updateuser->save();
767 
768 
769  if (((Input::get('email_user') == 1) && !config('app.lock_passwords'))) {
770  // Send the credentials through email
771  if ($row[3] != '') {
772  $data = array();
773  $data['username'] = trim(e($row[2]));
774  $data['first_name'] = trim(e($row[0]));
775  $data['password'] = $pass;
776 
777  if ($newuser['email']) {
778  Mail::send('emails.send-login', $data, function ($m) use ($newuser) {
779  $m->to($newuser['email'], $newuser['first_name'] . ' ' . $newuser['last_name']);
780  $m->subject('Welcome ' . $newuser['first_name']);
781  });
782  }
783  }
784  }
785  }
786  } catch (Exception $e) {
787  echo 'Caught exception: ', $e->getMessage(), "\n";
788  }
789  return true;
790  }
791  });
792 
793 
794  return Redirect::route('users')->with('duplicates', $duplicates)->with('success', 'Success');
795  }
App\Http\Controllers\UsersController::postLDAP ( )

LDAP form processing.

Author
Aladin Alaily
Since
[v1.8]
Returns
Redirect

Definition at line 1095 of file UsersController.php.

1096  {
1097 
1098  $location_id = e(Input::get('location_id'));
1099 
1100  $ldap_version = Setting::getSettings()->ldap_version;
1101  $url = Setting::getSettings()->ldap_server;
1102  $username = Setting::getSettings()->ldap_uname;
1103  $password = Crypt::decrypt(Setting::getSettings()->ldap_pword);
1104  $base_dn = Setting::getSettings()->ldap_basedn;
1105  $filter = Setting::getSettings()->ldap_filter;
1106 
1107  $ldap_result_username = Setting::getSettings()->ldap_username_field;
1108  $ldap_result_last_name = Setting::getSettings()->ldap_lname_field;
1109  $ldap_result_first_name = Setting::getSettings()->ldap_fname_field;
1110 
1111  $ldap_result_active_flag = Setting::getSettings()->ldap_active_flag_field;
1112  $ldap_result_emp_num = Setting::getSettings()->ldap_emp_num;
1113  $ldap_result_email = Setting::getSettings()->ldap_email;
1114  $ldap_server_cert_ignore = Setting::getSettings()->ldap_server_cert_ignore;
1115 
1116  // If we are ignoring the SSL cert we need to setup the environment variable
1117  // before we create the connection
1118  if ($ldap_server_cert_ignore) {
1119  putenv('LDAPTLS_REQCERT=never');
1120  }
1121 
1122  // Connect to LDAP server
1123  $ldapconn = @ldap_connect($url);
1124 
1125  // Needed for AD
1126  ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0);
1127 
1128  if (!$ldapconn) {
1129  return Redirect::route('users')->with('error', trans('admin/users/message.error.ldap_could_not_connect'));
1130  }
1131 
1132  // Set options
1133  $ldapopt = @ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, $ldap_version);
1134  if (!$ldapopt) {
1135  return Redirect::route('users')->with('error', trans('admin/users/message.error.ldap_could_not_connect'));
1136  }
1137 
1138  // Binding to ldap server
1139  $ldapbind = @ldap_bind($ldapconn, $username, $password);
1140 
1141  Log::error(ldap_errno($ldapconn));
1142  if (!$ldapbind) {
1143  return Redirect::route('users')->with('error', trans('admin/users/message.error.ldap_could_not_bind').ldap_error($ldapconn));
1144  }
1145 
1146  // Set up LDAP pagination for very large databases
1147  // @author Richard Hofman
1148  $page_size = 500;
1149  $cookie = '';
1150  $result_set = array();
1151  $global_count = 0;
1152 
1153  // Perform the search
1154  do {
1155  // Paginate (non-critical, if not supported by server)
1156  ldap_control_paged_result($ldapconn, $page_size, false, $cookie);
1157 
1158  $search_results = ldap_search($ldapconn, $base_dn, '('.$filter.')');
1159 
1160  if (!$search_results) {
1161  return Redirect::route('users')->with('error', trans('admin/users/message.error.ldap_could_not_search').ldap_error($ldapconn));
1162  }
1163 
1164  // Get results from page
1165  $results = ldap_get_entries($ldapconn, $search_results);
1166  if (!$results) {
1167  return Redirect::route('users')->with('error', trans('admin/users/message.error.ldap_could_not_get_entries').ldap_error($ldapconn));
1168  }
1169 
1170  // Add results to result set
1171  $global_count += $results['count'];
1172  $result_set = array_merge($result_set, $results);
1173 
1174  ldap_control_paged_result_response($ldapconn, $search_results, $cookie);
1175 
1176  } while ($cookie !== null && $cookie != '');
1177 
1178 
1179  // Clean up after search
1180  $result_set['count'] = $global_count;
1181  $results = $result_set;
1182  ldap_control_paged_result($ldapconn, 0);
1183 
1184  $summary = array();
1185 
1186  for ($i = 0; $i < $results["count"]; $i++) {
1187  if (empty($ldap_result_active_flag) || $results[$i][$ldap_result_active_flag][0] == "TRUE") {
1188 
1189  $item = array();
1190  $item["username"] = isset($results[$i][$ldap_result_username][0]) ? $results[$i][$ldap_result_username][0] : "";
1191  $item["employee_number"] = isset($results[$i][$ldap_result_emp_num][0]) ? $results[$i][$ldap_result_emp_num][0] : "";
1192  $item["lastname"] = isset($results[$i][$ldap_result_last_name][0]) ? $results[$i][$ldap_result_last_name][0] : "";
1193  $item["firstname"] = isset($results[$i][$ldap_result_first_name][0]) ? $results[$i][$ldap_result_first_name][0] : "";
1194  $item["email"] = isset($results[$i][$ldap_result_email][0]) ? $results[$i][$ldap_result_email][0] : "" ;
1195 
1196  // User exists
1197  $item["createorupdate"] = 'updated';
1198  if (!$user = User::where('username', $item["username"])->first()) {
1199  $user = new User;
1200  $item["createorupdate"] = 'created';
1201  }
1202 
1203 
1204  // Create the user if they don't exist.
1205  $pass = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 20);
1206 
1207  $user->first_name = e($item["firstname"]);
1208  $user->last_name = e($item["lastname"]);
1209  $user->username = e($item["username"]);
1210  $user->email = e($item["email"]);
1211  $user->employee_num = e($item["employee_number"]);
1212  $user->password = bcrypt($pass);
1213  $user->activated = 1;
1214  $user->location_id = e($location_id);
1215  $user->permissions = '{"user":1}';
1216  $user->notes = 'Imported from LDAP';
1217  $user->ldap_import = 1;
1218 
1219  $errors = '';
1220 
1221  if ($user->save()) {
1222  $item["note"] = $item["createorupdate"];
1223  $item["status"]='success';
1224  } else {
1225  //$errors_array = array($user->getErrors());
1226  foreach ($user->getErrors()->getMessages() as $key => $err) {
1227  //echo $user->getErrors();
1228  $errors .='<li>'.$err[0];
1229  }
1230  $item["note"] = $errors;
1231  $item["status"]='error';
1232  }
1233 
1234  array_push($summary, $item);
1235  }
1236 
1237  }
1238 
1239 
1240 
1241  return Redirect::route('ldap/user')->with('success', "OK")->with('summary', $summary);
1242  }
static getSettings()
Definition: Setting.php:33
App\Http\Controllers\UsersController::postUpload ( AssetFileRequest  $request,
  $userId = null 
)

Return JSON response with a list of user details for the getIndex() view.

Author
[A. Gianotto] [snipe.nosp@m.@sni.nosp@m.pe.ne.nosp@m.t]
Since
[v1.6]
Parameters
int$userId
Returns
string JSON

Definition at line 930 of file UsersController.php.

931  {
932 
933 
934  $user = User::find($userId);
935  $destinationPath = config('app.private_uploads') . '/users';
936 
937  if (isset($user->id)) {
938 
939  if (!Company::isCurrentUserHasAccess($user)) {
940  return Redirect::route('users')->with('error', trans('general.insufficient_permissions'));
941  }
942 
943  foreach (Input::file('file') as $file) {
944 
945  $extension = $file->getClientOriginalExtension();
946  $filename = 'user-' . $user->id . '-' . str_random(8);
947  $filename .= '-' . str_slug($file->getClientOriginalName()) . '.' . $extension;
948  $upload_success = $file->move($destinationPath, $filename);
949 
950  //Log the deletion of seats to the log
951  $logaction = new Actionlog();
952  $logaction->asset_id = $user->id;
953  $logaction->asset_type = 'user';
954  $logaction->user_id = Auth::user()->id;
955  $logaction->note = e(Input::get('notes'));
956  $logaction->checkedout_to = null;
957  $logaction->created_at = date("Y-m-d h:i:s");
958  $logaction->filename = $filename;
959  $logaction->action_type = 'uploaded';
960  $logaction->save();
961 
962  }
963  return JsonResponse::create($logaction);
964 
965  } else {
966  return JsonResponse::create(["error" => "Failed validation: ".print_r($logaction->getErrors(), true)], 500);
967  }
968  }
static isCurrentUserHasAccess($companyable)
Definition: Company.php:96
App\Http\Controllers\UsersController::store ( )

JSON handler for creating a user through a modal.

Author
[A. Gianotto] [snipe.nosp@m.@sni.nosp@m.pe.ne.nosp@m.t]
Since
[v1.8]
Returns
string JSON

Definition at line 141 of file UsersController.php.

142  {
143  $user = new User;
144 
145  $inputs = Input::except('csrf_token', 'password_confirm', 'groups', 'email_user');
146  $inputs['activated'] = true;
147 
148  // Was the user created?
149  if ($user->save()) {
150 
151  if (Input::get('email_user') == 1) {
152  // Send the credentials through email
153  $data = array();
154  $data['email'] = e(Input::get('email'));
155  $data['first_name'] = e(Input::get('first_name'));
156  $data['password'] = e(Input::get('password'));
157 
158  Mail::send('emails.send-login', $data, function ($m) use ($user) {
159  $m->to($user->email, $user->first_name . ' ' . $user->last_name);
160  $m->subject('Welcome ' . $user->first_name);
161  });
162  }
163 
164  return JsonResponse::create($user);
165 
166  } else {
167  return JsonResponse::create(["error" => "Failed validation: " . print_r($user->getErrors(), true)], 500);
168  }
169  return JsonResponse::create(["error" => "Couldn't save User"], 500);
170 
171 
172 
173  }

Member Data Documentation

App\Http\Controllers\UsersController::$ldapValidationRules
protected
Initial value:
= array(
'firstname' => 'required|string|min:2',
'lastname' => 'required|string|min:2',
'employee_number' => 'string',
'username' => 'required|min:2|unique:users,username',
'email' => 'email|unique:users,email',
)

Definition at line 1080 of file UsersController.php.


The documentation for this class was generated from the following file: