From 924729923c0be95aef8c6a98b060dbdf59fa8b49 Mon Sep 17 00:00:00 2001 From: javdiaort <javdiaort@alum.us.es> Date: Wed, 19 Mar 2025 11:09:02 +0100 Subject: [PATCH] work done --- public/home.css | 97 ++++++++++++++++++++++++++++++++++++++++++++++++ src/index.js | 55 ++++++++++++++++++++------- src/taskModel.js | 9 +++-- views/home.ejs | 50 +++++++++++++++++-------- 4 files changed, 179 insertions(+), 32 deletions(-) create mode 100644 public/home.css diff --git a/public/home.css b/public/home.css new file mode 100644 index 0000000..84129fc --- /dev/null +++ b/public/home.css @@ -0,0 +1,97 @@ +body { + font-family: Arial, sans-serif; + background-color: #f4f4f4; + margin: 0; + padding: 0; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + height: 100vh; +} + +h1 { + color: #333; +} + +.container { + background: white; + padding: 20px; + border-radius: 10px; + box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1); + width: 350px; + text-align: center; +} + +ul { + list-style: none; + padding: 0; +} + +li { + background: #e3f2fd; + margin: 10px 0; + padding: 10px; + border-radius: 5px; + font-size: 16px; + display: flex; + justify-content: space-between; + align-items: center; +} + +.completed { + text-decoration: line-through; + color: #777; +} + +.task-date { + font-size: 12px; + color: #777; +} + +form { + display: inline; +} + +button { + background: #007bff; + color: white; + border: none; + padding: 5px 10px; + cursor: pointer; + border-radius: 5px; +} + +button:hover { + background: #0056b3; +} + +.delete-btn { + background: #dc3545; +} + +.delete-btn:hover { + background: #c82333; +} + +.complete-btn { + background: #28a745; +} + +.complete-btn:hover { + background: #218838; +} + +.logout { + display: block; + margin-top: 15px; + color: white; + text-decoration: none; + background: #dc3545; + padding: 8px 12px; + border-radius: 5px; +} + +.logout:hover { + background: #c82333; +} \ No newline at end of file diff --git a/src/index.js b/src/index.js index d6bbf88..3c86434 100644 --- a/src/index.js +++ b/src/index.js @@ -1,23 +1,21 @@ const express = require('express'); -const pasth = require('path'); const bcrypt = require('bcrypt'); -const bcrypt2 = require('bcryptjs'); const collection=require("./config"); -const Task = require('./taskModel'); // Asegúrate de requerir el modelo de Task +const Task = require('./taskModel'); const app = express(); const session = require("express-session"); const MongoStore = require("connect-mongo"); const mongoose = require("mongoose"); app.use(session({ - secret: "tuClaveSecreta", // Cambia esto por una clave segura + secret: "tuClaveSecreta", // Clave secreta para firmar la cookie de sesión resave: false, saveUninitialized: false, store: MongoStore.create({ - mongoUrl: 'mongodb://localhost:27017/Login', // Tu conexión a MongoDB + mongoUrl: 'mongodb://localhost:27017/Login', //conexion a la base de datos collectionName: "sessions" }), - cookie: { maxAge: 1000 * 60 * 60 * 24 } // 1 dÃa + cookie: { maxAge: 1000 * 60 * 60 * 24 } // 1 dÃa por ejemplo })); @@ -29,12 +27,15 @@ app.use(express.urlencoded({extended: false})); app.use(express.static('public')); +//render things and endpoints app.set('view engine','ejs' ) app.get("/", (req, res)=> { res.render("login") }); - +app.get("/login", (req, res) => { + res.render("login"); +}); app.get("/signup", (req,res)=>{ res.render("signup") }); @@ -52,7 +53,6 @@ const existingUser= await collection.findOne({name: data.name}); if(existingUser){ res.send("User already exists. Please choose a different username") }else{ - res.send("User created") //hash de password unsing bcrypt const saltRounds =10; //number of salt rounds for bcrypy const hashedPassword = await bcrypt.hash(data.password, saltRounds); @@ -61,7 +61,8 @@ if(existingUser){ const userData = await collection.insertMany(data); - console.log(userData) + res.redirect("/login"); + // console.log(userData) } }) @@ -148,13 +149,39 @@ app.post("/add", async (req, res) => { //eliminar tareas app.post("/delete", async (req, res) => { - if (!req.session.userId) return res.redirect("/"); + try { + const { taskId } = req.body; + + // Eliminar la tarea de la base de datos + await Task.findByIdAndDelete(taskId); + + // Redirigir nuevamente a /home + res.redirect("/home"); + } catch (error) { + console.error("Error al eliminar tarea:", error); + res.status(500).send("Error al eliminar tarea"); + } +}); + +app.post("/complete", async (req, res) => { + try { + const { taskId } = req.body; - const user = await collection.findById(req.session.userId); - user.tasks = user.tasks.filter(task => task._id.toString() !== req.body.taskId); - await user.save(); + // Buscar la tarea y cambiar su estado (de true a false y viceversa) + const task = await Task.findById(taskId); + if (!task) { + return res.status(404).send("Tarea no encontrada"); + } - res.redirect("/todo"); + task.completed = !task.completed; // Cambia el estado de completado + await task.save(); + + // Redirigir nuevamente a /home + res.redirect("/home"); + } catch (error) { + console.error("Error al actualizar la tarea:", error); + res.status(500).send("Error al actualizar la tarea"); + } }); diff --git a/src/taskModel.js b/src/taskModel.js index c6764ba..9480b0c 100644 --- a/src/taskModel.js +++ b/src/taskModel.js @@ -12,11 +12,14 @@ const taskSchema = new mongoose.Schema({ userId: { type: mongoose.Schema.Types.ObjectId, // Referencia al usuario required: true, - ref: "users" // Esto indica que "userId" es una referencia a la colección "users" + ref: "users" + }, + completed: { + type: Boolean, + default: false // Por defecto, la tarea no está completada } }); -// Crear el modelo de la colección "tasks" const Task = mongoose.model("tasks", taskSchema); -module.exports = Task; \ No newline at end of file +module.exports = Task; diff --git a/views/home.ejs b/views/home.ejs index 50098a8..0abc658 100644 --- a/views/home.ejs +++ b/views/home.ejs @@ -4,25 +4,45 @@ <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Tu Lista de Tareas</title> + <link rel="stylesheet" href="home.css"> </head> <body> - <h1>Tu Lista de Tareas</h1> + <div class="container"> + <h1>Tu Lista de Tareas</h1> - <% if (tasks && tasks.length > 0) { %> - <ul> - <% tasks.forEach(task => { %> - <li><%= task.text %> - <%= task.createdAt.toLocaleString() %></li> - <% }); %> - </ul> - <% } else { %> - <p>No tienes tareas.</p> - <% } %> + <% if (tasks && tasks.length > 0) { %> + <ul> + <% tasks.forEach(task => { %> + <li class="<%= task.completed ? 'completed' : '' %>"> + <span><%= task.text %></span> + <span class="task-date"><%= task.createdAt.toLocaleString() %></span> - <form action="/add" method="POST"> - <input type="text" name="task" placeholder="Nueva tarea" required> - <button type="submit">Agregar tarea</button> - </form> + <!-- Formulario para marcar como completado --> + <form action="/complete" method="POST"> + <input type="hidden" name="taskId" value="<%= task._id %>"> + <button type="submit" class="complete-btn"> + <%= task.completed ? "Desmarcar" : "Completar" %> + </button> + </form> - <a href="/logout">Cerrar sesión</a> + <!-- Formulario para eliminar la tarea --> + <form action="/delete" method="POST"> + <input type="hidden" name="taskId" value="<%= task._id %>"> + <button type="submit" class="delete-btn">Eliminar</button> + </form> + </li> + <% }); %> + </ul> + <% } else { %> + <p>No tienes tareas.</p> + <% } %> + + <form action="/add" method="POST"> + <input type="text" name="task" placeholder="Nueva tarea" required> + <button type="submit">Agregar tarea</button> + </form> + + <a href="/logout" class="logout">Cerrar sesión</a> + </div> </body> </html> -- GitLab