-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
tareas
committed
Sep 26, 2021
0 parents
commit e127dd5
Showing
25 changed files
with
2,312 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
node_modules |
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
{ | ||
"name": "proyecto", | ||
"version": "1.0.0", | ||
"description": "", | ||
"main": "index.js", | ||
"scripts": { | ||
"start": "node src/index.js", | ||
"dev": "nodemon src/index.js", | ||
"test": "echo \"Error: no test specified\" && exit 1" | ||
}, | ||
"keywords": [], | ||
"author": "", | ||
"license": "ISC", | ||
"dependencies": { | ||
"bcryptjs": "^2.4.3", | ||
"connect-flash": "^0.1.1", | ||
"express": "^4.17.1", | ||
"express-handlebars": "^5.3.3", | ||
"express-session": "^1.17.2", | ||
"method-override": "^3.0.0", | ||
"mongoose": "^6.0.6", | ||
"passport": "^0.4.1", | ||
"passport-local": "^1.0.0" | ||
}, | ||
"devDependencies": { | ||
"nodemon": "^2.0.12" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
const mongoose = require('mongoose'); | ||
|
||
mongoose.connect('mongodb+srv://4rub1k:[email protected]/Notasytitulos?retryWrites=true&w=majority',{ | ||
|
||
useUnifiedTopology: true | ||
}) | ||
.then(db => console.log('DB :) conectado')) | ||
.catch(err => console.error(err)); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
const credencial = require('passport'); | ||
const estrategia = require('passport-local').Strategy; | ||
const Usuario = require('../models/Usuario'); | ||
|
||
|
||
credencial.use(new estrategia({usernameField: 'correo',passwordField: 'contraseña'}, async(correo, contraseña, done)=>{ | ||
|
||
const usuario = await Usuario.findOne({correo: correo}); | ||
if(!usuario){ | ||
return done(null, false,{message: 'Usuario no encontrado.'}); | ||
}else{ | ||
const procede = await usuario.matchPassword(contraseña); | ||
if(procede){ | ||
return done(null,usuario); | ||
} else{ | ||
return done(null,false,{message: 'Contraseña incorrecta'}); | ||
} | ||
} | ||
|
||
})); | ||
|
||
//Se queda en sesion guarda id | ||
credencial.serializeUser((usuario,done)=>{ | ||
done(null, usuario.id); | ||
}); | ||
//done es un colback | ||
credencial.deserializeUser((id,done)=>{ | ||
Usuario.findById(id, (err, usuario)=>{ | ||
done(err, usuario); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
|
||
const autenticacion = {}; | ||
|
||
autenticacion.isAuthenticated = (req, res, next)=>{ | ||
if(req.isAuthenticated()){ | ||
return next(); | ||
} | ||
req.flash('error_msg', 'No autorizado'); | ||
res.redirect('/usuarios/iniciarsecion') | ||
} | ||
|
||
//manda o exporta para utilizarlo en otro lado | ||
module.exports = autenticacion; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
const express = require('express'); | ||
const path = require('path'); | ||
const exphbs = require('express-handlebars'); | ||
const methodOverrride = require('method-override'); | ||
const session = require('express-session'); | ||
const flash = require('connect-flash'); | ||
const credencial = require('passport'); | ||
|
||
|
||
|
||
//Inicializa | ||
const app = express(); | ||
require('./basededatos'); | ||
require('./config/credencial'); | ||
|
||
//configuracion crea marcos y repite diseño | ||
app.set('port',process.env.PORT || 4000); | ||
app.set('views', path.join(__dirname, 'views')); | ||
app.engine('.hbs', exphbs({ | ||
defaultLayout: 'main', | ||
layoutsDir: path.join(app.get('views'), 'layouts'), | ||
partialsDir: path.join(app.get('views'),'partials'), | ||
extname: '.hbs' | ||
})); | ||
app.set('view engine', '.hbs'); | ||
|
||
//middlewares CONEXIONES | ||
app.use(express.urlencoded({extended: false})); | ||
app.use(methodOverrride('_method')); | ||
app.use(session({ | ||
secret: 'mysecreatapp', | ||
resave: true, | ||
saveUninitialized: true | ||
})); | ||
app.use(credencial.initialize()); | ||
app.use(credencial.session()); | ||
app.use(flash()); | ||
|
||
|
||
//global variables | ||
app.use((req, res, next)=>{ | ||
res.locals.success_msg = req.flash('success_msg'); | ||
res.locals.error_msg = req.flash('error_msg'); | ||
res.locals.error = req.flash('error'); | ||
//res.locals.nombre = req.nombre || null; | ||
let usuario = null | ||
if(req.user){ | ||
usuario =JSON.parse(JSON.stringify(req.user)) | ||
} | ||
res.locals.usuario = usuario | ||
next(); | ||
}); | ||
//rutas crear notas actualizar acceder a url login sing out etc | ||
app.use(require('./routes/index')); | ||
app.use(require('./routes/notas')); | ||
app.use(require('./routes/usuarios')); | ||
|
||
//estaticos ruta | ||
app.use(express.static(path.join(__dirname, 'public'))); | ||
|
||
|
||
//server esta escuchando | ||
app.listen(app.get('port'),()=>{ | ||
console.log('Servidor conectado ', app.get('port')); | ||
}); | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
const mongoose = require('mongoose'); | ||
const {Schema} = mongoose; | ||
|
||
const NotaSchema = new Schema({ | ||
titulo:{type: String,require: true}, | ||
descripcion:{type: String, require: true}, | ||
fecha: {type: Date, default: Date.now}, | ||
usuario: {type: String} | ||
}) | ||
|
||
module.exports = mongoose.model('Nota',NotaSchema); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
const mongoose = require('mongoose'); | ||
const {Schema} = mongoose; | ||
const bcrypt = require('bcryptjs'); | ||
|
||
|
||
const UsuarioSchema = new Schema({ | ||
nombre: {type: String, required: true}, | ||
correo: {type: String, required: true}, | ||
contraseña: {type: String, required: true}, | ||
fecha: {type: Date, default: Date.now}, | ||
}); | ||
|
||
UsuarioSchema.methods.encryptPassword = async(contraseña) =>{ | ||
//ejecutar 10 veces algoritmo entre mas vueltas mas recursos | ||
const salt = await bcrypt.genSalt(10); | ||
//usa contraseña y hash | ||
const hash = bcrypt.hash(contraseña,salt); | ||
//genera cifrado | ||
return hash; | ||
}; | ||
//Metodo para logear | ||
UsuarioSchema.methods.matchPassword = async function (contraseña){ | ||
return await bcrypt.compare(contraseña, this.contraseña); | ||
}; | ||
|
||
module.exports = mongoose.model('Usuario',UsuarioSchema); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
body{ | ||
background: #283c86; /* fallback for old browsers */ | ||
background: -webkit-linear-gradient(to right, #45a247, #283c86); /* Chrome 10-25, Safari 5.1-6 */ | ||
background: linear-gradient(to right, #45a247, #283c86); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */ | ||
} | ||
|
||
.logo{ | ||
width: 42%; | ||
} | ||
|
||
h2{ | ||
color: antiquewhite; | ||
font-style: italic; | ||
font-family: fantasy; | ||
} | ||
p{ | ||
font-size: 2.4rem; | ||
color: black; | ||
font-family: Helvetica, Arial, sans-serif; | ||
font: oblique bold 120% cursive; | ||
} |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
const express = require('express'); | ||
const router = express.Router(); | ||
|
||
router.get('/', (req,res)=>{ | ||
res.render('index'); | ||
}); | ||
|
||
router.get('/acerca', (req,res)=>{ | ||
res.render('acerca'); | ||
}); | ||
|
||
module.exports= router; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
const express = require('express'); | ||
const router = express.Router(); | ||
const Nota = require('../models/Nota'); | ||
const {isAuthenticated} = require('../helpers/conjunto'); | ||
|
||
//si esta isAuthenticated valida primero y despues hace la ejecucion | ||
router.get('/notas/agregar', isAuthenticated, (req,res)=>{ | ||
res.render('notas/nueva-nota'); | ||
}); | ||
//si esta isAuthenticated valida primero y despues hace la ejecucion | ||
//async <- es asincronos y AWAIT ABAJO | ||
router.post('/notas/nueva-nota', isAuthenticated, async(req, res) =>{ | ||
const {titulo,descripcion}= req.body; | ||
const errors=[]; | ||
if(!titulo){ | ||
errors.push({text: 'Por favor ingresa el titulo'}); | ||
} | ||
if(!descripcion){ | ||
errors.push({text: 'Por favor ingresa la descripcion'}); | ||
} | ||
if(errors.length>0){ | ||
res.render('notas/nueva-nota',{ | ||
errors, | ||
titulo, | ||
descripcion | ||
}); | ||
}else{ | ||
const nuevaNota = new Nota({titulo, descripcion}); | ||
nuevaNota.usuario = req.user.id; | ||
//await va de la mano con async | ||
await nuevaNota.save(); | ||
req.flash('success_msg', 'Nota agregada :)') | ||
res.redirect('/notas'); | ||
} | ||
|
||
}); | ||
//si esta isAuthenticated valida primero y despues hace la ejecucion | ||
router.get('/notas', isAuthenticated,async(req,res)=>{ | ||
//opera con la base de datos Nota | ||
//.find() normal pide todo .find({titulo, descripcion}) | ||
//recuerda que await y la consulta es asincrona | ||
//const notas = await Nota.find().lean(); | ||
const notas = await Nota.find({usuario: req.user.id}).lean().sort({fecha: 'desc'}); //AQUI............. | ||
res.render('notas/todaslasnotas',{notas}); | ||
}); | ||
|
||
//si esta isAuthenticated valida primero y despues hace la ejecucion | ||
router.get('/notas/editar/:id', isAuthenticated,async(req,res)=>{ | ||
const nota = await Nota.findById(req.params.id).lean(); | ||
res.render('notas/editar-nota', {nota}); | ||
}); | ||
//si esta isAuthenticated valida primero y despues hace la ejecucion | ||
router.put('/notas/editar-nota/:id', isAuthenticated,async(req,res)=>{ | ||
const {titulo, descripcion} = req.body; | ||
await Nota.findByIdAndUpdate(req.params.id, {titulo, descripcion}).lean(); | ||
req.flash('success_msg', 'Nota editada exitosamente'); | ||
res.redirect('/notas'); | ||
}); | ||
|
||
////si esta isAuthenticated valida primero y despues hace la ejecucion | ||
router.delete('/notas/borrar/:id', isAuthenticated,async(req, res)=>{ | ||
await Nota.findByIdAndDelete(req.params.id); | ||
req.flash('success_msg', 'Nota borrada exitosamente'); | ||
res.redirect('/notas'); | ||
}); | ||
|
||
|
||
|
||
module.exports= router; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
const express = require('express'); | ||
const router = express.Router(); | ||
const Usuario = require('../models/Usuario'); | ||
|
||
const credencial = require('passport'); | ||
|
||
router.get('/usuarios/iniciarsecion', (req,res)=>{ | ||
res.render('usuarios/iniciarsecion'); | ||
}); | ||
|
||
router.post('/usuarios/iniciarsecion', credencial.authenticate('local',{ | ||
successRedirect: '/notas', | ||
failureRedirect: '/usuarios/iniciarsecion', | ||
failureFlash: true | ||
})); | ||
|
||
router.get('/usuarios/registrar', (req,res)=>{ | ||
res.render('usuarios/registrar'); | ||
}); | ||
|
||
router.post('/usuarios/registrar', async(req,res)=>{ | ||
const {nombre,correo,contraseña,contraseña_confirmada} = req.body; | ||
const errors = []; | ||
if(nombre.length <= 0){ | ||
errors.push({text: 'Ingresa tu nombre'}); | ||
} | ||
if(correo.length <= 0){ | ||
errors.push({text: 'Ingresa tu correo'}); | ||
} | ||
if(contraseña.length <= 0){ | ||
errors.push({text: 'Ingresa tu contraseña'}); | ||
} | ||
if(contraseña_confirmada.length <= 0){ | ||
errors.push({text: 'Confirma tu contraseña'}); | ||
} | ||
if (contraseña != contraseña_confirmada){ | ||
errors.push({text: 'Las contraseñas no son iguales.'}); | ||
} | ||
if (contraseña.length < 4){ | ||
errors.push({text: 'La contraseña tiene que ser mayor a 4 caracteres.'}) | ||
} | ||
if (errors.length > 0){ | ||
res.render('usuarios/registrar', {errors, nombre, correo, contraseña, contraseña_confirmada}); | ||
}else{ | ||
const correoUsuario = await Usuario.findOne({correo: correo}); | ||
if(correoUsuario){ | ||
req.flash('error_msg', 'Correo ya registrado'); | ||
res.redirect('/usuarios/registrar'); | ||
} | ||
const nuevoUsuario = new Usuario({nombre, correo, contraseña}); | ||
nuevoUsuario.contraseña = await nuevoUsuario.encryptPassword(contraseña); | ||
await nuevoUsuario.save(); | ||
req.flash('success_msg', 'Registrado exitosamente'); | ||
res.redirect('/usuarios/iniciarsecion'); | ||
} | ||
}); | ||
|
||
router.get('/usuarios/salir',(req ,res)=>{ | ||
req.logout(); | ||
res.redirect('/'); | ||
}); | ||
|
||
|
||
module.exports= router; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
<div class="card"> | ||
<div class="card-body"> | ||
<h1>Nombre: Oscar Miguel Gonzalez Ramirez</h1> | ||
<p>Para realizar esta practica se utilizo: <br>Base de datos: Mongo db <br>Intermediario: Moongose<br>Diseño: bootstrap<br>Nodejs </p> | ||
</div> | ||
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
<div class="jumbotron mt-9"> | ||
<h2 class="display-4 " name="menu">Mi Primera app con Node, Bootstrap, y Mongo </h2> | ||
<p >Mi segundo Crud</p> | ||
<p >Aplicacion de LOGIN, NOTAS PERSONALES, EDITAR NOTAS, BORRAR NOTAS, CREAR NOTAS, CREAR USUARIO, BORRAR USUARIO</p> | ||
</div> |
Oops, something went wrong.