When creating a new user, the user being used is logged in and the new user is logged in automatically

Asked

Viewed 61 times

-2

I’m having a problem with the method of creating a new user in Windows, because I changed the method of registering users on my system so only administrators users can create new users, but every time I create a new user, my current user is logged and the site logs into the new user.

my file create_users.blade.php

 @extends('layouts.menu')


@section('content')

<?php
$status = (bool) rand(0, 1) ? "checked" : null;
?>

<br><br>
<div class="row">
    <div class="col-2"></div>
    <div class="col-10 ">
        <div class="pull">
            <h2>Criar Novo Usuário:</h2>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-2"></div>
    <form method="POST" action="{{ route('register') }}" class="col-10">
        @csrf
        <div class="row">

            <div class="col-6">
                <div class="form-group">
                    <strong>Nome:</strong>
                    <div class="col-6">
                        <input id="name" type="text" class="form-control @error('name') is-invalid @enderror"
                            name="name" required autocomplete="name" autofocus>
                        @error('name')
                        <span class="invalid-feedback" role="alert">
                            <strong>{{ $message }}</strong>
                        </span>
                        @enderror
                    </div>
                </div>
            </div>

            <div class="col-6">
                <div class="form-group">
                    <strong>Email:</strong>
                    <div class="col-6">
                        <input id="email" type="email" class="form-control @error('email') is-invalid @enderror"
                            name="email" required autocomplete="email">
                    </div>
                </div>
            </div>

            <div class="col-6">
                <div class="form-group">
                    <strong>Senha:</strong>
                    <div class="col-6">
                        <input id="password" type="password"
                            class="form-control @error('password') is-invalid @enderror" name="password" required
                            autocomplete="new-password">
                    </div>
                </div>
            </div>

            <div class="col-6">
                <div class="form-group">
                    <strong>CPF:</strong>
                    <div class="col-6">
                        <input id="CPF" type="text" class="form-control @error('CPF') is-invalid @enderror" name="CPF"
                            required autocomplete="new-CPF" minlength="11" maxlength='11'>
                        @error('CPF')
                        <span class="invalid-feedback" role="alert">
                            <strong>{{ $message }}</strong>
                        </span>
                        @enderror
                    </div>
                </div>
            </div>

            <div class="col-6">
                <div class="form-group">
                    <strong>Setor:</strong>
                    <div class="col-6">
                        <select class="browser-default custom-select" name="setor" id="setores">
                            <option selected>Selecione o Setor</option>
                            @foreach ($setor as $s)
                            <option value="{{ $s->id }}">{{ $s->name }}</option>
                            @endforeach
                        </select>
                    </div>
                </div>
            </div>

            <div class="col-6">
                <div class="form-group">
                    <strong>Cargo:</strong>
                    <div class="col-6">
                        <select class="browser-default custom-select" name="cargo" id="cargos">
                            <option selected>Selecione o Cargo</option>
                        </select>
                    </div>
                </div>
            </div>

            <div class="col-6">
                <div class="form-group">
                    <strong>Função (Para Permissões):</strong>
                    <div class="col-6">
                        <select class="browser-default custom-select" name="roles" id="roles">
                            <option selected>Selecione a Função</option>
                            @foreach ($role as $ro)
                            <option value="{{ $ro->id }}">{{ $ro->name }}</option>
                            @endforeach
                        </select>
                    </div>
                </div>
            </div>

        <div class="col-6">
            <div class="form-group">
                <div class="custom-control custom-switch">
                    <input type="checkbox" class="custom-control-input" name="status" value="1" id="switch1"
                    <?php echo $status; ?> >
                    <label class="custom-control-label" for="switch1">Ativo</label>
                </div>
            </div>
        </div>

            <div class="col-1 text-center" style="padding-top: 25px;">
                <button type="submit" class="btn btn-primary">Enviar</button>
            </div>

        </div>

    </form>
</div>

<script src="http://demo.itsolutionstuff.com/plugin/jquery.js"></script>
<script type="text/javascript">
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

$(document).ready(function() {
    $('#setores').on('change', function(e) {
        var setor_id = e.target.value;
        $.ajax({
            url: "{{ route('cargos') }}",
            type: "GET",
            data: {
                setor_id: setor_id
            },

            success: function(data) {
                $('#cargos').empty();
                $.each(data.cargos, function(index, cargos) {
                    $('#cargos').append('<option value="' + cargos.id +
                        '">' + cargos.name + '</option>');
                });
            }
        });
    });
});
</script>

@endsection


Man Registercontroller

   class RegisterController extends Controller
{
    use RegistersUsers;

protected $redirectTo = RouteServiceProvider::HOME;

public function index()
{

}

protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => ['required', 'string','min:5', 'max:25'],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password' => ['required', 'string', 'min:8', 'max:20'],
        'CPF' => ['required', 'unique:users','integer'],
        'setor' => ['required','integer'],
        'cargo' => ['required','integer'],
        'status' => ['boolean'],
    ]);
}
/**
 * Create a new user instance after a valid registration.
 *
 * @param  array  $data
 * @return \App\User
 */
protected function create(array $data)
{
    return User::create([
        'name' =>       $data['name'],
        'email' =>      $data['email'],
        'password' =>   Hash::make($data['password']),
        'CPF' =>        $data['CPF'],
        'setor_id' =>   $data['setor'],
        'cargo_id' =>   $data['cargo'],
        'status' =>     $data['status'],
    ]);
    return redirect()->route('usuarios/create')->with('message', 'Usuário criado com Sucesso!');
}

public function edit($id)
{
// $user = User::findOrFail($id);
// return view('users.edit',compact('user'));
}

}


EDIT I had put the wrong Controller.


Man Routeserviceprovider.php: (This file has not been changed.)

class RouteServiceProvider extends ServiceProvider
{
    /**
     * This namespace is applied to your controller routes.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $namespace = 'App\Http\Controllers';

/**
 * The path to the "home" route for your application.
 *
 * @var string
 */
public const HOME = 'home';

/**
 * Define your route model bindings, pattern filters, etc.
 *
 * @return void
 */
public function boot()
{
    //

    parent::boot();
}

/**
 * Define the routes for the application.
 *
 * @return void
 */
public function map()
{
    $this->mapApiRoutes();

    $this->mapWebRoutes();

    //
}

/**
 * Define the "web" routes for the application.
 *
 * These routes all receive session state, CSRF protection, etc.
 *
 * @return void
 */
protected function mapWebRoutes()
{
    Route::middleware('web')
        ->namespace($this->namespace)
        ->group(base_path('routes/web.php'));
}

/**
 * Define the "api" routes for the application.
 *
 * These routes are typically stateless.
 *
 * @return void
 */
protected function mapApiRoutes()
{
    Route::prefix('api')
        ->middleware('api')
        ->namespace($this->namespace)
        ->group(base_path('routes/api.php'));
}

}


and my Routes from web php.

Route::get('usuarios/create', 'User\UserController@index');
Route::get('/cargo', 'User\UserController@selectBoxAjax_users')->name('cargos');
Route::get('senha/update', 'User\UserSettingsController@edit');

My Model User

class User extends Authenticatable

{ use Notifiable, Hasroles;

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */

public function index($user_id){
   $user_id -> Auth::user()->id;
}

public $timestamps = false;

protected $table = 'users';

protected $fillable = [
    'name', 'password','CPF','setor_id','cargo_id','email',
];

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password',
];

/**
 * The attributes that should be cast to native types.
 *
 * @var array
 */
protected $casts = [
    'email_verified_at' => 'datetime',
];

}


Can anyone help me? I’ve searched a lot of places, I’ve looked at virtually all the documentation on the ship, and I can’t find anything on it. If anyone can help me I’d be very grateful.

3 answers

0


Well, I ran one more through mine Registercontroller and I ended up noticing a line that had gone unnoticed by me before.

use RegistersUsers;

When I opened this file, I saw that there was my problem

public function register(Request $request)
{
    $this->validator($request->all())->validate();

    event(new Registered($user = $this->create($request->all())));

    $this->guard()->login($user);

    if ($response = $this->registered($request, $user)) {
        return $response;
    }

    return $request->wantsJson()
                ? new Response('', 201)
                : redirect($this->redirectPath());
}

How I had used the default Controller created by php artisan ui vue --auth and had not paid attention to this file before, had not noticed the line $this->guard()->login($user); which is what caused the user to be logged in when creating. I thank those who tried to help me, the problem was really lack of attention.

0

Ideally you would post more about the User, as Middleware, own Model, among other things that interact with the User and that may be affecting.

For a palliative solution I suggest using the function login of Authat the end of store. This way, the logged-in user will be the user that you pass to function.

$user = User::where('id',$idUsuarioAtual)->first();
Auth::login($user);

$idUsuárioAtual can come as a parameter or something. Remembering that this is a palliative solution and is far from ideal. Edit the question by providing more information to make it easier to tell where the problem is!

  • I did another scan on my Controller again and found the cause of my "problem", I am posting an answer with what I did to solve, but thanks for the help.

0

This reply should be a comment, but I still have no points for this.

Could you share what you have inside the controller’s index method? Also what’s in the logic of assignCargo in your model.

Apart from these two points I see nothing that could be causing this behavior in your code.

  • 1

    my controller has no index function yet, but I figured out what was making the code react that way. I will post a reply with the resolution, but thanks for the help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.