Commit e6d12607 by Juan Montilla

Foto de perfil y recetas asociadas a usuarios

parent b09851d8
......@@ -37,23 +37,38 @@ $routes->match(['get', 'post'], '/loginAjax', [User::class, 'loginAjax']);
$routes->match(['get', 'post'], '/registerAjax', [User::class, 'registerAjax']);
$routes->match(['get'], '/home', [User::class, 'user_ok']);
// Ruta para boorar una receta dada un id
$routes->get('/recipes/delete/(:num)', 'RecipesController::delete/$1');
// Ruta cuando se cierra la sesión
$routes->get('/logout', 'User::logout');
// Ruta para ver una receta
$routes->get('/recipe/(:num)', 'RecipesController::view_recipe/$1');
// Ruta para obtener una imagen de una receta dado un id
$routes->get('recipe/image/(:num)', 'RecipesController::show_image/$1');
// Ruta para obtener un nombre de usuario dado un email
$routes->get('username/(:any)', 'User::show_name/$1');
// Rutas para formulario de ingresar recetas
$routes->get('/insert_recipe', 'InsertRecipeController::index');
$routes->get('/insert_recipe', 'InsertRecipeController::index', ['filter' => 'user_auth']);
$routes->match(['get', 'post'], '/search_ingredient', 'InsertRecipeController::search_ingredient');
$routes->post('/insert_recipe', 'InsertRecipeController::insert_recipe');
// Ruta para la búsqueda de recetas
$routes->match(['get', 'post'], '/search_recipe', 'RecipesController::search_recipe');
// Ruta para vista "Mis recetas"
$routes->get('/myrecipes', 'User::personalRecipes', ['filter' => 'user_auth']);
// Ruta para vista "Mi perfil"
$routes->get('/profile', 'User::myprofile', ['filter' => 'user_auth']);
$routes->post('/cambiarFoto', 'User::changeProfilePhoto');
$routes->get('login','Pages::viewLogin');
$routes->get('users','User::list');
$routes->get('users', 'User::list', ['filter' => 'admin_auth']);
$routes->get('home','Pages::prueba');
$routes->get('(:segment)', 'Home::index');
......
......@@ -28,39 +28,47 @@ class InsertRecipeController extends Controller
}
public function insert_recipe()
{
// Cargar los modelos necesarios
$recipeModel = new \App\Models\RecipesModel();
$recipesIngredientModel = new \App\Models\RecipesIngredientModel();
{
// Cargar los modelos necesarios
$recipeModel = new \App\Models\RecipesModel();
$recipesIngredientModel = new \App\Models\RecipesIngredientModel();
// Obtener los datos del formulario
$recipeData = $this->request->getPost();
$selectedIngredients = json_decode($recipeData['selected_ingredients'], true);
// Obtener los datos del formulario
$recipeData = $this->request->getPost();
$selectedIngredients = json_decode($recipeData['selected_ingredients'], true);
// Eliminar el elemento 'selected_ingredients' de los datos de la receta
unset($recipeData['selected_ingredients']);
// Eliminar el elemento 'selected_ingredients' de los datos de la receta
unset($recipeData['selected_ingredients']);
// Manejar el archivo de imagen
$photo = $this->request->getFile('photo');
if ($photo->isValid() && !$photo->hasMoved()) {
$photoBlob = file_get_contents($photo->getRealPath());
$recipeData['photo'] = $photoBlob;
}
// Manejar el archivo de imagen
$photo = $this->request->getFile('photo');
if ($photo->isValid() && !$photo->hasMoved()) {
$photoBlob = file_get_contents($photo->getRealPath());
$recipeData['photo'] = $photoBlob;
}
// Obtener el email del usuario de la sesión
$session = session();
$userEmail = $session->get('user')->email;
// Insertar la receta en la tabla 'recipes'
$recipeId = $recipeModel->insert($recipeData);
// Agregar el email del usuario a los datos de la receta
$recipeData['email_user'] = $userEmail;
// Insertar los ingredientes seleccionados y sus cantidades en la tabla 'recipes_ingredient'
foreach ($selectedIngredients as $ingredient) {
$recipesIngredientModel->insert([
'id_recipe' => $recipeId,
'id_ingredient' => $ingredient['id'],
'amount' => $ingredient['amount']
]);
}
// Insertar la receta en la tabla 'recipes'
$recipeId = $recipeModel->insert($recipeData);
// Redireccionar a la página principal (o cualquier otra página que desees)
return redirect()->to('/home');
// Insertar los ingredientes seleccionados y sus cantidades en la tabla 'recipes_ingredient'
foreach ($selectedIngredients as $ingredient) {
$recipesIngredientModel->insert([
'id_recipe' => $recipeId,
'id_ingredient' => $ingredient['id'],
'amount' => $ingredient['amount']
]);
}
// Redireccionar a la página principal
return redirect()->to('/home');
}
}
......@@ -14,6 +14,13 @@ class RecipesController extends Controller
$recipe = $recipesModel->find($recipe_id);
$ingredients = $recipesModel->get_recipe_ingredients($recipe_id);
// Obtén el nombre de usuario a partir del correo electrónico
$userModel = new \App\Models\UserModel();
$email = $recipe->email_user;
$user = $userModel->where('email', $email)->first();
$username = $user->username;
$photo = $user->photo;
if ($recipe == null) {
// Mostrar un mensaje de error si no se encuentra la receta
return redirect()->to('/');
......@@ -22,6 +29,8 @@ class RecipesController extends Controller
$data = [
'recipe' => $recipe,
'ingredients' => $ingredients,
'username' => $username,
'photoUser' => $photo,
];
return view('templates/header', $data)
......@@ -45,11 +54,34 @@ class RecipesController extends Controller
}
}
public function search_recipe()
{
$query = $this->request->getVar('query');
$recipesModel = new \App\Models\RecipesModel();
$recipes = $recipesModel->searchRecipe($query);
return $this->response->setJSON($recipes);
}
public function search_recipe()
{
$query = $this->request->getVar('query');
$recipesModel = new \App\Models\RecipesModel();
$recipes = $recipesModel->searchRecipe($query);
return $this->response->setJSON($recipes);
}
public function delete($id)
{
$recipeModel = new RecipesModel();
$recipeIngredientModel = new RecipesIngredientModel();
// Primero, borra todas las entradas de la tabla recipes_ingredient
if ($recipeIngredientModel->deleteRelation($id)) {
// Si se eliminaron las relaciones correctamente, borra la receta
if ($recipeModel->deleteRecipe($id)) {
// La receta se eliminó correctamente
return redirect()->to('/users')->with('message', 'Receta eliminada correctamente');
} else {
// Hubo un error al eliminar la receta
return redirect()->back()->with('error', 'No se pudo eliminar la receta');
}
} else {
// Hubo un error al eliminar las relaciones
return redirect()->back()->with('error', 'No se pudieron eliminar las relaciones de ingredientes de la receta');
}
}
}
\ No newline at end of file
......@@ -27,7 +27,8 @@ class User extends BaseController
}
public function loginAjax(){
public function loginAjax()
{
$validation = \Config\Services::validation();
$rules = [
"email" => [
......@@ -41,7 +42,7 @@ class User extends BaseController
//"rules" => "required|min_length[8]|max_length[20]"
]
];
$session = session();
$userModel = model('UserModel');
......@@ -56,18 +57,18 @@ class User extends BaseController
return $this->response->setStatusCode(200)->setJSON([
'text' => 'Usuario logeado'
]);
} else {
} else {
return $this->response->setStatusCode(403)->setJSON([
'text' => 'Usuario no logeado'
]);
}
} else {
return $this->output->set_content_type('application/json')
->set_status_header(400)
->set_output(json_encode([
'text' => 'Email o pasword incorrecto'
]));
}
->set_status_header(400)
->set_output(json_encode([
'text' => 'Email o pasword incorrecto'
]));
}
}
return $this->response->setStatusCode(400)->setJSON([
'text' => 'Solo se aceptan post request'
......@@ -77,12 +78,7 @@ class User extends BaseController
}
public function user_ok()
{
$session = session();
$usuario = $session->__get('user');
$data['usuario'] = $usuario;
$userModel = model('UserModel');
return view('templates/header',$data)
return view('templates/header')
. view('pages/home')
. view('templates/footer');
}
......@@ -90,7 +86,10 @@ class User extends BaseController
public function logout()
{
# To Do.
$session = session();
$session->destroy();
return redirect()->to('/login');
}
public function unauthorized()
......@@ -101,7 +100,7 @@ class User extends BaseController
}
public function registerAjax()
{
{
$validation = \Config\Services::validation();
$rules = [
"username" => [
......@@ -128,10 +127,13 @@ class User extends BaseController
$name = $this->request->getVar('username');
$email = $this->request->getVar('email');
$password = $this->request->getVar('password');
$role = $this->request->getVar('rol');
$userData = [
'username' => $name,
'email' => $email,
'password' => password_hash($password, PASSWORD_DEFAULT),
'rol' => $role,
'photo' => null
];
$userModel->saveUser($email, $name, $password);
$newUser = $userModel->authenticate($email, $password);
......@@ -164,5 +166,49 @@ class User extends BaseController
}
public function show_name($email)
{
$userModel = new \App\Models\UserModel();
$user = $userModel->find($email);
if ($user) {
return $user->username;
}
return false;
}
public function personalRecipes()
{
return view('templates/header')
. view('pages/userRecipes')
. view('templates/footer');
}
public function myprofile()
{
return view('templates/header')
. view('pages/profile_view')
. view('templates/footer');
}
public function changeProfilePhoto()
{
$session = \Config\Services::session();
$email = $session->get('user')->email;
$userModel = new UserModel();
$photo = $this->request->getFile('photo');
if ($photo->isValid() && !$photo->hasMoved()) {
$photoBlob = file_get_contents($photo->getRealPath());
$data['photo'] = $photoBlob;
$userModel->update($email, $data);
}
return redirect()->to('/perfil');
}
}
\ No newline at end of file
......@@ -11,7 +11,7 @@ class AdminAuth implements FilterInterface
{
if (!session('logged_in'))
return redirect()->to(site_url('/login'));
elseif ((session('user')->role & 2) == 0)
elseif ((session('user')->rol & 2) == 0)
return redirect()->to(site_url('/unauthorized'));
}
public function after(
......
......@@ -11,8 +11,6 @@ class UserAuth implements FilterInterface
{
if (!session('logged_in'))
return redirect()->to(site_url('/login'));
else if ((session('user')->role & 1) == 0)
return redirect()->to(site_url('/unauthorized'));
}
public function after(
RequestInterface $request, ResponseInterface $response,
......
......@@ -30,5 +30,10 @@ class RecipesIngredientModel extends Model
return $this->insert($data);
}
public function deleteRelation($id_recipe) {
return $this->where('id_recipe', $id_recipe)->delete();
}
}
\ No newline at end of file
......@@ -11,7 +11,7 @@ class RecipesModel extends Model
protected $returnType = 'object'; # 'object' or 'array'
protected $useSoftDeletes = false; # true if you expect to recover data
# Fields that can be set during save, insert, or update methods
protected $allowedFields = ['id', 'name', 'season', 'origin', 'photo', 'is_vegan', 'description', 'instructions', 'link'];
protected $allowedFields = ['id', 'name', 'season', 'origin', 'photo', 'is_vegan', 'description', 'instructions', 'link', 'email_user'];
protected $useTimestamps = false; # no timestamps on inserts and updates
# Do not use validations rules (for the time being...)
protected $validationRules = [];
......@@ -19,7 +19,7 @@ class RecipesModel extends Model
protected $skipValidation = false;
public function saveRecipe($id, $name, $season, $origin, $photo, $is_vegan, $description, $instructions, $link)
public function saveRecipe($id, $name, $season, $origin, $photo, $is_vegan, $description, $instructions, $link, $email_user)
{
$data = [
'id' => $id,
......@@ -31,6 +31,7 @@ class RecipesModel extends Model
'description' => $description,
'instructions' => $instructions,
'link' => $link,
'email_user' => $email_user
];
return $this->insert($data);
}
......@@ -57,9 +58,9 @@ class RecipesModel extends Model
return [];
}
public function deleteRecipe($id) {
return $this->delete($id);
}
}
\ No newline at end of file
......@@ -11,7 +11,7 @@ class UserModel extends Model
protected $returnType = 'object'; # 'object' or 'array'
protected $useSoftDeletes = false; # true if you expect to recover data
# Fields that can be set during save, insert, or update methods
protected $allowedFields = ['email', 'username', 'password'];
protected $allowedFields = ['email', 'username', 'password','photo'];
protected $useTimestamps = false; # no timestamps on inserts and updates
# Do not use validations rules (for the time being...)
protected $validationRules = [];
......
......@@ -62,17 +62,19 @@
</select>
</div>
</div>
<!-- Opción vegana -->
<div class="form-group col-md-4">
<label for="is_vegan" class="chip-label">Vegana</label>
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="is_vegan" name="is_vegan">
<label class="custom-control-label chip" for="is_vegan"></label>
<!-- Opción vegana -->
<div class="form-group col-md-4">
<label for="is_vegan" class="chip-label">Vegana</label>
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="is_vegan" name="is_vegan">
<label class="custom-control-label chip" for="is_vegan"></label>
</div>
</div>
</div>
<!-- Seleccionar ingredientes -->
<label>Ingredientes:</label>
<div class="input-group my-form">
......@@ -112,13 +114,17 @@
</div>
</div>
<div class="form-group">
<label for="link">Ingrese el enlace del video:</label>
<input type="text" id="link" name="link" class="form-control"
placeholder="ej: https://www.youtube.com/watch?v=cks8liHVdZg">
</div>
<!-- Añadir ingrediente -->
<h5>¿No ves tu ingrediente en la lista?
<!-- Seleccionar enlace de video-->
<div class="form-group">
<label for="link">Ingrese el enlace del video:</label>
<input type="text" id="link" name="link" class="form-control"
placeholder="ej: https://www.youtube.com/watch?v=cks8liHVdZg">
</div>
<input type="submit" value="Subir receta" class="btn btn-primary">
<input type="submit" value="Subir receta" class="btn btn-primary">
</form>
<script src="<?= base_url("js/insert.js") ?>"></script>
......
<main id="main" class="main">
<section class="section dashboard">
<?php $session = session(); ?>
<div style="display: flex; flex-direction: row; align-items: center;">
<?php if ($session->has('user') && !is_null($session->get('user')->photo)): ?>
<img src="data:image/jpeg;base64,<?= base64_encode($session->get('user')->photo) ?>" alt="Profile"
style="width: 100px; height: 100px; object-fit: cover; border-radius: 50%;">
<?php else: ?>
<img src="<?= base_url("imagenes/profile.png") ?>"
style="width: 100px; height: 100px; object-fit: cover; border-radius: 50%;">
<?php endif; ?>
<div style="display: flex; flex-direction: column; margin-left: 20px;">
<span style="font-size: 18px; font-weight: bold;">Nombre de usuario:</span>
<span style="font-size: 16px;">
<?= $session->get('user')->username ?>
</span>
<span style="font-size: 18px; font-weight: bold;">Correo:</span>
<span style="font-size: 16px;">
<?= $session->get('user')->email ?>
</span>
</div>
</div>
<a href="#" id="cambiar-foto-btn" class="btn btn-primary">Cambiar foto de perfil</a>
<div class="modal fade" id="cambiar-foto-modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Cambiar foto de perfil</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<form id="cambiar-foto-form" enctype="multipart/form-data">
<div class="form-group">
<label for="foto">Selecciona una foto:</label>
<input type="file" class="form-control-file" id="foto" name="foto">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
<button type="button" class="btn btn-primary" id="guardar-foto-btn">Guardar</button>
</div>
</div>
</div>
</div>
</section>
</main><!-- End #main -->
<script>
$(document).ready(function () {
$('#cambiar-foto-btn').click(function () {
$('#cambiar-foto-modal').modal('show');
});
});
</script>
<script>
$(document).ready(function() {
$('#guardar-foto-btn').click(function() {
var formData = new FormData($('#cambiar-foto-form')[0]);
$.ajax({
url: '/cambiarFoto',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function(data) {
window.location.href = '/perfil';
}
});
});
});
</script>
......@@ -76,6 +76,12 @@ function getYoutubeVideoId($url)
width: 100%;
height: 100%;
}
#profile-pic {
border-radius: 10px;
width: 25px;
height: 25px;
}
</style>
<main id="main" class="main">
......@@ -94,6 +100,22 @@ function getYoutubeVideoId($url)
<?php echo $recipe->description; ?>
</p>
<div class="recipe-header">
<p>Receta subida por:
<b>
<?= $username ?>
<?php if (empty($photoUser)): ?>
<img src="<?= base_url("imagenes/profile.png") ?>" alt="Profile" id="profile-pic">
<?php else: ?>
<img src="data:image/jpeg;base64,<?= base64_encode($photoUser) ?>" alt="Profile"
id="profile-pic">
<?php endif; ?>
</b>
</p>
</div>
<h2>Ingredientes</h2>
<ul class="ingredient-list">
<?php foreach ($ingredients as $ingredient) { ?>
......
<main id="main" class="main">
<section class="section dashboard">
<h1>Vista por hacer🤠</h1>
</section>
</main><!-- End #main -->
\ No newline at end of file
<h1>Admin Page</h1>
<h2>Lista de usuarios</h2>
<!-- LISTA DE USUARIOS -->
<?php
if (sizeof($users) > 0) {
foreach ($users as $row) {
echo $row->email . " - ";
echo $row->username . " - ";
echo $row->password . " ";
echo "<br/>";
}
} else {
echo "No user";
}
?>
<main id="main" class="main">
<section class="section dashboard">
<h2>Usuarios</h2>
<!-- LISTA DE USUARIOS -->
<?php
if (sizeof($users) > 0) {
foreach ($users as $row) {
echo $row->email . " - ";
echo $row->username . " - ";
echo $row->password . " ";
echo "<br/>";
}
} else {
echo "No user";
}
?>
<h2> Recetas </h2>
<!-- LISTA DE RECETAS -->
<?php
$recipesModel = new \App\Models\RecipesModel();
$recipes = $recipesModel->findAll();
?>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Nombre</th>
<th>Temporada</th>
<th>Origen</th>
<th>Foto</th>
<th>Vegano</th>
<th>Descripción</th>
<th>Instrucciones</th>
<th>Enlace</th>
<th>Acciones</th>
</tr>
</thead>
<tbody>
<?php foreach ($recipes as $row): ?>
<tr>
<td>
<?= $row->id; ?>
</td>
<td>
<?= $row->name; ?>
</td>
<td>
<?= $row->season; ?>
</td>
<td>
<?= $row->origin; ?>
</td>
<td>
<img src="<?= base_url('recipe/image/' . $row->id); ?>" alt="" class="img-thumbnail"
style="width: 100px;">
</td>
<td>
<?= $row->is_vegan ? 'Sí' : 'No'; ?>
</td>
<td>
<?= mb_strimwidth($row->description, 0, 10, "..."); ?>
</td>
<td>
<?= mb_strimwidth($row->instructions, 0, 10, "..."); ?>
</td>
<td>
<?= $row->link; ?>
</td>
<td>
<button class="btn btn-danger" onclick="deleteRecipe(<?= $row->id; ?>)">Borrar</button>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<h2> Recetas </h2>
<!-- LISTA DE RECETAS -->
<?php
$recipesModel = new \App\Models\RecipesModel();
$recipes = $recipesModel->findAll();
?>
<script>
function borrarReceta(recipeId) {
//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAa
}
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Nombre</th>
<th>Temporada</th>
<th>Origen</th>
<th>Foto</th>
<th>Vegano</th>
<th>Descripción</th>
<th>Instrucciones</th>
<th>Enlace</th>
<th>Acciones</th>
</tr>
</thead>
<tbody>
<?php foreach ($recipes as $row): ?>
<tr>
<td>
<?= $row->id; ?>
</td>
<td>
<?= $row->name; ?>
</td>
<td>
<?= $row->season; ?>
</td>
<td>
<?= $row->origin; ?>
</td>
<td>
<img src="<?= base_url('recipe/image/' . $row->id); ?>" alt="" class="img-thumbnail"
style="width: 100px;">
</td>
<td>
<?= $row->is_vegan ? 'Sí' : 'No'; ?>
</td>
<td>
<?= mb_strimwidth($row->description, 0, 10, "..."); ?>
</td>
<td>
<?= mb_strimwidth($row->instructions, 0, 10, "..."); ?>
</td>
<td>
<?= mb_strimwidth($row->link, 0, 50, "..."); ?>
</td>
<td>
<button class="btn btn-danger" onclick="window.location.href='<?php echo base_url('/recipes/delete/' . $row->id); ?>'">Borrar</button>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<script>
function borrarReceta(recipeId) {
}
</script>
\ No newline at end of file
</script>
</section>
</main><!-- End #main -->
\ No newline at end of file
h2 class="alert alert-danger">Access denied</h2>
<p>You are not authorized to access this page.</p>
<p>You are not authorized to access this page.</p>
\ No newline at end of file
......@@ -266,6 +266,38 @@ body {
width: 32%;
}
.form-group {
margin-bottom: 20px;
}
.form-row {
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
margin-bottom: 20px;
}
.form-row > .form-group {
flex: 1;
padding: 0 15px;
}
.form-row > .form-group:first-child {
padding-left: 0;
}
.form-row > .form-group:last-child {
padding-right: 0;
}
.label-centered {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
/* Estilos para el chip vegano */
.vegan-chip {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment