Ajouter la génération et la lecture de la clé utilisateur (.papillon_id)

This commit is contained in:
2025-10-23 23:42:25 +02:00
parent b5f63df5c4
commit 8e25bb44eb
7 changed files with 259 additions and 94 deletions
+2 -2
View File
@@ -6,7 +6,7 @@ CREATE TABLE rappel (
theme VARCHAR(30),
rang INT
);
SS
-- Table utilisateur
CREATE TABLE utilisateur (
id INT AUTO_INCREMENT PRIMARY KEY,
@@ -16,6 +16,6 @@ CREATE TABLE utilisateur (
-- Ajouter la FK côté rappel
ALTER TABLE rappel
ADD COLUMN IF NOT EXISTS utilisateur_id INT,
ADD COLUMN utilisateur_id INT,
ADD CONSTRAINT fk_rappel_user FOREIGN KEY (utilisateur_id)
REFERENCES utilisateur(id) ON DELETE CASCADE;
+1 -89
View File
@@ -1,7 +1,4 @@
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class BaseDeDonnees {
@@ -9,8 +6,7 @@ public class BaseDeDonnees {
private static final String USER = "val";
private static final String PASS = "vali";
/** Connexion */
public static Connection getConnexion() throws SQLException {
public static java.sql.Connection getConnexion() throws java.sql.SQLException {
try {
Class.forName("org.mariadb.jdbc.Driver");
} catch (ClassNotFoundException e) {
@@ -18,88 +14,4 @@ public class BaseDeDonnees {
}
return DriverManager.getConnection(URL, USER, PASS);
}
/** Ajout dun rappel (INSERT) */
public static int ajouter(Rappel r) throws SQLException {
String sql = "INSERT INTO rappel(titre, contenu, theme, rang) VALUES (?, ?, ?, ?)";
Connection cnx = getConnexion();
PreparedStatement pst = cnx.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
pst.setString(1, r.getTitre());
pst.setString(2, r.getContenu());
pst.setString(3, r.getTheme());
pst.setInt(4, r.getRang());
pst.executeUpdate();
ResultSet rs = pst.getGeneratedKeys();
int id = 0;
if (rs.next()) {
id = rs.getInt(1);
r.setId(id);
}
rs.close();
pst.close();
cnx.close();
return id;
}
/** Liste des rappels */
public static List<Rappel> lister() throws SQLException {
String sql = "SELECT id, titre, contenu, theme, rang FROM rappel ORDER BY rang ASC, id ASC";
List<Rappel> res = new ArrayList<>();
Connection cnx = getConnexion();
PreparedStatement pst = cnx.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
while (rs.next()) {
Rappel r = new Rappel(
rs.getInt("id"),
rs.getString("titre"),
rs.getString("contenu"),
rs.getString("theme"),
rs.getInt("rang")
);
res.add(r);
}
rs.close();
pst.close();
cnx.close();
return res;
}
/** Modification dun rappel (UPDATE) */
public static int modifier(int id, Rappel r) throws SQLException {
String sql = "UPDATE rappel SET titre=?, contenu=?, theme=?, rang=? WHERE id=?";
Connection cnx = getConnexion();
PreparedStatement pst = cnx.prepareStatement(sql);
pst.setString(1, r.getTitre());
pst.setString(2, r.getContenu());
pst.setString(3, r.getTheme());
pst.setInt(4, r.getRang());
pst.setInt(5, id);
int rows = pst.executeUpdate();
pst.close();
cnx.close();
return rows;
}
/** Suppression dun rappel (DELETE) */
public static int supprimer(int id) throws SQLException {
String sql = "DELETE FROM rappel WHERE id=?";
Connection cnx = getConnexion();
PreparedStatement pst = cnx.prepareStatement(sql);
pst.setInt(1, id);
int rows = pst.executeUpdate();
pst.close();
cnx.close();
return rows;
}
}
@@ -0,0 +1,32 @@
public class FichierDemarrage {
public static void main(String[] args) {
try {
String cle = UserKey.lireOuCreerCle();
int userId = UtilisateurBD.getOrCreateUserId(cle, "local_user");
// Démo rapide
Rappel r = new Rappel("Faire le TD", "chapitre JDBC", "Travail", 2);
int idNew = RappelBD.ajouterPourUtilisateur(userId, r);
for (Rappel x : RappelBD.listerParUtilisateur(userId)) {
System.out.println(" - " + x.toString());
}
r.setTitre("Faire le TD (MAJ)");
RappelBD.modifierPourUtilisateur(userId, r.getId(), r);
for (Rappel x : RappelBD.listerParUtilisateur(userId)) {
System.out.println(" * " + x.toString());
}
RappelBD.supprimerPourUtilisateur(userId, r.getId());
for (Rappel x : RappelBD.listerParUtilisateur(userId)) {
System.out.println(" # " + x.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
+94
View File
@@ -0,0 +1,94 @@
import java.util.ArrayList;
import java.util.List;
import java.sql.*;
public class RappelBD {
public static int ajouterPourUtilisateur(int utilisateurId, Rappel r) throws SQLException {
String sql = "INSERT INTO rappel(titre, contenu, theme, rang, utilisateur_id) VALUES (?, ?, ?, ?, ?)";
Connection cnx = BaseDeDonnees.getConnexion();
PreparedStatement pst = cnx.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
pst.setString(1, r.getTitre());
pst.setString(2, r.getContenu());
pst.setString(3, r.getTheme());
pst.setInt(4, r.getRang());
pst.setInt(5, utilisateurId);
pst.executeUpdate();
int id = 0;
ResultSet rs = pst.getGeneratedKeys();
if (rs.next()) {
id = rs.getInt(1);
r.setId(id);
}
rs.close();
pst.close();
cnx.close();
return id;
}
public static List<Rappel> listerParUtilisateur(int utilisateurId) throws SQLException {
String sql = "SELECT id, titre, contenu, theme, rang FROM rappel WHERE utilisateur_id=? ORDER BY rang ASC, id ASC";
Connection cnx = BaseDeDonnees.getConnexion();
PreparedStatement pst = cnx.prepareStatement(sql);
pst.setInt(1, utilisateurId);
ResultSet rs = pst.executeQuery();
List<Rappel> res = new ArrayList<Rappel>();
while (rs.next()) {
Rappel r = new Rappel(
rs.getInt("id"),
rs.getString("titre"),
rs.getString("contenu"),
rs.getString("theme"),
rs.getInt("rang")
);
res.add(r);
}
rs.close();
pst.close();
cnx.close();
return res;
}
public static int modifierPourUtilisateur(int utilisateurId, int idRappel, Rappel r) throws SQLException {
String sql = "UPDATE rappel SET titre=?, contenu=?, theme=?, rang=? WHERE id=? AND utilisateur_id=?";
Connection cnx = BaseDeDonnees.getConnexion();
PreparedStatement pst = cnx.prepareStatement(sql);
pst.setString(1, r.getTitre());
pst.setString(2, r.getContenu());
pst.setString(3, r.getTheme());
pst.setInt(4, r.getRang());
pst.setInt(5, idRappel);
pst.setInt(6, utilisateurId);
int rows = pst.executeUpdate();
pst.close();
cnx.close();
return rows;
}
public static int supprimerPourUtilisateur(int utilisateurId, int idRappel) throws SQLException {
String sql = "DELETE FROM rappel WHERE id=? AND utilisateur_id=?";
Connection cnx = BaseDeDonnees.getConnexion();
PreparedStatement pst = cnx.prepareStatement(sql);
pst.setInt(1, idRappel);
pst.setInt(2, utilisateurId);
int rows = pst.executeUpdate();
pst.close();
cnx.close();
return rows;
}
}
+51
View File
@@ -0,0 +1,51 @@
import java.io.*;
import java.util.UUID;
public class UserKey {
/**
Lit la clé stockée dans le fichier ~/.papillon_id
ou en génère une nouvelle si le fichier n'existe pas.
@return La clé utilisateur sous forme de chaîne de caractères
*/
public static String lireOuCreerCle() {
// Récupère le dossier personnel de lutilisateur
String home = System.getProperty("user.home");
File fichier = new File(home, ".papillon_id");
String cle = "";
try {
// Si le fichier existe déjà on lit son contenu
if (fichier.exists()) {
FileReader fr = new FileReader(fichier);
BufferedReader br = new BufferedReader(fr);
cle = br.readLine(); // lit la première ligne (la clé)
br.close();
fr.close();
System.out.println("Clé existante trouvée : " + cle);
}
// Sinon, on génère une nouvelle clé et on l’écrit dans le fichier
else {
cle = UUID.randomUUID().toString(); // Génère une clé unique
FileWriter fw = new FileWriter(fichier);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(cle);
bw.newLine();
bw.close();
fw.close();
System.out.println("Nouvelle clé générée et enregistrée : " + cle);
}
} catch (IOException e) {
System.err.println("Erreur lors de la lecture/écriture du fichier de clé : " + e.getMessage());
}
return cle;
}
}
@@ -0,0 +1,27 @@
public class Utilisateur {
private int id;
private String nom;
private String cleUnique;
public Utilisateur(int id, String nom, String cleUnique) {
this.id = id;
this.nom = nom;
this.cleUnique = cleUnique;
}
public Utilisateur(String nom, String cleUnique) {
this(0, nom, cleUnique);
}
public int getId() { return id; }
public String getNom() { return nom; }
public String getCleUnique() { return cleUnique; }
public void setId(int id) { this.id = id; }
public void setNom(String nom) { this.nom = nom; }
public void setCleUnique(String cleUnique) { this.cleUnique = cleUnique; }
public String toString() {
return "[id=" + id + "] nom=" + nom + " cle=" + cleUnique;
}
}
@@ -0,0 +1,49 @@
import java.sql.*;
public class UtilisateurBD {
public static int getUserIdByKey(String cle) throws java.sql.SQLException {
String sql = "SELECT id FROM utilisateur WHERE cle_unique = ?";
Connection cnx = BaseDeDonnees.getConnexion();
PreparedStatement pst = cnx.prepareStatement(sql);
pst.setString(1, cle);
ResultSet rs = pst.executeQuery();
int id = -1;
if (rs.next()){
id = rs.getInt("id");
}
rs.close();
pst.close();
cnx.close();
return id;
}
public static int creerUtilisateur(String nom, String cle) throws java.sql.SQLException {
String sql = "INSERT INTO utilisateur(nom, cle_unique) VALUES (?, ?)";
java.sql.Connection cnx = BaseDeDonnees.getConnexion();
java.sql.PreparedStatement pst = cnx.prepareStatement(sql, java.sql.Statement.RETURN_GENERATED_KEYS);
pst.setString(1, nom);
pst.setString(2, cle);
pst.executeUpdate();
int id = -1;
java.sql.ResultSet rs = pst.getGeneratedKeys();
if (rs.next()) id = rs.getInt(1);
rs.close();
pst.close();
cnx.close();
return id;
}
public static int getOrCreateUserId(String cle, String nomParDefaut) throws java.sql.SQLException {
int id = getUserIdByKey(cle);
if (id != -1){
return id;
}
return creerUtilisateur(nomParDefaut, cle);
}
}