Skip to content

Commit

Permalink
manage login for streamer (only acces widget edit page), improve ipli…
Browse files Browse the repository at this point in the history
…mit (move to .env)
  • Loading branch information
emnbdx committed Aug 28, 2024
1 parent 3cffab8 commit 865d53a
Show file tree
Hide file tree
Showing 9 changed files with 165 additions and 24 deletions.
6 changes: 0 additions & 6 deletions .htaccess
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,6 @@ RewriteEngine On
RewriteCond %{REQUEST_URI} ^/.env
RewriteRule ^ - [F]

# Restrict access to the admin directory, allow only two specific IPs
RewriteCond %{REQUEST_URI} ^/admin
RewriteCond %{REMOTE_ADDR} !^90\.63\.182\.86$
RewriteCond %{REMOTE_ADDR} !^217\.128\.58\.80$
RewriteRule ^ - [F]

# Block access to specific code directories
RewriteCond %{REQUEST_URI} ^/(app|migration|vendor)/
RewriteRule ^ - [F]
Expand Down
40 changes: 36 additions & 4 deletions admin/index.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
<?php
require '../app/Config.php';

$canAccess = in_array($_SERVER['REMOTE_ADDR'], Config::getInstance()->haIps);

if(!$canAccess) {
header("Location: /index.php");
}

$repository = Config::getInstance()->repo;

// Traitement du formulaire de création de Charity Stream
Expand All @@ -14,7 +20,18 @@
$guid = bin2hex(random_bytes(16)); // Utilisation de bin2hex pour obtenir une chaîne hexadécimale

// Appeler la fonction pour créer le Charity Stream
$repository->createCharityStreamDB($guid, $ownerEmail, $formSlug, $organizationSlug, $title);
$_SESSION[$guid . 'password'] = $repository->createCharityStreamDB($guid, $ownerEmail, $formSlug, $organizationSlug, $title);
header("Location: /admin/index.php");
exit();
}

if (isset($_POST['refresh_password'])) {
$email = $_POST['email'];
$guid = $_POST['guid'];

$_SESSION[$guid . 'password'] = $repository->updateUserPassword($email);
header("Location: /admin/index.php");
exit();
}

// Utilisation de la fonction GetCharityStreamsList pour récupérer les données mises à jour
Expand All @@ -27,10 +44,8 @@

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Administration des Charity Streams</title>
<link href="/node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="/node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="/node_modules/bootstrap/dist/css/bootstrap.min.css">
</head>

<body class="bg-light">
Expand Down Expand Up @@ -68,6 +83,7 @@
<th>ID</th>
<th>GUID</th>
<th>Email</th>
<th>Mot de passe</th>
<th>Titre</th>
<th>Slug formuaire</th>
<th>Slug association</th>
Expand All @@ -80,6 +96,20 @@
<td><?php echo htmlspecialchars($stream['id']); ?></td>
<td><?php echo htmlspecialchars(bin2hex($stream['guid'])); ?></td>
<td><?php echo htmlspecialchars($stream['owner_email']); ?></td>
<?php if(isset($_SESSION[bin2hex($stream['guid']) . 'password'])) {
$password = $_SESSION[bin2hex($stream['guid']) . 'password'];
unset($_SESSION[bin2hex($stream['guid']) . 'password']);
?>
<td><?php echo $password; ?></td>
<?php } else { ?>
<td>
<form method="POST">
<input type="hidden" name="guid" value="<?php echo bin2hex($stream['guid']) ?>"/>
<input type="hidden" name="email" value="<?php echo $stream['owner_email'] ?>"/>
<button type="submit" class="btn btn-warning" name="refresh_password">Regénérer</button>
</form>
</td>
<?php } ?>
<td><?php echo htmlspecialchars($stream['title']); ?></td>
<td><?php echo htmlspecialchars($stream['form_slug']); ?></td>
<td><?php echo htmlspecialchars($stream['organization_slug']); ?></td>
Expand All @@ -94,6 +124,8 @@ class="btn btn-primary" target="_blank">Mire d'authorisation</a>
</tbody>
</table>
</div>

<script src="/node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
</body>

</html>
23 changes: 17 additions & 6 deletions admin/widget_edit.php
Original file line number Diff line number Diff line change
@@ -1,15 +1,27 @@
<?php
require '../app/Config.php';

$canAccess = isset($_SESSION['user_email']) ||
in_array($_SERVER['REMOTE_ADDR'], Config::getInstance()->haIps);

if(!$canAccess) {
header("Location: /index.php");
}

$repository = Config::getInstance()->repo;
$fileManager = Config::getInstance()->fileManager;

// Récupérer le GUID depuis l'URL et le convertir en binaire
$guidHex = $_GET['charityStreamId'] ?? '';
if (!$guidHex) {
die("GUID manquant ou incorrect.");
if(isset($_SESSION['user_email'])) {
$charityStreams = $repository->getCharityStreamByEmail($_SESSION['user_email']);
$guidBinary = $charityStreams[0]['guid'];
$guidHex = bin2hex($charityStreams[0]['guid']);
} else {
$guidHex = $_GET['charityStreamId'] ?? '';
if (!$guidHex) {
die("GUID manquant ou incorrect.");
}
$guidBinary = hex2bin($guidHex);
}
$guidBinary = hex2bin($guidHex);

$charityStream = $repository->getCharityStreamByGuidDB($guidBinary);
$donationGoalWidget = $repository->getDonationGoalWidgetByGuidDB($guidBinary);
Expand Down Expand Up @@ -46,7 +58,6 @@

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Édition</title>
<link rel="stylesheet" href="/node_modules/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="/css/main.min.css">
Expand Down
2 changes: 2 additions & 0 deletions app/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ class Config
public $fileManager = null;
public $encryptionKey = null;
public $haUrl = null;
public $haIps = null;
public $webSiteDomain = null;

private function getDb()
Expand Down Expand Up @@ -59,6 +60,7 @@ private function __construct()
$this->encryptionKey = $_ENV['ENCRYPTION_KEY'];

$this->haUrl = $_ENV['HA_URL'];
$this->haIps = isset($_ENV['HA_IPS']) ? explode(",", $_ENV['HA_IPS']) : [];
$this->webSiteDomain = $_ENV['WEBSITE_DOMAIN'];
}

Expand Down
57 changes: 51 additions & 6 deletions app/Repository.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,21 +20,28 @@ function getCharityStreamsListDB()

function getCharityStreamByGuidDB($guidBinary)
{
$stmt = $this->db->prepare('SELECT * FROM ' . $this->prefix . 'charity_stream WHERE guid = ? LIMIT 1');
$stmt = $this->db->prepare('SELECT * FROM ' . $this->prefix . 'charity_stream WHERE guid = ?');
$stmt->execute([$guidBinary]);
return $stmt->fetch();
}

function getCharityStreamByEmail($email)
{
$stmt = $this->db->prepare('SELECT * FROM ' . $this->prefix . 'charity_stream WHERE owner_email = ?');
$stmt->execute([$email]);
return $stmt->fetchAll();
}

function getDonationGoalWidgetByGuidDB($guidBinary)
{
$stmt = $this->db->prepare('SELECT * FROM ' . $this->prefix . 'widget_donation_goal_bar WHERE charity_stream_guid = ? LIMIT 1');
$stmt = $this->db->prepare('SELECT * FROM ' . $this->prefix . 'widget_donation_goal_bar WHERE charity_stream_guid = ?');
$stmt->execute([$guidBinary]);
return $stmt->fetch();
}

function getAlertBoxWidgetByGuidDB($guidBinary)
{
$stmt = $this->db->prepare('SELECT * FROM ' . $this->prefix . 'widget_alert_box WHERE charity_stream_guid = ? LIMIT 1');
$stmt = $this->db->prepare('SELECT * FROM ' . $this->prefix . 'widget_alert_box WHERE charity_stream_guid = ?');
$stmt->execute([$guidBinary]);
return $stmt->fetch();
}
Expand Down Expand Up @@ -97,6 +104,16 @@ function updateAlertBoxWidgetDB($guidBinary, $postData, $image = null, $sound =

function createCharityStreamDB($guid, $owner_email, $form_slug, $organization_slug, $title)
{
$password = Helpers::generateRandomString(30);

$query = 'INSERT INTO ' . $this->prefix . 'users (email, password)
VALUES (:email, :password)';
$stmt = $this->db->prepare($query);
$stmt->execute([
':email' => $owner_email,
':password' => password_hash($password, PASSWORD_DEFAULT)
]);

$query = 'INSERT INTO ' . $this->prefix . 'charity_stream (guid, owner_email, form_slug, organization_slug, title, state)
VALUES (:guid, :owner_email, :form_slug, :organization_slug, :title, 1)';
$stmt = $this->db->prepare($query);
Expand All @@ -121,6 +138,34 @@ function createCharityStreamDB($guid, $owner_email, $form_slug, $organization_sl
$stmt->execute([
':guid' => hex2bin($guid)
]);

// This seems to be a bad pratice but we will display password to user only one time
// Consider it like a secret key revealed one time at creation
// Only way to recover is to regenerate new one
return $password;
}

function getUser($email)
{
$stmt = $this->db->prepare('SELECT * FROM ' . $this->prefix . 'users WHERE email = ?');
$stmt->execute([$email]);
return $stmt->fetch();
}

function updateUserPassword($email)
{
$password = Helpers::generateRandomString(30);

$query = 'UPDATE ' . $this->prefix . 'users
SET password = :password
WHERE email = :email';
$stmt = $this->db->prepare($query);
$stmt->execute([
':email' => $email,
':password' => password_hash($password, PASSWORD_DEFAULT)
]);

return $password;
}

function insertAccessTokenDB($accessToken, $refreshToken, $organization_slug, $accessTokenExpiresAt, $refreshTokenExpiresAt)
Expand Down Expand Up @@ -198,12 +243,12 @@ function getAccessTokensDB($organization_slug)
{
if (is_null($organization_slug)) {
$query = 'SELECT * FROM ' . $this->prefix . 'access_token_partner_organization
WHERE organization_slug IS NULL LIMIT 1';
WHERE organization_slug IS NULL';
$stmt = $this->db->prepare($query);
$stmt->execute();
} else {
$query = 'SELECT * FROM ' . $this->prefix . 'access_token_partner_organization
WHERE organization_slug = :organization_slug LIMIT 1';
WHERE organization_slug = :organization_slug';
$stmt = $this->db->prepare($query);
$stmt->execute([
':organization_slug' => $organization_slug
Expand All @@ -216,7 +261,7 @@ function getAccessTokensDB($organization_slug)

function getAuthorizationCodeByIdDB($id)
{
$query = 'SELECT * FROM ' . $this->prefix . 'authorization_code WHERE id = ? LIMIT 1';
$query = 'SELECT * FROM ' . $this->prefix . 'authorization_code WHERE id = ?';
$stmt = $this->db->prepare($query);
$stmt->execute([$id]);
return $stmt->fetch();
Expand Down
50 changes: 50 additions & 0 deletions index.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php

require 'app/Config.php';

$repository = Config::getInstance()->repo;

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'] ?? '';
$password = $_POST['password'] ?? '';

$user = $repository->getUser($username);

if ($user && password_verify($password, $user['password'])) {
$_SESSION['user_email'] = $user['email'];
header('Location: /admin/widget_edit.php');
exit;
} else {
echo '<div class="alert alert-danger" role="alert">Email ou mot de passe invalide 😞</div>';
}
}
?>

<!DOCTYPE html>

<html lang="fr">

<head>
<meta charset="UTF-8">
<title>Connexion</title>
<link rel="stylesheet" href="/node_modules/bootstrap/dist/css/bootstrap.min.css">
</head>

<body>
<div class="container">
<h2>Connexion</h2>
<form action="index.php" method="POST">
<div class="form-group">
<label for="username">Email</label>
<input type="text" class="form-control" id="username" name="username" required>
</div>
<div class="form-group">
<label for="password">Mot de passe</label>
<input type="password" class="form-control" id="password" name="password" required>
</div>
<button type="submit" class="btn btn-primary">🚀</button>
</form>
</div>
</body>

</html>
9 changes: 9 additions & 0 deletions migration/02-add-user-table.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
CREATE TABLE {prefix}users (
id INT AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
creation_date DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
last_update DATETIME(6) DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6) NOT NULL
);

ALTER TABLE ADD CONSTRAINT fk_{prefix}charity_stream_users FOREIGN KEY (owner_email) REFERENCES {prefix}users(email),
1 change: 0 additions & 1 deletion widget_alert_box.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Alert Box Widget</title>
<link rel="stylesheet" href="/css/main.min.css">
</head>
Expand Down
1 change: 0 additions & 1 deletion widget_donation_goal.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Donation Goal Widget</title>
<link rel="stylesheet" href="/css/main.min.css">
</head>
Expand Down

0 comments on commit 865d53a

Please sign in to comment.