premier commit
This commit is contained in:
commit
394055b19b
9 changed files with 579 additions and 0 deletions
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
test_creds.php
|
171
api.md
Normal file
171
api.md
Normal file
|
@ -0,0 +1,171 @@
|
|||
# API PHP
|
||||
|
||||
Ce document décrit le comportement de l'api utilisée par le site
|
||||
|
||||
## Endpoints
|
||||
|
||||
### Authentification
|
||||
|
||||
- **Endpoint:** `auth.php?auth`
|
||||
- **Description:** Authentifie l'utilisateur et initialise une session.
|
||||
- **Méthode HTTP:** GET
|
||||
- **Réponse JSON:**
|
||||
```json
|
||||
{
|
||||
"status": 1,
|
||||
"msg": "Authentification réussie."
|
||||
}
|
||||
```
|
||||
En cas d'erreur :
|
||||
```json
|
||||
{
|
||||
"status": 0,
|
||||
"msg": "Erreur pendant le traitement de la requête."
|
||||
}
|
||||
|
||||
### Déconnexion
|
||||
|
||||
- **Endpoint:** `auth.php?unauth`
|
||||
- **Description:** Déconnecte l'utilisateur en mettant fin à la session.
|
||||
- **Méthode HTTP:** GET
|
||||
- **Réponse JSON:**
|
||||
```json
|
||||
{
|
||||
"status": 1,
|
||||
"msg": "Déconnexion réussie."
|
||||
}
|
||||
```
|
||||
|
||||
### Test d'authentification
|
||||
|
||||
- **Endpoint:** `auth.php?test_auth`
|
||||
- **Description:** Vérifie si l'utilisateur est authentifié.
|
||||
- **Méthode HTTP:** GET
|
||||
- **Réponse JSON:**
|
||||
- Si l'utilisateur est authentifié :
|
||||
```json
|
||||
{
|
||||
"status": 1,
|
||||
"msg": "Utilisateur bien authentifié."
|
||||
}
|
||||
```
|
||||
- Si l'utilisateur n'est pas authentifié :
|
||||
```json
|
||||
{
|
||||
"status": 4,
|
||||
"msg": "Utilisateur non authentifié."
|
||||
}
|
||||
```
|
||||
|
||||
## Statuts de réponse
|
||||
|
||||
- **Status 1 :** Requête valide.
|
||||
- **Status 0 :** Erreur pendant le traitement de la requête.
|
||||
- **Status 2 :** Requête invalide.
|
||||
- **Status 3 :** Session expirée.
|
||||
- **Status 4 :** Utilisateur non authentifié, requête interdite.
|
||||
|
||||
## Gestion des sessions
|
||||
|
||||
Le fichier `session_verif.php` est inclus pour la gestion des sessions. Assurez-vous qu'il est présent et correctement configuré.
|
||||
|
||||
---
|
||||
|
||||
**Remarque :** Ce document est une documentation basique. Assurez-vous d'ajuster et d'améliorer la sécurité en fonction des besoins spécifiques de votre application.
|
||||
|
||||
|
||||
## upload de plusieurs fichiers :
|
||||
|
||||
```javascript
|
||||
async function uploadMultiple(donneesFormulaires) {
|
||||
try {
|
||||
const reponse = await fetch("https://example.com/api", {
|
||||
method: "POST",
|
||||
body: donneesFormulaires,
|
||||
});
|
||||
const resultat = await reponse.json();
|
||||
console.log("Réussite :", resultat);
|
||||
} catch (erreur) {
|
||||
console.error("Erreur :", erreur);
|
||||
}
|
||||
}
|
||||
|
||||
const docs = document.querySelector('input[type="file"][multiple]');
|
||||
const donneesFormulaires = new FormData();
|
||||
|
||||
donneesFormulaires.append("title", "documents");
|
||||
|
||||
for (const [i, doc] of Array.from(docs.files).entries()) {
|
||||
donneesFormulaires.append(`doc_${i}`, doc);
|
||||
}
|
||||
|
||||
uploadMultiple(donneesFormulaires);
|
||||
```
|
||||
|
||||
## upload de données json
|
||||
```javascript
|
||||
|
||||
async function postJSON(donnees) {
|
||||
try {
|
||||
const reponse = await fetch("https://example.com/profile", {
|
||||
method: "POST", // ou 'PUT'
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(donnees),
|
||||
});
|
||||
|
||||
const resultat = await reponse.json();
|
||||
console.log("Réussite :", resultat);
|
||||
} catch (erreur) {
|
||||
console.error("Erreur :", erreur);
|
||||
}
|
||||
}
|
||||
|
||||
const donnees = { login: "Jean Biche" };
|
||||
postJSON(donnees);
|
||||
|
||||
```
|
||||
|
||||
## récupérer des documents
|
||||
|
||||
``` javascript
|
||||
|
||||
async function fetchImage() {
|
||||
try {
|
||||
const response = await fetch("flowers.jpg");
|
||||
if (!response.ok) {
|
||||
throw new Error("La réponse n'est pas OK");
|
||||
}
|
||||
const myBlob = await response.blob();
|
||||
monImage.src = URL.createObjectURL(myBlob);
|
||||
} catch (error) {
|
||||
console.error("Un problème est survenu lors de la récupération :", error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
```
|
||||
|
||||
[source](https://developer.mozilla.org/fr/docs/Web/API/Fetch_API/Using_Fetch)
|
||||
|
||||
|
||||
## récupérer des données
|
||||
``` javascript
|
||||
|
||||
|
||||
async function test_auth(){
|
||||
resp = await fetch("/annales/api.php?test_auth");
|
||||
data = await resp.json();
|
||||
document.getElementById("user_status").innerText = data["msg"];
|
||||
}
|
||||
|
||||
async function unauthenticate_user(){
|
||||
resp = await fetch("/annales/api.php?unauth");
|
||||
data = await resp.json();
|
||||
if(data.status == 1){
|
||||
document.getElementById("user_status").innerText = data["msg"];
|
||||
}
|
||||
}
|
||||
|
||||
```
|
74
api.php
Normal file
74
api.php
Normal file
|
@ -0,0 +1,74 @@
|
|||
<?php
|
||||
session_start();
|
||||
|
||||
/*
|
||||
status :
|
||||
1 => Requète valide
|
||||
0 => Erreur pendant le traitement de la requète
|
||||
2 => Requète invalide
|
||||
3 => Session expirée
|
||||
4 => Utilisateur non authentifié, requète interdite
|
||||
|
||||
*/
|
||||
|
||||
include("session_verif.php");
|
||||
include("test_creds.php");
|
||||
include("bdd.php");
|
||||
|
||||
|
||||
// Get the requested URL
|
||||
$request_uri = $_SERVER['REQUEST_URI'];
|
||||
|
||||
// Split the URL into an array using the '/' delimiter
|
||||
$url_parts = explode('/', $request_uri);
|
||||
|
||||
// Remove empty elements from the array
|
||||
$url_parts = array_filter($url_parts);
|
||||
|
||||
// The first element is the base path (in this case, "/api")
|
||||
$base_path = array_shift($url_parts);
|
||||
|
||||
|
||||
if($_SERVER['REQUEST_METHOD'] === 'GET'){
|
||||
if(isset($_GET["auth"])){
|
||||
try{
|
||||
$_SESSION["utilisateur_authentifie"] = true;
|
||||
session_regenerate_id(true);
|
||||
$_SESSION["heure_debut"] = time();
|
||||
echo json_encode(["status"=>"1","msg"=>"Authentification réussie."]);
|
||||
}catch(Exception $e){
|
||||
echo( json_encode(["status"=> "0","msg"=> $e->getMessage() ]) );
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if(isset($_GET["unauth"])){
|
||||
$_SESSION["utilisateur_authentifie"] = false;
|
||||
echo json_encode(["status"=>"1","msg"=>"Déconnection réussie."]);
|
||||
session_destroy();
|
||||
session_abort();
|
||||
}
|
||||
|
||||
if(isset($_GET["test_auth"])){
|
||||
if($_SESSION["utilisateur_authentifie"] == true){
|
||||
echo(json_encode(["status"=> "1","msg"=> "Utilisateur bien authentifié."]));
|
||||
}else{
|
||||
echo(json_encode(["status"=> "4","msg"=> "Utilisateur non authentifié."]));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
if($_SERVER['REQUEST_METHOD'] === 'POST'){
|
||||
switch(array_shift($url_parts)){
|
||||
case "aj_doc":
|
||||
ajouter_doc($_POST);
|
||||
break;
|
||||
default:
|
||||
echo(json_encode(["status"=> "2","msg"=> "Opération inconnue."]));
|
||||
}
|
||||
|
||||
}
|
||||
?>
|
56
bdd.php
Normal file
56
bdd.php
Normal file
|
@ -0,0 +1,56 @@
|
|||
<?php
|
||||
|
||||
$conn = new mysqli($servername, $username, $password, $dbname);
|
||||
|
||||
// Check connection
|
||||
if ($conn->connect_error) {
|
||||
die("Connection failed: " . $conn->connect_error);
|
||||
}
|
||||
|
||||
|
||||
function ajouter_doc($request){
|
||||
|
||||
saveFilesFromPost($request);
|
||||
|
||||
if (isset($request['files']) && is_array($request['files'])) {
|
||||
foreach ($request['files'] as $file) {
|
||||
$sql="INSERT INTO ";
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
function saveFilesFromPost($postData) {
|
||||
// Check if the $_POST variable is set and contains files
|
||||
if (isset($postData['files']) && is_array($postData['files'])) {
|
||||
// Directory to save the files
|
||||
$uploadDir = 'archives/';
|
||||
|
||||
// Iterate through each file in the $_POST['files'] array
|
||||
foreach ($postData['files'] as $file) {
|
||||
// Extract file information
|
||||
$fileName = $file['name'];
|
||||
$fileData = $file['data'];
|
||||
|
||||
// Decode base64 encoded file data
|
||||
$fileData = base64_decode($fileData);
|
||||
|
||||
// Create a unique filename to avoid overwriting existing files
|
||||
$uniqueFileName = uniqid() . '_' . $fileName;
|
||||
|
||||
// Define the path to save the file
|
||||
$filePath = $uploadDir . $uniqueFileName;
|
||||
|
||||
// Save the file
|
||||
if (file_put_contents($filePath, $fileData) !== false) {
|
||||
echo(json_encode(["status"=>"1","msg" =>"File '$uniqueFileName' has been saved successfully."]));
|
||||
} else {
|
||||
echo(json_encode(["status"=>"0","msg"=>"Error saving file '$uniqueFileName'"]));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
echo(json_encode(["status"=>"2","msg"=>"No files in the POST data."]));
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
49
index.php
Normal file
49
index.php
Normal file
|
@ -0,0 +1,49 @@
|
|||
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Document</title>
|
||||
</head>
|
||||
<body>
|
||||
<?php
|
||||
session_start();
|
||||
|
||||
?>
|
||||
<a href="javascript:authenticate_user();">connection</a>
|
||||
<a href="javascript:unauthenticate_user();">déconnection</a>
|
||||
|
||||
<div id="user_status">
|
||||
|
||||
</div>
|
||||
</body>
|
||||
<script>
|
||||
async function test_auth(){
|
||||
resp = await fetch("/annales/api.php?test_auth");
|
||||
data = await resp.json();
|
||||
document.getElementById("user_status").innerText = data["msg"];
|
||||
}
|
||||
|
||||
// fonction de test, innutile en prod
|
||||
async function authenticate_user(){
|
||||
resp = await fetch("/annales/api.php?auth");
|
||||
data = await resp.json();
|
||||
if(data.status == 1){
|
||||
document.getElementById("user_status").innerText = data["msg"];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async function unauthenticate_user(){
|
||||
resp = await fetch("/annales/api.php?unauth");
|
||||
data = await resp.json();
|
||||
if(data.status == 1){
|
||||
document.getElementById("user_status").innerText = data["msg"];
|
||||
}
|
||||
}
|
||||
|
||||
test_auth();
|
||||
|
||||
</script>
|
||||
</html>
|
70
init_db.php
Normal file
70
init_db.php
Normal file
|
@ -0,0 +1,70 @@
|
|||
<?php
|
||||
// Database connection parameters
|
||||
$servername = "127.0.0.1";
|
||||
$username = "root";
|
||||
$password = "";
|
||||
$dbname = "archivinsa";
|
||||
|
||||
// Create connection
|
||||
$conn = new mysqli($servername, $username, $password, $dbname);
|
||||
|
||||
// Check connection
|
||||
if ($conn->connect_error) {
|
||||
die("Connection failed: " . $conn->connect_error);
|
||||
}
|
||||
|
||||
// Create tables
|
||||
$sql = "
|
||||
CREATE TABLE IF NOT EXISTS themes (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
name VARCHAR(255) NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS ensemble (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
commentaire_auteur TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS documents (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
titre VARCHAR(255) NOT NULL,
|
||||
type INT,
|
||||
upload_path TEXT NOT NULL,
|
||||
commentaire_auteur TEXT,
|
||||
ensemble_id INT,
|
||||
theme_id INT,
|
||||
FOREIGN KEY (theme_id) REFERENCES themes(id),
|
||||
FOREIGN KEY (ensemble_id) REFERENCES ensemble(id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS exercices (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
titre VARCHAR(255) NOT NULL,
|
||||
commentaire_auteur TEXT,
|
||||
document_id INT,
|
||||
FOREIGN KEY (document_id) REFERENCES documents(id)
|
||||
);
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS exercices_themes (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
exercice_id INT,
|
||||
theme_id INT,
|
||||
FOREIGN KEY (exercice_id) REFERENCES exercices(id),
|
||||
FOREIGN KEY (theme_id) REFERENCES themes(id)
|
||||
);
|
||||
|
||||
|
||||
|
||||
|
||||
";
|
||||
|
||||
if ($conn->multi_query($sql) === TRUE) {
|
||||
echo "Tables created successfully";
|
||||
} else {
|
||||
echo "Error creating tables: " . $conn->error;
|
||||
}
|
||||
|
||||
// Close the connection
|
||||
$conn->close();
|
||||
?>
|
48
readme.md
Normal file
48
readme.md
Normal file
|
@ -0,0 +1,48 @@
|
|||
# Arch'insa
|
||||
Ce site a pour but à therme de remplacer le site actuel des annales de L'INSA Toulouse, avec une recherche par themes/classes/temps de résolution, la possibilité de prendre directement des photos de son exercice pour le téléverser et d'envoyer toutes sortes de supports tels que des fiches de cours. Des commentaires seront aussi disponibles pour les auteurs pour donner un contexte ou des indications sur un exercice en particulier, ou un paquet de documents en entier.
|
||||
D'autres fonctionnalités seront ajoutées petit à petit. (si vous avez des suggestions, n'hésitez pas à contacter le club info ou moi directement)
|
||||
|
||||
|
||||
## structure bdd
|
||||
### Table: themes
|
||||
|
||||
| Column | Type | Constraints |
|
||||
|--------|-----------------|--------------------------|
|
||||
| id | INT | AUTO_INCREMENT, PRIMARY KEY |
|
||||
| name | VARCHAR(255) | NOT NULL |
|
||||
|
||||
### Table: exercices_themes
|
||||
|
||||
| Column | Type | Constraints |
|
||||
|--------------|--------|-------------------------------------------|
|
||||
| exercice_id | INT | FOREIGN KEY (exercice_id) REFERENCES exercises(id) |
|
||||
| theme_id | INT | FOREIGN KEY (theme_id) REFERENCES themes(id) |
|
||||
| PRIMARY KEY | | (exercice_id, theme_id) |
|
||||
|
||||
### Table: exercices
|
||||
|
||||
| Column | Type | Constraints |
|
||||
|--------------------|---------------|------------------------------------------|
|
||||
| id | INT | AUTO_INCREMENT, PRIMARY KEY |
|
||||
| titre | VARCHAR(255) | NOT NULL |
|
||||
| commentaire_auteur | TEXT | |
|
||||
| document_id | INT | FOREIGN KEY (document_id) REFERENCES documents(id) |
|
||||
|
||||
### Table: ensemble
|
||||
|
||||
| Column | Type | Constraints |
|
||||
|--------------------|---------------|------------------------------------------|
|
||||
| id | INT | AUTO_INCREMENT |
|
||||
| commentaire_auteur | TEXT | |
|
||||
|
||||
### Table: documents
|
||||
|
||||
| Column | Type | Constraints |
|
||||
|--------------------|---------------|------------------------------------------|
|
||||
| id | INT | AUTO_INCREMENT, PRIMARY KEY |
|
||||
| titre | VARCHAR(255) | NOT NULL |
|
||||
| type | INT | |
|
||||
| upload_path | TEXT | NOT NULL |
|
||||
| commentaire_auteur | TEXT | |
|
||||
| ensemble_id | INT | FOREIGN KEY (ensemble_id) REFERENCES ensemble(id) |
|
||||
| theme_id | INT | FOREIGN KEY (theme_id) REFERENCES themes(id) |
|
13
session_verif.php
Normal file
13
session_verif.php
Normal file
|
@ -0,0 +1,13 @@
|
|||
<?php
|
||||
session_start();
|
||||
|
||||
if(isset($_SESSION["utilisateur_authentifie"])){
|
||||
// vérifie que la session ne dépasse pas 4h
|
||||
if((time() - $_SESSION["heure_debut"]) > 3600*4){
|
||||
session_destroy();
|
||||
session_abort();
|
||||
echo(json_encode(array("status"=> "3","msg"=>"Session expirée, veuillez vous reconnecter.")));
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
97
televerser.php
Normal file
97
televerser.php
Normal file
|
@ -0,0 +1,97 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>File Upload</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<!-- Input to choose files -->
|
||||
<input type="file" id="fileInput" multiple>
|
||||
<button onclick="uploadFiles()">Upload Files</button>
|
||||
|
||||
<!-- Button to open the camera -->
|
||||
<button onclick="openCamera()">Open Camera</button>
|
||||
|
||||
<script>
|
||||
function uploadFiles() {
|
||||
const fileInput = document.getElementById('fileInput');
|
||||
|
||||
// Create FormData object to append files
|
||||
const formData = new FormData();
|
||||
|
||||
// Append each selected file to the FormData
|
||||
for (const file of fileInput.files) {
|
||||
formData.append('files[]', file);
|
||||
}
|
||||
|
||||
// Make a POST request using Fetch API
|
||||
fetch('annales/api.php/aj_doc.php', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
console.log(data);
|
||||
// Handle the response from the server
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error:', error);
|
||||
});
|
||||
}
|
||||
|
||||
function openCamera() {
|
||||
// Open the camera and take pictures
|
||||
// You can use the MediaDevices API to access the camera
|
||||
navigator.mediaDevices.getUserMedia({ video: true })
|
||||
.then(mediaStream => {
|
||||
const video = document.createElement('video');
|
||||
document.body.appendChild(video);
|
||||
|
||||
// Display the camera stream in a video element
|
||||
video.srcObject = mediaStream;
|
||||
video.play();
|
||||
|
||||
// Capture an image from the video stream
|
||||
video.addEventListener('click', () => {
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = video.videoWidth;
|
||||
canvas.height = video.videoHeight;
|
||||
const context = canvas.getContext('2d');
|
||||
context.drawImage(video, 0, 0, canvas.width, canvas.height);
|
||||
|
||||
// Convert the canvas content to a data URL
|
||||
const imageDataUrl = canvas.toDataURL('image/jpeg');
|
||||
|
||||
// Close the camera stream
|
||||
mediaStream.getTracks().forEach(track => track.stop());
|
||||
|
||||
// Make a POST request to upload the image
|
||||
fetch('annales/api.php/aj_doc', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
files: [{ name: 'camera_image.jpg', data: imageDataUrl.split(',')[1] }]
|
||||
})
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
console.log(data);
|
||||
// Handle the response from the server
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error:', error);
|
||||
});
|
||||
});
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error accessing camera:', error);
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
Loading…
Reference in a new issue