Technológie internetuInternet Technologies / Týždeň 10Week 10

Sessions a prihlásenieSessions and login

Táto téma je nepovinná a na cvičení sa nepreberá. Stránka vysvetľuje, ako prihlásenie funguje a prečo, a dáva postup po krokoch. Prompty tu nie sú a ukážky sú len časti files, zvyšok kódu dopĺňa autor aplikácie. Body sú za obhajobu. Kto prihlásenie spraví, vysvetlí pri obhajobe každý riadok. Pojmy sú v tabuľke v týždni 1.

Východisko je aplikácia po cv08. Prihlásenie sa skladá z toho, čo v nej už je: formulár s INSERT ako v add-ENTITY.php, file bez stránky s redirect ako delete-LOOKUP.php a správa cez $messages v template.php. Príklady sú z aplikácie lezecká stena.

This topic is optional and is not covered in the lab. The page explains how login works and why, and gives a step-by-step procedure. There are no prompts here and the examples are only parts of files; the author of the application writes the rest of the code. Points are awarded for the defence. Whoever builds the login explains every line at the defence. Terms are in the table in week 1.

The starting point is the application after cv08. Login is built from what is already in it: a form with INSERT like add-ENTITY.php, a file without a page with a redirect like delete-LOOKUP.php, and a message through $messages in template.php. The examples come from the climbing wall application.

TeóriaTheory

Prečo server nevie, kto je prihlásený

Každý request je pre server nový. Server si medzi requestami nepamätá, kto ich poslal. Keby sa používateľ prihlásil v login.php, pri ďalšom requeste na add-route.php by o tom server nevedel. Prihlásenie preto potrebuje miesto, kde sa informácia o používateľovi uchová medzi requestami.

Cookie je krátky text, ktorý server pošle prehliadaču v response. Prehliadač ho uloží a pošle späť s každým ďalším requestom na ten istý web.

Session je miesto na serveri, kde má PHP uložené údaje jedného návštevníka. Každá session má identifikátor, session id. Prehliadač dostane v cookie s názvom PHPSESSID len toto id. Údaje zostávajú na serveri.

Kde Čo tam je Kto to vidí
prehliadač, cookie PHPSESSID session id, dlhý náhodný text používateľ, v nástrojoch pre vývojárov
server, session údaje: id a meno prihláseného používateľa len PHP na serveri

Priebeh:

  1. Prvý request: prehliadač cookie nemá. PHP vytvorí session a pošle v response cookie PHPSESSID s jej id.
  2. Každý ďalší request: prehliadač pošle cookie. PHP podľa id nájde session a načíta jej údaje.
  3. Prihlásenie: PHP zapíše do session id a meno používateľa.
  4. Ďalšie requesty: PHP v session nájde id používateľa, používateľ je prihlásený.
  5. Odhlásenie: PHP údaje session zmaže.

session_start a $_SESSION

session_start() je funkcia PHP. Prečíta session id z cookie a načíta údaje session do array $_SESSION. Keď prehliadač cookie nemá, vytvorí novú session a pošle cookie.

session_start();
$_SESSION['user_name'] = 'Jana';     // zápis: hodnota zostane aj pri ďalšom requeste
echo $_SESSION['user_name'];         // čítanie v inom file, pri inom requeste: Jana

$_SESSION je array ako $_GET a $_POST. Rozdiel je v tom, odkiaľ sú hodnoty: do $_GET a $_POST ich posiela prehliadač, do $_SESSION ich zapisuje PHP na serveri. Používateľ ich prepísať nevie.

Cookie sa posiela v HTTP header. Pre session_start() preto platí to isté ako pre header() v cv08: musí byť zavolaná skôr, ako PHP začne vypisovať HTML.

session_start() je v db.php, lebo db.php pripája každý file ako prvý riadok. Session je tak spustená pred začiatkom HTML. Spustená session ešte nie je ochrana: file vie zistiť, kto je prihlásený, ale otvorí sa každému. Ochranu pridáva až login-required.php.

Viac: php.net: session_start

Heslo sa neukladá, ukladá sa hash

Databázu môže niekto získať. Keby v nej boli heslá, mal by heslo každého používateľa. Do databázy sa preto ukladá hash: text vypočítaný z hesla, z ktorého sa heslo späť zistiť nedá.

Funkcia Kedy Čo vráti
password_hash($pass, PASSWORD_DEFAULT) pri registrácii hash, text dlhý 60 znakov, ukladá sa do column password_hash
password_verify($pass, $hash) pri prihlásení true, keď heslo patrí k hash, inak false
$hash = password_hash('tajne12345', PASSWORD_DEFAULT);   // $2y$10$Jn8JlMeT39Q1/...
password_verify('tajne12345', $hash);                    // true
password_verify('tajne12346', $hash);                    // false

password_hash vráti pre to isté heslo zakaždým iný hash. Hash sa preto neporovnáva cez === ani vo WHERE, vždy cez password_verify.

Column password_hash má typ VARCHAR(255). Kratšia column by hash orezala a prihlásenie by nefungovalo.

Viac: php.net: password_hash, php.net: password_verify

Files a ich roly

File Rola Na čo nadväzuje
db.php spoločný file: pripojenie k databáze a session_start() cv07
signup.php + content/signup.php používatelia, formulár na nového používateľa, INSERT do users add-ENTITY.php
login.php + content/login.php používatelia, formulár na prihlásenie
login-check.php file bez stránky: overí heslo, zapíše do $_SESSION, redirect delete-LOOKUP.php
logout.php file bez stránky: zmaže údaje session, redirect delete-LOOKUP.php
login-required.php spoločný file: neprihláseného pošle na login.php header() a exit
template.php v menu meno a button Odhlásiť, alebo odkazy Prihlásiť a Registrácia $messages

Prihlásenie končí redirect. Redirect v content file nefunguje, preto formulár v content/login.php má action="login-check.php" a správu o výsledku vypíše template.php z $messages.

Table users má columns id, name, email (UNIQUE) a password_hash.

Skrytý odkaz nie je ochrana

Keď template.php neprihlásenému neukáže odkaz na add-route.php, adresa stále funguje pre každého, kto ju napíše do prehliadača. Rovnako POST request na delete-route.php sa dá poslať bez formulára. Chrániť treba file. login-required.php sa preto pripája v každom file, ktorý mení dáta, aj vo files bez stránky.

File Kto ho otvorí
index.php, contact.php, routes.php, detail.php, stats.php, login.php, signup.php každý
add-route.php, edit-route.php, delete-route.php, data.php, edit-grade.php, edit-style.php, delete-grade.php, delete-style.php len prihlásený

Bezpečnosť pri prihlásení

  • Správa po neúspešnom prihlásení je tá istá pre neexistujúci e-mail aj pre nesprávne heslo. Rôzne správy by prezradili, ktoré e-maily sú registrované.
  • session_regenerate_id(true) po úspešnom prihlásení vytvorí nové session id a staré prestane platiť. Kto poznal staré id, s ním nič nezíska.
  • V $_SESSION je id a meno používateľa. Heslo ani hash tam nepatria.
  • Odhlásenie mení stav, preto ide cez POST ako mazanie v cv08.
  • db.php už má premenné $user a $password s údajmi k databáze. Hodnoty z formulára a record používateľa preto patria do premenných s iným názvom, v ukážkach $pass a $account, aby sa neplietli s údajmi k databáze.
  • Pri skúšaní sa používajú vymyslené heslá a e-maily s doménou example.com.

Najčastejšie chyby a čo znamenajú

Hláška alebo prejav Príčina Riešenie
Warning: session_start(): Session cannot be started after headers have already been sent pred require 'db.php' sa niečo vypísalo, alebo je pred <?php prázdny riadok require 'db.php'; ako prvý riadok file stránky
meno prihláseného v menu chýba v index.php alebo contact.php file nepripája db.php, session nie je spustená doplniť require 'db.php';
aj prihlásený používateľ skončí na login.php login-required.php je pripojený pred db.php, session ešte nie je spustená poradie: db.php, potom login-required.php
prihlásenie nejde ani so správnym heslom column password_hash je krátka a hash je orezaný VARCHAR(255), registrovať znova
prihlásenie nejde ani so správnym heslom hash sa porovnáva cez === alebo vo WHERE password_verify
neprihlásený vie mazať cez adresu login-required.php chýba v delete-*.php pripojiť aj vo files bez stránky
po odhlásení je v menu stále meno logout.php nepripája db.php, alebo chýba session_destroy() doplniť
správa po prihlásení sa nezobrazí key v URL nie je v $messages doplniť keys wrong, login, welcome, bye

Why the server does not know who is logged in

Every request is new to the server. Between requests the server does not remember who sent them. If a user logged in on login.php, the server would not know about it at the next request to add-route.php. Login therefore needs a place where the information about the user is kept between requests.

A cookie is a short text the server sends to the browser in the response. The browser stores it and sends it back with every further request to the same website.

A session is a place on the server where PHP keeps the data of one visitor. Every session has an identifier, the session id. In the cookie named PHPSESSID the browser receives only this id. The data stays on the server.

Where What is there Who sees it
browser, cookie PHPSESSID the session id, a long random text the user, in the developer tools
server, session the data: id and name of the logged-in user only PHP on the server

The sequence:

  1. First request: the browser has no cookie. PHP creates a session and sends the cookie PHPSESSID with its id in the response.
  2. Every further request: the browser sends the cookie. PHP finds the session by the id and loads its data.
  3. Login: PHP writes the id and name of the user into the session.
  4. Further requests: PHP finds the id of the user in the session, the user is logged in.
  5. Logout: PHP deletes the data of the session.

session_start and $_SESSION

session_start() is a PHP function. It reads the session id from the cookie and loads the session data into the array $_SESSION. When the browser has no cookie, it creates a new session and sends the cookie.

session_start();
$_SESSION['user_name'] = 'Jana';     // zápis: hodnota zostane aj pri ďalšom requeste
echo $_SESSION['user_name'];         // čítanie v inom file, pri inom requeste: Jana

$_SESSION is an array like $_GET and $_POST. The difference is where the values come from: the browser sends them into $_GET and $_POST, PHP on the server writes them into $_SESSION. The user cannot rewrite them.

A cookie is sent in an HTTP header. The same rule as for header() in cv08 therefore applies to session_start(): it must be called before PHP starts printing HTML.

session_start() is in db.php because every file includes db.php as its first line. The session is thus started before the HTML begins. A started session is not protection yet: the file can find out who is logged in, but it opens for everyone. Protection is added only by login-required.php.

More: php.net: session_start

The password is not stored, the hash is

Somebody may get hold of the database. If it contained passwords, they would have the password of every user. The database therefore stores a hash: a text computed from the password from which the password cannot be recovered.

Function When What it returns
password_hash($pass, PASSWORD_DEFAULT) at registration the hash, a text 60 characters long, stored in the column password_hash
password_verify($pass, $hash) at login true when the password belongs to the hash, otherwise false
$hash = password_hash('tajne12345', PASSWORD_DEFAULT);   // $2y$10$Jn8JlMeT39Q1/...
password_verify('tajne12345', $hash);                    // true
password_verify('tajne12346', $hash);                    // false

password_hash returns a different hash for the same password every time. The hash is therefore never compared with === or in WHERE, always with password_verify.

The column password_hash has the type VARCHAR(255). A shorter column would cut the hash and login would not work.

More: php.net: password_hash, php.net: password_verify

Files and their roles

File Role Builds on
db.php shared file: database connection and session_start() cv07
signup.php + content/signup.php users, form for a new user, INSERT into users add-ENTITY.php
login.php + content/login.php users, login form
login-check.php file without a page: verifies the password, writes into $_SESSION, redirect delete-LOOKUP.php
logout.php file without a page: deletes the session data, redirect delete-LOOKUP.php
login-required.php shared file: sends a user who is not logged in to login.php header() and exit
template.php in the menu the name and the button Odhlásiť (Log out), or the links Prihlásiť (Log in) and Registrácia (Sign up) $messages

Login ends with a redirect. A redirect does not work in a content file, so the form in content/login.php has action="login-check.php" and the message about the result is printed by template.php from $messages.

The table users has the columns id, name, email (UNIQUE) and password_hash.

When template.php does not show the link to add-route.php to a user who is not logged in, the address still works for anyone who types it into the browser. Likewise a POST request to delete-route.php can be sent without the form. The file has to be protected. login-required.php is therefore included in every file that changes data, including the files without a page.

File Who can open it
index.php, contact.php, routes.php, detail.php, stats.php, login.php, signup.php everyone
add-route.php, edit-route.php, delete-route.php, data.php, edit-grade.php, edit-style.php, delete-grade.php, delete-style.php only a logged-in user

Security of login

  • The message after a failed login is the same for an unknown e-mail and for a wrong password. Different messages would reveal which e-mails are registered.
  • session_regenerate_id(true) after a successful login creates a new session id and the old one stops being valid. Whoever knew the old id gains nothing with it.
  • $_SESSION holds the id and name of the user. The password and the hash do not belong there.
  • Logout changes state, so it goes through POST like deleting in cv08.
  • db.php already has the variables $user and $password with the database details. Values from the form and the record of the user therefore go into variables with other names, $pass and $account in the examples, so that they are not confused with the database details.
  • Use made-up passwords and e-mails with the domain example.com when testing.

Common errors and what they mean

Message or symptom Cause Fix
Warning: session_start(): Session cannot be started after headers have already been sent something was printed before require 'db.php', or there is an empty line before <?php require 'db.php'; as the first line of the page file
the name of the logged-in user is missing in the menu in index.php or contact.php the file does not include db.php, the session is not started add require 'db.php';
even a logged-in user ends up on login.php login-required.php is included before db.php, the session is not started yet order: db.php, then login-required.php
login fails even with the correct password the column password_hash is short and the hash is cut VARCHAR(255), register again
login fails even with the correct password the hash is compared with === or in WHERE password_verify
a user who is not logged in can delete through the address login-required.php is missing in delete-*.php include it in the files without a page too
after logout the name is still in the menu logout.php does not include db.php, or session_destroy() is missing add them
no message after login the key in the URL is not in $messages add the keys wrong, login, welcome, bye

UkážkyExamples

Ukážky sú časti files: riadky, ktoré sú pre prihlásenie nové. Zvyšok každého file (komentár s rolou, kontrola povinných hodnôt, HTML formulára) je rovnaký ako vo files z cv07 a cv08 a dopĺňa ho autor aplikácie. Pod každou ukážkou je náhľad stránky v prehliadači s adresou, ktorá sa otvorí. Používateľ v náhľadoch je vymyslený: Jana, jana@example.com.

Ukážka 1: table users

sql/schema.sql
CREATE TABLE users (
  id            INT AUTO_INCREMENT PRIMARY KEY,
  name          VARCHAR(60)  NOT NULL,           -- meno, vypisuje sa v menu
  email         VARCHAR(120) NOT NULL UNIQUE,    -- podľa e-mailu sa používateľ hľadá pri prihlásení
  password_hash VARCHAR(255) NOT NULL            -- hash z password_hash(); heslo sa neukladá
) CHARACTER SET utf8mb4;

Na začiatok schema.sql patrí aj DROP TABLE IF EXISTS users;. Table users na nič neukazuje a nič neukazuje na ňu, jej poradie medzi ostatnými je ľubovoľné.

Ukážka 2: db.php, session_start

web/db.php
ini_set('display_errors', 1);
error_reporting(E_ALL);
session_start();                 // session: načíta $_SESSION podľa cookie PHPSESSID, pred začiatkom HTML

Do index.php a contact.php pribudne require 'db.php'; ako prvý riadok, aby mala session každá stránka.

Takto to vyzerá v prehliadači: stránka vyzerá rovnako ako predtým. V nástrojoch pre vývojárov (F12, karta Application, vľavo Cookies) je cookie PHPSESSID s dlhým náhodným textom.

Ukážka 3: signup.php (používatelia), registrácia

web/content/signup.php
$pass = $_POST['pass'];                                      // $pass, nie $password: $password je v db.php

$stmt = $pdo->prepare('SELECT id FROM users WHERE email = ?');   // existuje už taký e-mail?
$stmt->execute([$email]);
if ($stmt->fetch()) {
  $message = 'E-mail ' . $email . ' je už registrovaný.';
} else {
  $hash = password_hash($pass, PASSWORD_DEFAULT);            // hash hesla; heslo sa do databázy nezapíše
  $stmt = $pdo->prepare('INSERT INTO users (name, email, password_hash) VALUES (?, ?, ?)');
  $stmt->execute([$name, $email, $hash]);
  $message = 'Registrácia prebehla. Teraz sa prihlás.';
}
web/content/signup.php
<input class="form-control" id="pass" name="pass" type="password" required>

type="password" skryje znaky pri písaní. Heslo sa po odoslaní späť do formulára nevypisuje, input pass nemá value.

…/web/signup.php
Lezecká stenaDomovCestyNová cestaDatabázaPrehľadKontaktPrihlásiťRegistrácia

Registrácia

Registrácia prebehla. Teraz sa prihlás.
Registrovať Mám účet, prihlásiť

Takto to vyzerá v prehliadači: otvorená adresa je signup.php. Po odoslaní mena Jana, e-mailu jana@example.com a hesla je nad formulárom správa „Registrácia prebehla. Teraz sa prihlás.” Po druhom odoslaní toho istého e-mailu je tam správa „E-mail jana@example.com je už registrovaný.”

Čo vráti SELECT * FROM users v Adminer:

id name email password_hash
1 Jana jana@example.com $2y10Jn8JlMeT39Q1/… (60 znakov)

Ukážka 4: login.php a login-check.php, prihlásenie

web/content/login.php
<form method="post" action="login-check.php" class="row g-3">
web/login-check.php
require 'db.php';

$email = $_POST['email'];
$pass  = $_POST['pass'];

$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
$stmt->execute([$email]);
$account = $stmt->fetch();                       // record používateľa, alebo false

if (!$account || !password_verify($pass, $account['password_hash'])) {   // e-mail neexistuje, alebo heslo nepatrí k hash
  header('Location: login.php?msg=wrong');       // tá istá správa pre obe príčiny
  exit;
}

session_regenerate_id(true);                     // nové session id po prihlásení
$_SESSION['user_id']   = $account['id'];         // od tejto chvíle je používateľ prihlásený
$_SESSION['user_name'] = $account['name'];
header('Location: index.php?msg=welcome');
exit;

Čo robí ktorý riadok:

  • !$account: fetch() vrátil false, používateľ s týmto e-mailom nie je,
  • || znamená „alebo”: podmienka platí, keď platí aspoň jedna časť,
  • !password_verify(...): heslo nepatrí k hash z databázy,
  • do $_SESSION sa zapisuje až po kontrole; pred ňou skript pri neúspechu končí cez exit.

Na začiatok login-check.php patrí aj kontrola, že request je POST, ako v delete-LOOKUP.php.

…/web/login.php
Lezecká stenaDomovCestyNová cestaDatabázaPrehľadKontaktPrihlásiťRegistrácia

Prihlásenie

Prihlásiť Registrácia

Takto to vyzerá v prehliadači: otvorená adresa je login.php. V menu vpravo sú odkazy Prihlásiť a Registrácia.

…/web/login.php?msg=wrong
Lezecká stenaDomovCestyNová cestaDatabázaPrehľadKontaktPrihlásiťRegistrácia

Prihlásenie

Nesprávny e-mail alebo heslo.
Prihlásiť Registrácia

Po odoslaní nesprávneho hesla alebo neregistrovaného e-mailu sa otvorí adresa login.php?msg=wrong. Pod titulkom je správa „Nesprávny e-mail alebo heslo.”

…/web/index.php?msg=welcome
Lezecká stenaDomovCestyNová cestaDatabázaPrehľadKontaktJanaOdhlásiť

Lezecká stena

Prihlásenie prebehlo.

(obsah úvodnej stránky)

Po odoslaní správneho e-mailu a hesla sa otvorí adresa index.php?msg=welcome. Pod titulkom je správa „Prihlásenie prebehlo.” a v menu vpravo je meno Jana a button Odhlásiť.

Ukážka 5: template.php, menu a správy

web/template.php
$messages = [
  'deleted' => 'Záznam bol zmazaný.',
  'used'    => 'Záznam sa nedá zmazať, je použitý.',
  'wrong'   => 'Nesprávny e-mail alebo heslo.',
  'login'   => 'Táto stránka je len pre prihlásených.',
  'welcome' => 'Prihlásenie prebehlo.',
  'bye'     => 'Odhlásenie prebehlo.',
];
web/template.php
<ul class="navbar-nav ms-auto">
  <?php if (isset($_SESSION['user_id'])): ?>                      <!-- niekto je prihlásený -->
    <li class="nav-item"><span class="navbar-text me-2"><?= htmlspecialchars($_SESSION['user_name']) ?></span></li>
    <li class="nav-item">
      <form method="post" action="logout.php">                    <!-- odhlásenie cez POST -->
        <button class="btn btn-outline-light btn-sm">Odhlásiť</button>
      </form>
    </li>
  <?php else: ?>                                                  <!-- nikto nie je prihlásený -->
    <li class="nav-item"><a class="nav-link" href="login.php">Prihlásiť</a></li>
    <li class="nav-item"><a class="nav-link" href="signup.php">Registrácia</a></li>
  <?php endif; ?>
</ul>

isset($_SESSION['user_id']) vráti true, keď je v session id používateľa. Bootstrap class ms-auto posunie tento zoznam na pravú stranu menu. Meno zapísal do databázy používateľ, preto sa vypisuje cez htmlspecialchars.

Ukážka 6: login-required.php, ochrana

web/login-required.php
if (!isset($_SESSION['user_id'])) {              // v session nie je id používateľa: nikto nie je prihlásený
  header('Location: login.php?msg=login');       // redirect na formulár na prihlásenie
  exit;                                          // zvyšok file, ktorý login-required.php pripojil, sa nevykoná
}
web/add-route.php
require 'db.php';                 // pripojenie a session
require 'login-required.php';     // ochrana: neprihlásený ide na login.php

exit v pripojenom file ukončí celý skript, teda aj file, ktorý ho pripojil. Neprihlásenému sa formulár nevypíše a DELETE sa nevykoná.

…/web/login.php?msg=login
Lezecká stenaDomovCestyNová cestaDatabázaPrehľadKontaktPrihlásiťRegistrácia

Prihlásenie

Táto stránka je len pre prihlásených.
Prihlásiť Registrácia

Takto to vyzerá v prehliadači: neprihlásený používateľ napíše do prehliadača adresu add-route.php. Otvorí sa adresa login.php?msg=login a pod titulkom je správa „Táto stránka je len pre prihlásených.” Adresa stats.php sa neprihlásenému otvorí: stats.php pripája db.php, session má, ale login-required.php nepripája.

Ukážka 7: logout.php, odhlásenie

web/logout.php
require 'db.php';

$_SESSION = [];                   // vyprázdni údaje session v tomto requeste
session_destroy();                // zmaže údaje session na serveri
header('Location: index.php?msg=bye');
exit;

Na začiatok logout.php patrí kontrola, že request je POST.

…/web/index.php?msg=bye
Lezecká stenaDomovCestyNová cestaDatabázaPrehľadKontaktPrihlásiťRegistrácia

Lezecká stena

Odhlásenie prebehlo.

(obsah úvodnej stránky)

Takto to vyzerá v prehliadači: po kliknutí na button Odhlásiť sa otvorí adresa index.php?msg=bye. Pod titulkom je správa „Odhlásenie prebehlo.” a v menu vpravo sú znova odkazy Prihlásiť a Registrácia. Adresa add-route.php znova otvorí login.php?msg=login.

The examples are parts of files: the lines that are new for login. The rest of each file (the comment with the role, the check of required values, the HTML of the form) is the same as in the files from cv07 and cv08 and is completed by the author of the application. Under every example is a preview of the page in the browser with the address that opens. The user in the previews is made up: Jana, jana@example.com. Comments in the code and texts in the application are in Slovak.

Example 1: the table users

sql/schema.sql
CREATE TABLE users (
  id            INT AUTO_INCREMENT PRIMARY KEY,
  name          VARCHAR(60)  NOT NULL,           -- meno, vypisuje sa v menu
  email         VARCHAR(120) NOT NULL UNIQUE,    -- podľa e-mailu sa používateľ hľadá pri prihlásení
  password_hash VARCHAR(255) NOT NULL            -- hash z password_hash(); heslo sa neukladá
) CHARACTER SET utf8mb4;

DROP TABLE IF EXISTS users; also belongs at the beginning of schema.sql. The table users points to nothing and nothing points to it, so its position among the others does not matter.

Example 2: db.php, session_start

web/db.php
ini_set('display_errors', 1);
error_reporting(E_ALL);
session_start();                 // session: načíta $_SESSION podľa cookie PHPSESSID, pred začiatkom HTML

index.php and contact.php get require 'db.php'; as their first line, so that every page has the session.

What it looks like in the browser: the page looks the same as before. In the developer tools (F12, the Application tab, Cookies on the left) there is the cookie PHPSESSID with a long random text.

Example 3: signup.php (users), registration

web/content/signup.php
$pass = $_POST['pass'];                                      // $pass, nie $password: $password je v db.php

$stmt = $pdo->prepare('SELECT id FROM users WHERE email = ?');   // existuje už taký e-mail?
$stmt->execute([$email]);
if ($stmt->fetch()) {
  $message = 'E-mail ' . $email . ' je už registrovaný.';
} else {
  $hash = password_hash($pass, PASSWORD_DEFAULT);            // hash hesla; heslo sa do databázy nezapíše
  $stmt = $pdo->prepare('INSERT INTO users (name, email, password_hash) VALUES (?, ?, ?)');
  $stmt->execute([$name, $email, $hash]);
  $message = 'Registrácia prebehla. Teraz sa prihlás.';
}
web/content/signup.php
<input class="form-control" id="pass" name="pass" type="password" required>

type="password" hides the characters while typing. After submitting, the password is not printed back into the form; the input pass has no value.

…/web/signup.php
Lezecká stenaDomovCestyNová cestaDatabázaPrehľadKontaktPrihlásiťRegistrácia

Registrácia

Registrácia prebehla. Teraz sa prihlás.
Registrovať Mám účet, prihlásiť

What it looks like in the browser: the opened address is signup.php. After submitting the name Jana, the e-mail jana@example.com and a password, the message above the form is “Registrácia prebehla. Teraz sa prihlás.” (Registration done. Now log in.) After submitting the same e-mail again the message is “E-mail jana@example.com je už registrovaný.” (is already registered).

What SELECT * FROM users returns in Adminer:

id name email password_hash
1 Jana jana@example.com $2y10Jn8JlMeT39Q1/… (60 znakov)

Example 4: login.php and login-check.php, login

web/content/login.php
<form method="post" action="login-check.php" class="row g-3">
web/login-check.php
require 'db.php';

$email = $_POST['email'];
$pass  = $_POST['pass'];

$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
$stmt->execute([$email]);
$account = $stmt->fetch();                       // record používateľa, alebo false

if (!$account || !password_verify($pass, $account['password_hash'])) {   // e-mail neexistuje, alebo heslo nepatrí k hash
  header('Location: login.php?msg=wrong');       // tá istá správa pre obe príčiny
  exit;
}

session_regenerate_id(true);                     // nové session id po prihlásení
$_SESSION['user_id']   = $account['id'];         // od tejto chvíle je používateľ prihlásený
$_SESSION['user_name'] = $account['name'];
header('Location: index.php?msg=welcome');
exit;

What each line does:

  • !$account: fetch() returned false, there is no user with this e-mail,
  • || means “or”: the condition holds when at least one part holds,
  • !password_verify(...): the password does not belong to the hash from the database,
  • $_SESSION is written only after the check; before it the script ends with exit on failure.

The check that the request is POST also belongs at the beginning of login-check.php, as in delete-LOOKUP.php.

…/web/login.php
Lezecká stenaDomovCestyNová cestaDatabázaPrehľadKontaktPrihlásiťRegistrácia

Prihlásenie

Prihlásiť Registrácia

What it looks like in the browser: the opened address is login.php. On the right of the menu are the links Prihlásiť and Registrácia.

…/web/login.php?msg=wrong
Lezecká stenaDomovCestyNová cestaDatabázaPrehľadKontaktPrihlásiťRegistrácia

Prihlásenie

Nesprávny e-mail alebo heslo.
Prihlásiť Registrácia

After submitting a wrong password or an e-mail that is not registered, the address login.php?msg=wrong opens. Below the title is the message “Nesprávny e-mail alebo heslo.” (Wrong e-mail or password.)

…/web/index.php?msg=welcome
Lezecká stenaDomovCestyNová cestaDatabázaPrehľadKontaktJanaOdhlásiť

Lezecká stena

Prihlásenie prebehlo.

(obsah úvodnej stránky)

After submitting the correct e-mail and password the address index.php?msg=welcome opens. Below the title is the message “Prihlásenie prebehlo.” (Logged in.) and on the right of the menu are the name Jana and the button Odhlásiť.

Example 5: template.php, the menu and the messages

web/template.php
$messages = [
  'deleted' => 'Záznam bol zmazaný.',
  'used'    => 'Záznam sa nedá zmazať, je použitý.',
  'wrong'   => 'Nesprávny e-mail alebo heslo.',
  'login'   => 'Táto stránka je len pre prihlásených.',
  'welcome' => 'Prihlásenie prebehlo.',
  'bye'     => 'Odhlásenie prebehlo.',
];
web/template.php
<ul class="navbar-nav ms-auto">
  <?php if (isset($_SESSION['user_id'])): ?>                      <!-- niekto je prihlásený -->
    <li class="nav-item"><span class="navbar-text me-2"><?= htmlspecialchars($_SESSION['user_name']) ?></span></li>
    <li class="nav-item">
      <form method="post" action="logout.php">                    <!-- odhlásenie cez POST -->
        <button class="btn btn-outline-light btn-sm">Odhlásiť</button>
      </form>
    </li>
  <?php else: ?>                                                  <!-- nikto nie je prihlásený -->
    <li class="nav-item"><a class="nav-link" href="login.php">Prihlásiť</a></li>
    <li class="nav-item"><a class="nav-link" href="signup.php">Registrácia</a></li>
  <?php endif; ?>
</ul>

isset($_SESSION['user_id']) returns true when the session holds the id of a user. The Bootstrap class ms-auto moves this list to the right side of the menu. The name was written into the database by the user, so it is printed through htmlspecialchars.

Example 6: login-required.php, protection

web/login-required.php
if (!isset($_SESSION['user_id'])) {              // v session nie je id používateľa: nikto nie je prihlásený
  header('Location: login.php?msg=login');       // redirect na formulár na prihlásenie
  exit;                                          // zvyšok file, ktorý login-required.php pripojil, sa nevykoná
}
web/add-route.php
require 'db.php';                 // pripojenie a session
require 'login-required.php';     // ochrana: neprihlásený ide na login.php

exit in an included file ends the whole script, including the file that included it. For a user who is not logged in the form is not printed and DELETE is not executed.

…/web/login.php?msg=login
Lezecká stenaDomovCestyNová cestaDatabázaPrehľadKontaktPrihlásiťRegistrácia

Prihlásenie

Táto stránka je len pre prihlásených.
Prihlásiť Registrácia

What it looks like in the browser: a user who is not logged in types the address add-route.php into the browser. The address login.php?msg=login opens and below the title is the message “Táto stránka je len pre prihlásených.” (This page is for logged-in users only.) The address stats.php opens for a user who is not logged in: stats.php includes db.php, so it has the session, but it does not include login-required.php.

Example 7: logout.php, logout

web/logout.php
require 'db.php';

$_SESSION = [];                   // vyprázdni údaje session v tomto requeste
session_destroy();                // zmaže údaje session na serveri
header('Location: index.php?msg=bye');
exit;

The check that the request is POST belongs at the beginning of logout.php.

…/web/index.php?msg=bye
Lezecká stenaDomovCestyNová cestaDatabázaPrehľadKontaktPrihlásiťRegistrácia

Lezecká stena

Odhlásenie prebehlo.

(obsah úvodnej stránky)

What it looks like in the browser: after clicking the button Odhlásiť the address index.php?msg=bye opens. Below the title is the message “Odhlásenie prebehlo.” (Logged out.) and on the right of the menu are the links Prihlásiť and Registrácia again. The address add-route.php opens login.php?msg=login again.

Úlohy na cvičenieLab tasks

Téma je nepovinná. Prijať zadanie cv09 v Classroom 50 (platí pre skupiny B. Stehlíkovej; ostatné skupiny dostanú link od svojho cvičiaceho).

Pracuje sa v repository cv09 na kópii aplikácie z cv08. Odovzdaný stav cv08 a ti/projekt/ sa nemenia.

10.1 git clone repository cv09 a prekopíruj aplikáciu z cv08:

rsync -a --exclude .git --exclude README.md cv08/ cv09/

Commit.

10.2 Table users (ukážka 1): doplň ju do sql/schema.sql a spusti schema.sql a seed.sql v Adminer.

10.3 db.php (ukážka 2): doplň session_start() pred vytvorenie $pdo a uprav komentár // ROLA:. Do index.php a contact.php doplň require 'db.php'; ako prvý riadok. Over: v nástrojoch pre vývojárov je cookie PHPSESSID.

10.4 signup.php s content/signup.php (ukážka 3): formulár meno, e-mail, heslo. Kontrola povinných hodnôt, kontrola, či e-mail už existuje, password_hash, INSERT, správa nad formulárom. Použi vymyslené heslo a e-mail s doménou example.com. Over v Adminer: v column password_hash je hash, heslo tam nie je. Commit.

10.5 login.php s content/login.php (ukážka 4): formulár e-mail a heslo, method="post", action="login-check.php".

10.6 login-check.php (ukážka 4): kontrola, že request je POST, SELECT používateľa podľa e-mailu, password_verify, pri neúspechu redirect na login.php?msg=wrong, pri úspechu session_regenerate_id(true), zápis do $_SESSION a redirect na index.php?msg=welcome.

10.7 template.php (ukážka 5): doplň keys wrong, login, welcome a bye do $messages. V menu vpravo meno a button Odhlásiť pre prihláseného, odkazy na login.php a signup.php pre neprihláseného. Over: prihlásenie so správnym heslom, s nesprávnym heslom, s neregistrovaným e-mailom. Commit.

10.8 logout.php (ukážka 7): kontrola, že request je POST, zmazanie údajov session, redirect na index.php?msg=bye.

10.9 login-required.php (ukážka 6). Pripoj ho hneď za require 'db.php'; v add-ENTITY.php, edit-ENTITY.php, delete-ENTITY.php, data.php, edit-LOOKUP.php a delete-LOOKUP.php. Každý nový file má na začiatku komentár // ROLA:.

10.10 Over bez prihlásenia: adresa add-ENTITY.php napísaná do prehliadača otvorí login.php. Over to isté po odhlásení. Commit a push. Upload Folder: cv09 do ti/cv09/. Do ti/projekt/ sa cv09 nenahráva.

Hodnotenie: téma je nepovinná, body sú za obhajobu. Aplikácia s registráciou, prihlásením, odhlásením a ochranou files, ktoré menia dáta, funguje vo svojom webovom priestore na sigma.tuke.sk v ti/cv09/, kód je v repository. Po push sa spustia testy (10 kontrol); zelený výsledok znamená, že files a požadované časti kódu sú na mieste, body udeľuje učiteľka po obhajobe.

The topic is optional. Accept assignment cv09 in Classroom 50 (applies to B. Stehlíková’s groups; other groups get the link from their own teacher).

The work is done in the repository cv09 on a copy of the application from cv08. The submitted state of cv08 and ti/projekt/ do not change.

10.1 git clone the repository cv09 and copy the application from cv08:

rsync -a --exclude .git --exclude README.md cv08/ cv09/

Commit.

10.2 The table users (example 1): add it to sql/schema.sql and run schema.sql and seed.sql in Adminer.

10.3 db.php (example 2): add session_start() before $pdo is created and update the comment // ROLA:. Add require 'db.php'; as the first line of index.php and contact.php. Verify: the developer tools show the cookie PHPSESSID.

10.4 signup.php with content/signup.php (example 3): a form with name, e-mail and password. A check of required values, a check whether the e-mail already exists, password_hash, INSERT, a message above the form. Use a made-up password and an e-mail with the domain example.com. Verify in Adminer: the column password_hash holds a hash, the password is not there. Commit.

10.5 login.php with content/login.php (example 4): a form with e-mail and password, method="post", action="login-check.php".

10.6 login-check.php (example 4): a check that the request is POST, SELECT of the user by e-mail, password_verify, on failure a redirect to login.php?msg=wrong, on success session_regenerate_id(true), writing into $_SESSION and a redirect to index.php?msg=welcome.

10.7 template.php (example 5): add the keys wrong, login, welcome and bye to $messages. On the right of the menu the name and the button Odhlásiť for a logged-in user, links to login.php and signup.php otherwise. Verify: login with the correct password, with a wrong password, with an e-mail that is not registered. Commit.

10.8 logout.php (example 7): a check that the request is POST, deleting the session data, a redirect to index.php?msg=bye.

10.9 login-required.php (example 6). Include it right after require 'db.php'; in add-ENTITY.php, edit-ENTITY.php, delete-ENTITY.php, data.php, edit-LOOKUP.php and delete-LOOKUP.php. Every new file starts with the comment // ROLA:.

10.10 Verify without logging in: the address add-ENTITY.php typed into the browser opens login.php. Verify the same after logging out. Commit and push. Upload Folder: cv09 to ti/cv09/. cv09 is not uploaded to ti/projekt/.

Grading: the topic is optional, points are awarded for the defence. The application with registration, login, logout and protection of the files that change data works in your web space on sigma.tuke.sk in ti/cv09/, and the code is in the repository. Tests run after the push (10 checks); a green result means the files and the required parts of the code are in place, points are awarded by the teacher after the defence.

Obhajoba a live codingDefence and live coding

Prihlásenie sa obhajuje na aplikácii v ti/cv09/. Live coding sa robí v kópii, odovzdaný stav sa nedotkne. Pri obhajobe budú použité iba zverejnené otázky a úlohy.

Vysvetli (code walkthrough)

  1. Prečo server bez session nevie, že je používateľ prihlásený.
  2. Čo je v cookie PHPSESSID a čo je na serveri. Ukáž cookie v nástrojoch pre vývojárov.
  3. Čo robí session_start(), kde je a prečo práve tam.
  4. Čím sa $_SESSION líši od $_POST.
  5. stats.php pripája db.php, teda má session. Prečo sa napriek tomu otvorí neprihlásenému.
  6. Ukáž v Adminer, čo je v column password_hash, a vysvetli, prečo tam nie je heslo.
  7. Čo vráti password_hash a čo password_verify.
  8. Prečo sa hash neporovnáva cez === ani vo WHERE.
  9. Prečo má column password_hash typ VARCHAR(255).
  10. Prečo je login-check.php file bez stránky a kde sa vypíše správa o výsledku.
  11. Čo znamená podmienka !$account || !password_verify(...).
  12. Prečo je pri neregistrovanom e-maile aj pri nesprávnom hesle tá istá správa.
  13. Čo robí session_regenerate_id(true) a prečo je po prihlásení.
  14. Čo je po prihlásení v $_SESSION a prečo tam nie je heslo.
  15. Čo robí login-required.php a čo spraví exit v pripojenom file.
  16. Prečo nestačí skryť odkaz v menu.
  17. Prečo je login-required.php aj v delete-ENTITY.php, keď button Zmazať vidí len prihlásený.
  18. Čo sa stane po logout.php s údajmi na serveri a čo s cookie v prehliadači.
  19. Prečo hodnota hesla z formulára nie je v premennej $password.
  20. Prečo sa meno v menu vypisuje cez htmlspecialchars.

Uprav (live coding)

  1. Pridaj ochranu do stats.php.
  2. Zmeň text správy po odhlásení.
  3. Vypíš meno prihláseného používateľa v content/index.php; neprihlásenému sa nevypíše nič.
  4. V content/signup.php pridaj kontrolu, že heslo má aspoň 8 znakov (strlen).
  5. V content/signup.php pridaj input na zopakovanie hesla a kontrolu, že sa obe hodnoty rovnajú.
  6. Zmeň adresu, na ktorú ide redirect po prihlásení, na ENTITY.php.
  7. V content/detail.php zobraz odkaz Upraviť a button Zmazať len prihlásenému.
  8. V Adminer napíš SELECT, ktorý vráti počet používateľov.

Zdôvodni (design decisions)

  1. Prečo má db.php aj session_start() a čo by bolo treba zmeniť, keby bol vo vlastnom file.
  2. Prečo je v $_SESSION id používateľa a nie celý record z table users.
  3. Prečo je odhlásenie cez POST.
  4. Ktoré files sú verejné a ktoré chránené, a prečo práve tak.
  5. Prečo je ochrana vo vlastnom file a nie skopírovaná do každého file.

Definition of Done

  • table users je v schema.sql, v column password_hash je hash,
  • registrácia odmietne e-mail, ktorý už existuje,
  • prihlásenie so správnym heslom skončí správou a menom v menu, s nesprávnym heslom alebo neregistrovaným e-mailom tou istou správou,
  • odhlásenie vráti do menu odkazy Prihlásiť a Registrácia,
  • adresa každého file, ktorý mení dáta, otvorí neprihlásenému login.php,
  • index.php, ENTITY.php, detail.php a stats.php sa otvoria aj neprihlásenému,
  • každý nový file má komentár // ROLA:,
  • všetko vo webovom priestore na sigma.tuke.sk v ti/cv09/ a v repository.

Login is defended on the application in ti/cv09/. Live coding is done in a copy, the submitted state is not touched. Only the published questions and tasks are used at the defence.

Explain (code walkthrough)

  1. Why the server does not know without a session that a user is logged in.
  2. What is in the cookie PHPSESSID and what is on the server. Show the cookie in the developer tools.
  3. What session_start() does, where it is and why there.
  4. How $_SESSION differs from $_POST.
  5. stats.php includes db.php, so it has the session. Why it still opens for a user who is not logged in.
  6. Show in Adminer what is in the column password_hash and explain why the password is not there.
  7. What password_hash returns and what password_verify returns.
  8. Why the hash is not compared with === or in WHERE.
  9. Why the column password_hash has the type VARCHAR(255).
  10. Why login-check.php is a file without a page and where the message about the result is printed.
  11. What the condition !$account || !password_verify(...) means.
  12. Why the message is the same for an e-mail that is not registered and for a wrong password.
  13. What session_regenerate_id(true) does and why it comes after login.
  14. What is in $_SESSION after login and why the password is not there.
  15. What login-required.php does and what exit in an included file does.
  16. Why hiding the link in the menu is not enough.
  17. Why login-required.php is also in delete-ENTITY.php when only a logged-in user sees the button Zmazať.
  18. What happens after logout.php to the data on the server and to the cookie in the browser.
  19. Why the password value from the form is not in the variable $password.
  20. Why the name in the menu is printed through htmlspecialchars.

Modify (live coding)

  1. Add protection to stats.php.
  2. Change the text of the message after logout.
  3. Print the name of the logged-in user in content/index.php; nothing is printed for a user who is not logged in.
  4. In content/signup.php add a check that the password has at least 8 characters (strlen).
  5. In content/signup.php add an input to repeat the password and a check that both values are equal.
  6. Change the address of the redirect after login to ENTITY.php.
  7. In content/detail.php show the link Upraviť and the button Zmazať only to a logged-in user.
  8. In Adminer write a SELECT that returns the number of users.

Justify (design decisions)

  1. Why db.php also has session_start() and what would have to change if it were in its own file.
  2. Why $_SESSION holds the id of the user and not the whole record from the table users.
  3. Why logout goes through POST.
  4. Which files are public and which are protected, and why.
  5. Why the protection is in its own file and not copied into every file.

Definition of Done

  • the table users is in schema.sql, the column password_hash holds a hash,
  • registration refuses an e-mail that already exists,
  • login with the correct password ends with a message and the name in the menu, with a wrong password or an e-mail that is not registered with the same message,
  • logout returns the links Prihlásiť and Registrácia to the menu,
  • the address of every file that changes data opens login.php for a user who is not logged in,
  • index.php, ENTITY.php, detail.php and stats.php open for a user who is not logged in too,
  • every new file has the comment // ROLA:,
  • everything is in your web space on sigma.tuke.sk in ti/cv09/ and in the repository.