четверг, 14 сентября 2017 г.

Laravel. Блог. Запрет на вход для пользователя с нулевым статусом

Отобразим статус пользователя в таблице.


Откроем вид \resources\views\admin\user\show.blade.php
@extends('admin.layouts.app')

@section('headSection')
<link rel="stylesheet" href="{{ asset('admin/bower_components/datatables.net-bs/css/dataTables.bootstrap.min.css') }}" />
@endsection

@section('main-content')
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
@include('admin.layouts.pagehead')
</section>

<!-- Main content -->
<section class="content">

<!-- Default box -->
<div class="box">
<div class="box-header with-border">
<h3 class="box-title">Users</h3>
<a class="col-lg-offset-5 btn btn-success" href="{{ route('user.create') }}">Add New User</a>
@include('includes.messages')

<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse" data-toggle="tooltip"
title="Collapse">
<i class="fa fa-minus"></i></button>
<button type="button" class="btn btn-box-tool" data-widget="remove" data-toggle="tooltip" title="Remove">
<i class="fa fa-times"></i></button>
</div>
</div>
<div class="box-body">
<div class="box">
<div class="box-header">
<h3 class="box-title">Data Table With Full Features</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>S.No</th>
<th>User Name</th>
<th>Assigned Roles</th>
<th>Status</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
@foreach ($users as $user)
<tr>
<td>{{ $loop->index + 1 }}</td>
<td>{{ $user->name }}</td>
<td>
@foreach ($user->roles as $role)
{{ $role->name }} |
@endforeach
</td>
<td>{{ $user->status ? 'Active' : 'Not active' }}</td>
<td><a href="{{ route('user.edit', $user->id) }}"><span class="glyphicon glyphicon-edit"></span></a></td>
<td>
<form id="delete-form-{{ $user->id }}" method="post" action="{{ route('user.destroy', $user->id) }}" style="display:none">
{{ csrf_field() }}
{{ method_field('DELETE') }}
</form>
<a href="" onclick="if(confirm('Are you sure, you want to delete this?'))
{event.preventDefault();
document.getElementById('delete-form-{{ $user->id }}').submit();
}else{
event.preventDefault();
}"><span class="glyphicon glyphicon-trash"></span></a>
</td>
</tr>
@endforeach
</tbody>
<tfoot>
<tr>
<th>S.No</th>
<th>User Name</th>
<th>Assigned Roles</th>
<th>Status</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</tfoot>
</table>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
<!-- /.box-body -->
<div class="box-footer">
Footer
</div>
<!-- /.box-footer-->
</div>
<!-- /.box -->

</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
@endsection

@section('footerSection')
<script src="{{ asset('admin/bower_components/datatables.net/js/jquery.dataTables.min.js') }}"></script>
<script src="{{ asset('admin/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js') }}"></script>
<script>
$(function () {
$('#example1').DataTable()
})
</script>
@endsection

Идем в контроллер \app\Http\Controllers\Admin\UserController.php
public function update(Request $request, $id)
{
$this->validate($request, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255',
'phone' => 'required|numeric',
]);

$request->status ? : $request['status'] = 0;

$user = admin::where('id', $id)->update($request->except('_token','_method', 'role'));
admin::find($id)->roles()->sync($request->role);
return redirect(route('user.index'))->with('message', 'User has been updated successfully');
}

Запретим пользователю залогиниваться, если его статус равен 0.
\app\Http\Controllers\Admin\Auth\LoginController.php

protected function credentials(Request $request) {
return ['email'=>$request->email, 'password'=>$request->password, 'status'=>1]; // при залогинивании проверяется 3 поля
// return $request->only($this->username(), 'password');
}

Теперь, если попытаться войти у нас появляется запись: These credentials do not match our records.
Перепишем файл \app\Http\Controllers\Admin\Auth\LoginController.php
<?php

namespace App\Http\Controllers\Admin\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Model\admin\admin;

class LoginController extends Controller
{


use AuthenticatesUsers;


protected $redirectTo = 'admin/home';

public function showLoginForm() {
return view('admin.login');
}

public function login(Request $request)
{
$this->validateLogin($request);


if ($this->attemptLogin($request)) {
return $this->sendLoginResponse($request);
}


return $this->sendFailedLoginResponse($request);
}

protected function credentials(Request $request) {
$admin = admin::where('email', $request->email)->first();
if(count($admin)) {
if($admin->status == 0) {
return ['email'=>'inactive', 'password'=>'You are not an active person, please contact Admin']; // при залогинивании проверяется 3 поля
} else {
return ['email'=>$request->email, 'password'=>$request->password, 'status'=>1]; // при залогинивании проверяется 3 поля
}
}
return $request->only($this->username(), 'password');
}


public function __construct()
{
$this->middleware('guest:admin')->except('logout');
}

protected function guard() {
return Auth::guard('admin');
}
}


\vendor\laravel\framework\src\Illuminate\Foundation\Auth\AuthenticatesUsers.php
Мы все переписали!

protected function sendFailedLoginResponse(Request $request)
{

$fields = $this->credentials($request);
if($fields['email'] == 'inactive') {
$errors = $fields['password'];

} else {
$errors = [$this->username() => trans('auth.failed')];
}

if ($request->expectsJson()) {
return response()->json($errors, 422);
}

return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors($errors);
}

Комментариев нет:

Отправить комментарий

Materialize-css. Футер

Сделаем футер и прижмем к низу страницы. Документация: https://materializecss.com/footer.html