plateforme-corres2math/server_files/controllers/ajouter_admin.php

56 lines
1.5 KiB
PHP
Raw Normal View History

<?php
if (!isset($_SESSION["role"]) || $_SESSION["role"] != Role::ADMIN)
require_once "server_files/403.php";
$has_error = false;
$error_message = null;
if (isset($_POST["add_admin"])) {
$admin = new NewAdmin($_POST);
try {
$admin->makeVerifications();
$admin->register();
}
catch (AssertionError $e) {
$has_error = true;
$error_message = $e->getMessage();
}
}
class NewAdmin {
public $surname;
public $first_name;
public $email;
public $password;
public function __construct($data)
{
foreach ($data as $key => $value)
$this->$key = htmlspecialchars($value);
}
public function makeVerifications()
{
ensure($this->surname != null && $this->surname != "", "Le nom est invalide.");
ensure($this->first_name != null && $this->first_name != "", "Le prénom est invalide.");
ensure(filter_var($this->email, FILTER_VALIDATE_EMAIL), "L'adresse e-mail est invalide.");
$this->email = strtolower($this->email);
ensure(!userExists($this->email), "Cette adresse e-mail est déjà utilisée.");
}
public function register() {
global $DB, $YEAR;
$this->password = genRandomPhrase(16, true);
$req = $DB->prepare("INSERT INTO `users`(`email`, `pwd_hash`, `surname`, `first_name`, `class`, `role`, `year`)
VALUES (?, ?, ?, ?, ?, ?, ?);");
$req->execute([$this->email, password_hash($this->password, PASSWORD_BCRYPT), $this->surname,
$this->first_name, "ADULT", "ADMIN", $YEAR]);
Mailer::sendAddAdminMail($this);
}
}
require_once "server_files/views/ajouter_admin.php";