Symfony4 ユーザー認証機能作成（後編）


こちらは前編の続きになります。
先に前編のほうを完了させてから進めてください。
[Symfony4 ユーザー認証機能作成（前編）](https://qiita.com/RyotaIhara/items/a5658fd38cdbbb50a926)

### ログインページを作成する

ログイン処理のSecurityControllerを作成する

```bash
$ php bin/console make:controller
```

```php:src/Controller/SecurityController.php
<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;

class SecurityController extends AbstractController
{
    /**
     * @Route("/login", name="login")
     */
    public function login(AuthenticationUtils $authenticationUtils): Response
    {
        $error = $authenticationUtils
            ->getLastAuthenticationError();

        if ($this->getUser() == null) {
            $user = 'not logined...';
        } else {
            $user = 'logined: ' . $this->getUser()->getUsername(); 
        }

        return $this->render('security/login.html.twig', [
            'error' => $error,
            'user' => $user,
        ]);
    }
}
```
ログイン用のテンプレートを作成する。

```twig:templates/security/login.html.twig
{% extends 'base.html.twig' %}

{% block title %}Hello SecurityController!{% endblock %}

{% block body %}
<style>
    .example-wrapper { margin: 1em auto; max-width: 800px; width: 95%; font: 18px/1.5 sans-serif; }
    .example-wrapper code { background: #F5F5F5; padding: 2px 6px; }
</style>

<div class="example-wrapper">
    <p>login</p>
    <p>{{user}}</p>
    {% if error %}
    <p>{{ error.messageKey }}</p>
    {% endif %}

    <form action="{{ path('login') }}" method="post">
        <table>
            <tr>
                <th><label for="username">Username:</th>
                <td><input type="text" id="username" name="_username" /></td>
            </tr>
            <tr>
                <th><label for="password">Password:</th>
                <td><input type="password" id="password" name="_password" /></td>
            </tr>
            <tr><th></th><td><button type="submit">login</button></td></tr>
        </table>
    </form>
</div>
{% endblock %}
```

### 管理者ページを作成する

AdminControllerを作成する。

```bash
$ php bin/console make:controller
```

```php:src/Controller/AdminController.php
<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class AdminController extends AbstractController
{
    /**
     * @Route("/admin", name="admin")
     */
    public function admin(): Response
    {
        return $this->render('admin/admin.html.twig', [
            'title' => 'Admin',
            'message' => 'message',
            'user' => $this->getUSer(),
        ]);
    }
}
```

```twig:templates/admin/admin.html.twig
{% extends 'base.html.twig' %}

{% block title %}Hello AdminController!{% endblock %}

{% block body %}
<style>
    .example-wrapper { margin: 1em auto; max-width: 800px; width: 95%; font: 18px/1.5 sans-serif; }
    .example-wrapper code { background: #F5F5F5; padding: 2px 6px; }
</style>

<div class="example-wrapper">
    <h2>{{ message }}</h2>
    <p>user: {{ user.username }}</p>
    <p>mail: {{ user.email }}</p>
</div>
{% endblock %}
```

### 一般ユーザー用のページを作成する

HelloControllerを作成する。

```bash
$ php bin/console make:controller
```

```php:src/Controller/HelloController.php
<?php

namespace App\Controller;

use App\Entity\Person;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

class HelloController extends AbstractController
{
    /**
     * @Route("/hello", name="hello")
     */
    public function index(Request $request): Response
    {
        if (!$this->getUser()->getIsActivated()) {
            throw new AccessDeniedException('Unable to access!');
        }

        return $this->render('hello/index.html.twig', [
            'title' => 'Admin',
            'message' => 'message',
            'user' => $this->getUser(),
        ]);
    }
}
```

```twig:templates/hello/index.html.twig
{% extends 'base.html.twig' %}

{% block title %}Hello HelloController!{% endblock %}

{% block body %}
<style>
    .example-wrapper { margin: 1em auto; max-width: 800px; width: 95%; font: 18px/1.5 sans-serif; }
    .example-wrapper code { background: #F5F5F5; padding: 2px 6px; }
</style>

<div class="example-wrapper">
    <h2>{{ message }}</h2>
    <table>
        <tr><th>id</th><td>{{ user.id }}</td></tr>
        <tr><th>name</th><td>{{ user.username }}</td></tr>
        <tr><th>mail</th><td>{{ user.email }}</td></tr>
    </table>
</div>
{% endblock %}
```