Problem with validating blocked users Laravel

1

I have a site which I have a function to validate if the email entered belongs or not to a user in blacklist (Blocked User). Which for the case that is fulfilled should not allow sending the form.

What validation should do is, validate if the email entered is the same as an email from a user that is on the blacklist. To get that email the validation will ask first if the user id of my TABLE Blacklist , is equal to id of my user table and finally ask if that user's email is the same as the email received from the form.

As for example, the following query shows me the users that I have in the blacklist, that is, blocked.

In other words, the validation must follow the same order of the query in a similar way, plus the email received from the form.

This is the form.

<form name="form" action="{{route('miruta')}} method="POST">

  @foreach($user as $user)
    @foreach($lista_negra as $lista)
      @if($lista->user_id == $user->id)
         <input type="hidden" id="user_email" value="{{$user->email}}">
         <input type="hidden" id="user_name" value="{{$user->name}}">
      @endif
    @endforeach
  @endforeach

  <table>
    <tr>
      <td>Responsable</td>
      <td>
        <input type="email" name="responsable" id="responsable" required="required">

        <br><br>
        <textarea maxlength="500" id="comentario" name="comentario"></textarea>
      </td>
    </tr>

    <tr>
      <td>
       <!--CONTENIDO-->
      </td>
    </tr>
  </table>

  <input type="submit" name="guardar" id="btn-guardar" value="CONFIRMAR"/>
</form>

I have been testing to perform the validation on my controller, as follows:

public function guardarReserva(Request $request){

  $monto = $request->codigo;

  if($request->isMethod('POST')){

    $id_complejo=$request->input('complejo');
    $horario=$request->input('horario');
    $indumentarias=$request->input('indumentaria');
    $responsable=$request->input('responsable');
    $fono_responsable=$request->input('fono_responsable');
    $comentario = $request->input('comentario');

    $id_descuento=0;
    $fecha_reserva=date('Y-m-d H:i:s');


    $listaNegra = DB::select('select users.email from lista_negra join users where lista_negra.user_id like users.id');


    //CONDICION - ¿COMO PODRIA COMPARAR EL ARRAY $listaNegra?
    if ($listaNegra == $responsable) {

        Session::flash('error', 'El usuario'.' '.$user_name.' '.'no se puede utilizar como responsable debido a que se encuentra en Lista Negra');
        return Redirect()->back();
    } 

    //SEGUNDA FORMA
    $user_blocked = $request->user_email;

    if($user_blocked == $responsable){
      Session::flash('error', 'Este usuario no se puede utilizar porque se encuentra bloqueado');
    return redirect()->back();
    }

    //AL HACER UN dd($user_blocked == $responsable) OBTENGO true COMO RESULTADO


    //VISTA FINAL QUE ES RETORNADA
    return view('reservar-cancha-exito',['id'=>$rid,'hora_inicio'=>$hora_inicio,'complejo'=>$complejo,'hora_fin'=>$hora_fin,'monto'=>$monto,'cancha'=>$cancha,'descuento'=>$monto_descuento,'fecha_reserva' => $fecha_reserva,'indumentarias' => $indumentariasArr]);
  }

}

Which when doing a dd($listaNegra, $responsable) I get the following:

  

IMPORTANT: The photo is edited to explain which email is received by the variable $request

Finally the validation does not work in any of the 2 ways. And I do not receive any error, for the first case in exchange for the second I receive an error that says NO MESSAGE .

What could I have done wrong? As extra information I leave the main models that I occupy.

The model for the blacklist.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ListaNegra extends Model{

  protected $table = "lista_negra";
  protected $fillable = ['name'];
}
?>

And the model of the user.

<?php

  namespace App;

  use Illuminate\Auth\Authenticatable;
  use Illuminate\Database\Eloquent\Model;
  use Illuminate\Auth\Passwords\CanResetPassword;
  use Illuminate\Foundation\Auth\Access\Authorizable;
  use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
  use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
  use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

  class User extends Model implements AuthenticatableContract, AuthorizableContract,CanResetPasswordContract{

    use Authenticatable, Authorizable, CanResetPassword;

    protected $table = 'users';

    protected $fillable = ['id','name', 'email', 'password','LastName','sLastName','telephone','role_id', 'complejo_id'];

    protected $hidden = ['password', 'remember_token'];

    public function setPasswordAttribute($valor){
        if (!empty($valor)){
            $this->attributes['password'] = \Hash::make($valor);
        }
    }
  }
?>

I have also tried the view in the following way, without getting the expected result, which is to show an alert to the user preventing the form from being sent.

<script type="text/javascript">

  var name_user = document.getElementById('user_name').val();

  $(document).ready(function(){
    $('#btn-guardar').click(function(){
      $("#user_email").each(function(e){

        var user_mail = $('#user_email').val();
        var email_usuario= document.getElementById('responsable').value;

        if(email_usuario == user_mail){
           e.prevenDefault();
           $('#responsable').focus();

           $.alert({
            title: ''+'<nav style="background: #478573; color: white; width: 20cm;height: 10mm; margin-top: -5mm; margin-left: -5mm; padding-top:2.5mm; padding-bottom: 6mm;">&nbsp;&nbsp;<i class="fa fa-times"></i>&nbsp;&nbsp;¡Error!</nav> ',
            content: ''+'<label style="color: black; font-weight: 500;">El usuario (@'+name_user+') no se puede utilizar ya que se encuentra bloqueado.</label>',
          });
          return false;
        }
      });
    });
  });
</script>
    
asked by M4uriXD 20.12.2018 в 17:45
source

3 answers

0

I answer my own question, I have managed to solve the dilemma. What I did was to perform validation on the controller before saving the received data.

  • First I put some fields with some values, which will be validated later in the controller.
<!--PUEDEN ESTAR COMO HIDDEN LOS INPUT COMO TAMBIEN DARLE COMO ESTILO UN DISPLAY: NONE-->
@foreach($user as $user)
    @foreach($listaNegra as $lista)
        @if($lista->user_id == $user->id)
            <!-- USUARIOS EN LISTA NEGRA -->
            <input type="text" id="user_email" readonly="readonly" name="user_email" value="{{$user->email}}" style="display: none;">
            <input type="hidden" value="{{$user->id}}" id="user_id_input" name="user_id_input">
            <input type="hidden" value="{{$lista->user_id}}" id="listaNegra" name="listaNegra">
            <input type="hidden" value="{{$user->name}}" id="user_name">
        @endif
    @endforeach
@endforeach

The fields are the email of the user, the id of the user, and the id of the user in the blacklist, respectively.

Then in the controller rescue the data to be validated and apply the validation that returns to my main page in case an error message is fulfilled.

public function guardarReserva(Request $request){

    $monto = $request->codigo;

    if($request->isMethod('POST')){

        $id_complejo=$request->input('complejo');
        $horario=$request->input('horario');
        $indumentarias=$request->input('indumentaria');

        $responsable = $request->input('responsable');

        $fono_responsable=$request->input('fono_responsable');
        $comentario = $request->input('comentario');

        $id_descuento=0;

        $fecha_reserva=date('Y-m-d H:i:s');

        //VALIDACION
        $lista = $request->listaNegra;
        $usuario_b = $request->user_id_input;
        $user_email = $request->user_email; 


        if ($lista == $usuario_b && $user_email == $responsable) {
            Session::flash('error', 'Este usuario se encuentra bloqueado por lo que no se puede utilizar como responsable');

            return Redirect()->route('reservar'); //PAGINA INICIO RESERVAS
       }

    }  
}
    
answered by 02.01.2019 / 18:03
source
0

Having several foreach in the view is too much load for the server, let's do it via javascript :

1.- Remove your foreach from the view.

2.- We already have the variable $lista_negra , assuming it is an array we do this in Javascript :

function ValidaEmail(e){
...
    var listaNegra  = {{ $listaNegra }};
    var responsable = document.getElementById('responsable').value;
    var a           = listaNegra.indexOf(responsable);
    if ( a != -1 ) //significa que sí encontró el correo en la lista negra
    {
       //Muestras la alerta de que el correo no se puede usar
       $.alert({
          title: ''+'<nav style="background: #478573; color: white; width: 20cm;height: 10mm; margin-top: -5mm; margin-left: -5mm; padding-top:2.5mm; padding-bottom: 6mm;">&nbsp;&nbsp;<i class="fa fa-times"></i>&nbsp;&nbsp;¡Error!</nav> ',
          content: ''+'<label style="color: black; font-weight: 500;">No se puede usar a este usuario como responsable ya que se encuentra bloqueado.</label>',
        });
        e.prevenDefault();
        $('#responsable').focus();
        return:
    }
    // **Aqui pones el código que deberá ejecutarse si el correo NO está en la lista negra**
...
}

Note : If indexOf does not find the value within the array it returns -1 .

Note2 : The indexOf function is caseSensitive .

Note 3 : indexOf was added in JavaScript 1.6 and does not work in IE 8 and previous versions.

Note 4 : {{$listaNegra }} will only work if Script is inside the view Blade and not in an external file.

    
answered by 20.12.2018 в 21:05
-1

Try this script since the php part of the blucle has not explained it very well

function ValidaEmail(e){

    // OBTENEMOS EL INPUT PRINCIPAL A VALIDAR
    var responsable = $("input#responsable").val();


    // OBTENEMOS EL OTRO INPUT A VALIDAR

    $("input[name='user_email']").each(function(i,item){
          var u_email = $(item).val();

    //  VALIDAMOS SI EL VALOR DEL PRIMER INPUT ES IGUAL A 
    //  ALGUNO DEL 2DO INPUT
          if(responsable == u_email){
             e.prevenDefault();
             $('#responsable').focus();

             $.alert({
          title: ''+'<nav style="background: #478573; color: white; width: 20cm;height: 10mm; margin-top: -5mm; margin-left: -5mm; padding-top:2.5mm; padding-bottom: 6mm;">&nbsp;&nbsp;<i class="fa fa-times"></i>&nbsp;&nbsp;¡Error!</nav> ',
          content: ''+'<label style="color: black; font-weight: 500;">No se puede usar a este usuario como responsable ya que se encuentra bloqueado.</label>',
      })
          }
     });

  }
    
answered by 20.12.2018 в 18:10