aboutsummaryrefslogtreecommitdiffhomepage
path: root/routes/user_auth.php
blob: afdf8d85433444b1ac776caa3c5c082345c7f375 (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
<?php

use Digitigrade\HttpResponseStatus\TemporaryRedirect;
use Digitigrade\Model\Session;
use Digitigrade\Model\UserAccount;
use Digitigrade\Router;

Router::getInstance()->mount('/login', function (array $args) {
    if (UserAccount::findByCurrentSession() != null) {
        // already logged in
        throw new TemporaryRedirect('/');
    }
    $failedVerification = false;
    if (isset($_POST['email'], $_POST['password'])) {
        $failedVerification = true;
        // try to log in?
        $user = UserAccount::findByEmail($_POST['email']);
        if ($user?->verifyPassword($_POST['password'])) {
            // success
            $session = Session::create($user);
            $session->setCookie(isset($_POST['rememberSession']));
            throw new TemporaryRedirect('/');
        }
    }

    if (isset($_SERVER['HTTP_HX_CURRENT_URL']) && str_ends_with($_SERVER['HTTP_HX_CURRENT_URL'], '/login')) {
        // htmx form submission, therefore just return the form itself
        render_template('login_form', ['email' => $_POST['email'] ?? '', 'failed' => $failedVerification]);
    } else {
        render_template('login_page', ['email' => $_POST['email'] ?? '', 'failed' => $failedVerification]);
    }
});