AuthFilter.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace App\Filters;
  3. use App\Models\UserModel;
  4. use CodeIgniter\Filters\FilterInterface;
  5. use CodeIgniter\HTTP\RequestInterface;
  6. use CodeIgniter\HTTP\ResponseInterface;
  7. // Valida si un usuario está autenticado.
  8. class AuthFilter implements FilterInterface
  9. {
  10. /**
  11. * Do whatever processing this filter needs to do.
  12. * By default it should not return anything during
  13. * normal execution. However, when an abnormal state
  14. * is found, it should return an instance of
  15. * CodeIgniter\HTTP\Response. If it does, script
  16. * execution will end and that Response will be
  17. * sent back to the client, allowing for error pages,
  18. * redirects, etc.
  19. *
  20. * @param array|null $arguments
  21. *
  22. * @return RequestInterface|ResponseInterface|string|void
  23. */
  24. public function before(RequestInterface $request, $arguments = null)
  25. {
  26. // Obtiene la cookie del usuario autenticado.
  27. $cookie = request()->getCookie('userAuth');
  28. if (empty($cookie)) {
  29. return redirect()->route('auth.loginView')
  30. ->with('warning', 'Ingresa tus credenciales de acceso');
  31. }
  32. $userModel = model(UserModel::class);
  33. // Consulta la información del usuario autenticado.
  34. $userAuth = $userModel->select('usuarios.idUsuario, usuarios.nombre, roles.nombre AS rol')
  35. ->role()
  36. ->where('usuarios.estatus', 1)
  37. ->find($cookie);
  38. // Roles permitidos en la aplicación.
  39. $allowedRoles = ['Administrador', 'Almacenista'];
  40. if (empty($userAuth) || ! in_array($userAuth['rol'], $allowedRoles, true)) {
  41. return redirect()->route('auth.loginView')
  42. ->with('error', 'Acceso denegado al sistema');
  43. }
  44. // Almacena la información del usuario durante la sesión.
  45. session()->set('userAuth', $userAuth);
  46. }
  47. /**
  48. * Allows After filters to inspect and modify the response
  49. * object as needed. This method does not allow any way
  50. * to stop execution of other after filters, short of
  51. * throwing an Exception or Error.
  52. *
  53. * @param array|null $arguments
  54. *
  55. * @return ResponseInterface|void
  56. */
  57. public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
  58. {
  59. }
  60. }