summaryrefslogtreecommitdiff
path: root/src/Controller/Login.php
blob: 0f360aef8db8b99a1ab7073c9b64a914af18bd93 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php

namespace App\Controller;

use App\DB;
use App\View;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class Login
{
  #[Route(path: '/login', methods: ['GET'])]
  public function form(Request $request): Response
  {
    return new Response(View::render('login.twig'));
  }

  #[Route(path: '/login', methods: ['POST'])]
  public function login(Request $request): Response
  {
    $email = $request->get('email');
    $user = DB::query('select id,username,password from users where email=:email', ['email' => $email])->fetch();

    if (empty($user)) {
      $password = password_hash($request->get('password'), PASSWORD_DEFAULT);
      DB::query('insert into users (username, password, email) values (:username, :password, :email)', ['username' => $email, 'password' => $password, 'email' => $email]);
    } else {
      $password = $user['password'];
    }

    if (password_verify($request->get('password'), $password)) {
      $_SESSION['user'] = [
        'id' => $user['id'],
        'username' => $user['username'],
      ];

      return new RedirectResponse('/villages');
    }

    return new RedirectResponse('/login');
  }

  #[Route(path: '/logout', methods: ['GET'])]
  public function logout(Request $request): Response
  {
    session_unset();
    session_destroy();

    return new RedirectResponse('/login');
  }
}