diff --git a/.gitignore b/.gitignore index 3f8e1d990..9e4e2cd9b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ node_modules -.vscode/* \ No newline at end of file +.vscode/* +.env diff --git a/config/.env b/config/.env deleted file mode 100644 index dbe126e0a..000000000 --- a/config/.env +++ /dev/null @@ -1,2 +0,0 @@ -PORT = 2121 -DB_STRING = mongodb+srv://demo:demo@cluster0.hcds1.mongodb.net/todos?retryWrites=true&w=majority \ No newline at end of file diff --git a/config/database.js b/config/database.js index 4aac3a233..f5c5b2bcc 100644 --- a/config/database.js +++ b/config/database.js @@ -2,14 +2,14 @@ const mongoose = require('mongoose') const connectDB = async () => { try { - const conn = await mongoose.connect(process.env.DB_STRING, { + const conn = await mongoose.connect(process.env.DB_STRING, { //awaits connection useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, useCreateIndex: true }) - console.log(`MongoDB Connected: ${conn.connection.host}`) + console.log(`MongoDB Connected: ${conn.connection.host}`) //logs success } catch (err) { console.error(err) process.exit(1) diff --git a/controllers/auth.js b/controllers/auth.js index c434c3c3a..7f43d6ece 100644 --- a/controllers/auth.js +++ b/controllers/auth.js @@ -1,46 +1,48 @@ -const passport = require('passport') -const validator = require('validator') +const passport = require('passport') //auth +const validator = require('validator') // validator const User = require('../models/User') exports.getLogin = (req, res) => { - if (req.user) { + if (req.user) { //if session exists return res.redirect('/todos') } - res.render('login', { + res.render('login', //if it doesnt render login.ejs + { title: 'Login' }) } exports.postLogin = (req, res, next) => { - const validationErrors = [] - if (!validator.isEmail(req.body.email)) validationErrors.push({ msg: 'Please enter a valid email address.' }) - if (validator.isEmpty(req.body.password)) validationErrors.push({ msg: 'Password cannot be blank.' }) + const validationErrors = [] //error array + if (!validator.isEmail(req.body.email)) validationErrors.push({ msg: 'Please enter a valid email address.' }) //if its not a valid email push error + if (validator.isEmpty(req.body.password)) validationErrors.push({ msg: 'Password cannot be blank.' }) //if pass is empty push message - if (validationErrors.length) { - req.flash('errors', validationErrors) - return res.redirect('/login') + if (validationErrors.length) { //if there is something in the validator array + req.flash('errors', validationErrors) //I assume this makes the messages appear + return res.redirect('/login') //returns to login } - req.body.email = validator.normalizeEmail(req.body.email, { gmail_remove_dots: false }) + req.body.email = validator.normalizeEmail(req.body.email, { gmail_remove_dots: false }) //normalizes email - passport.authenticate('local', (err, user, info) => { + passport.authenticate('local', (err, user, info) => { // I assume user comes from req and its passed by the authenticate function if (err) { return next(err) } if (!user) { - req.flash('errors', info) + req.flash('errors', info) //if it doesnt find the user return res.redirect('/login') } req.logIn(user, (err) => { - if (err) { return next(err) } - req.flash('success', { msg: 'Success! You are logged in.' }) + if (err) { return next(err) } // case of an error + req.flash('success', { msg: 'Success! You are logged in.' }) //seems like its not do anything res.redirect(req.session.returnTo || '/todos') }) - })(req, res, next) + })(req, res, next) //exceutes the function } exports.logout = (req, res) => { req.logout(() => { console.log('User has logged out.') - }) - req.session.destroy((err) => { + }) + //logouts ( not really sure what this does probably change the req body or res body) does nothing if taken out + req.session.destroy((err) => { //destroys sessions i think this does something to the cookies if (err) console.log('Error : Failed to destroy the session during logout.', err) req.user = null res.redirect('/') @@ -48,7 +50,7 @@ const User = require('../models/User') } exports.getSignup = (req, res) => { - if (req.user) { + if (req.user) { // if req has a session goes to dashboard return res.redirect('/todos') } res.render('signup', { @@ -58,16 +60,17 @@ const User = require('../models/User') exports.postSignup = (req, res, next) => { const validationErrors = [] - if (!validator.isEmail(req.body.email)) validationErrors.push({ msg: 'Please enter a valid email address.' }) - if (!validator.isLength(req.body.password, { min: 8 })) validationErrors.push({ msg: 'Password must be at least 8 characters long' }) - if (req.body.password !== req.body.confirmPassword) validationErrors.push({ msg: 'Passwords do not match' }) + if (!validator.isEmail(req.body.email)) validationErrors.push({ msg: 'Please enter a valid email address.' }) //validates email + if (!validator.isLength(req.body.password, { min: 8 })) validationErrors.push({ msg: 'Password must be at least 8 characters long' }) //min characters + if (req.body.password !== req.body.confirmPassword) validationErrors.push({ msg: 'Passwords do not match' }) - if (validationErrors.length) { + if (validationErrors.length) { //if we have errors we have to redirect to the same page req.flash('errors', validationErrors) - return res.redirect('../signup') + return res.redirect('/signup') } req.body.email = validator.normalizeEmail(req.body.email, { gmail_remove_dots: false }) + //creates a new user const user = new User({ userName: req.body.userName, email: req.body.email, @@ -80,11 +83,11 @@ const User = require('../models/User') ]}, (err, existingUser) => { if (err) { return next(err) } if (existingUser) { - req.flash('errors', { msg: 'Account with that email address or username already exists.' }) - return res.redirect('../signup') + req.flash('errors', { msg: 'Account with that email address or username already exists.' }) //flashes if email or username is taken + return res.redirect('../signup') } user.save((err) => { - if (err) { return next(err) } + if (err) { return next(err) } //saves the user on atlas req.logIn(user, (err) => { if (err) { return next(err) diff --git a/controllers/todos.js b/controllers/todos.js index b10950f93..bf22fb417 100644 --- a/controllers/todos.js +++ b/controllers/todos.js @@ -1,7 +1,7 @@ const Todo = require('../models/Todo') module.exports = { - getTodos: async (req,res)=>{ + getTodos: async (req,res)=>{ //gets the info and renders de dashboard console.log(req.user) try{ const todoItems = await Todo.find({userId:req.user.id}) @@ -11,9 +11,14 @@ module.exports = { console.log(err) } }, - createTodo: async (req, res)=>{ + createTodo: async (req, res)=>{ //creates a new document and redirects try{ - await Todo.create({todo: req.body.todoItem, completed: false, userId: req.user.id}) + await Todo.create( + {todo: req.body.todoItem, + completed: false, + userId: req.user.id, + priority: req.body.todoPriority + }) console.log('Todo has been added!') res.redirect('/todos') }catch(err){ diff --git a/middleware/auth.js b/middleware/auth.js index 8b92a4620..a6ca74f1d 100644 --- a/middleware/auth.js +++ b/middleware/auth.js @@ -1,5 +1,5 @@ module.exports = { - ensureAuth: function (req, res, next) { + ensureAuth: function (req, res, next) { //checks if the req/user is authenticated if (req.isAuthenticated()) { return next() } else { diff --git a/models/Todo.js b/models/Todo.js index 8698f6900..da0ae9419 100644 --- a/models/Todo.js +++ b/models/Todo.js @@ -12,6 +12,10 @@ const TodoSchema = new mongoose.Schema({ userId: { type: String, required: true + }, + priority: { + type: Number, + required: false } }) diff --git a/models/User.js b/models/User.js index db4b2d116..0d3873d86 100644 --- a/models/User.js +++ b/models/User.js @@ -9,7 +9,8 @@ const UserSchema = new mongoose.Schema({ // Password hash middleware. - +//hashes the password before saving it +// I suspect this runs before saving the password UserSchema.pre('save', function save(next) { const user = this if (!user.isModified('password')) { return next() } diff --git a/public/css/style.css b/public/css/style.css index fbd6b929e..95157ba0a 100644 --- a/public/css/style.css +++ b/public/css/style.css @@ -1,3 +1,6 @@ +*{ + background: grey; +} h1{ color: red; } @@ -7,4 +10,4 @@ h1{ } .not{ text-decoration: underline; -} \ No newline at end of file +} diff --git a/public/js/main.js b/public/js/main.js index b4cfee075..06228dade 100644 --- a/public/js/main.js +++ b/public/js/main.js @@ -33,7 +33,7 @@ async function deleteTodo(){ } async function markComplete(){ - const todoId = this.parentNode.dataset.id + const todoId = this.parentNode.dataset.id //takes id from the li try{ const response = await fetch('todos/markComplete', { method: 'put', @@ -44,7 +44,7 @@ async function markComplete(){ }) const data = await response.json() console.log(data) - location.reload() + location.reload() // reloads page }catch(err){ console.log(err) } diff --git a/routes/main.js b/routes/main.js index bdeb7529f..d54dff017 100644 --- a/routes/main.js +++ b/routes/main.js @@ -1,10 +1,13 @@ +//create router const express = require('express') const router = express.Router() + +//controller const authController = require('../controllers/auth') const homeController = require('../controllers/home') const { ensureAuth, ensureGuest } = require('../middleware/auth') -router.get('/', homeController.getIndex) +router.get('/', homeController.getIndex) router.get('/login', authController.getLogin) router.post('/login', authController.postLogin) router.get('/logout', authController.logout) diff --git a/routes/todos.js b/routes/todos.js index 03dcf42e4..c2f2d23a3 100644 --- a/routes/todos.js +++ b/routes/todos.js @@ -1,5 +1,8 @@ +//creates router const express = require('express') const router = express.Router() + + const todosController = require('../controllers/todos') const { ensureAuth } = require('../middleware/auth') diff --git a/server.js b/server.js index b031c4cad..4f9765c13 100644 --- a/server.js +++ b/server.js @@ -1,27 +1,35 @@ +//creates app const express = require('express') const app = express() -const mongoose = require('mongoose') -const passport = require('passport') -const session = require('express-session') -const MongoStore = require('connect-mongo')(session) -const flash = require('express-flash') -const logger = require('morgan') -const connectDB = require('./config/database') + +//dependencies +const mongoose = require('mongoose') // db connection +const passport = require('passport') // auth +const session = require('express-session') // allows you to store the session +const MongoStore = require('connect-mongo')(session) // allows you to store the session +const flash = require('express-flash') +const logger = require('morgan') // logs every request +const connectDB = require('./config/database') // connectDB function + +//routes const mainRoutes = require('./routes/main') const todoRoutes = require('./routes/todos') +//allows me to use env variables require('dotenv').config({path: './config/.env'}) // Passport config require('./config/passport')(passport) -connectDB() +connectDB() // connects to DB + +//middleware +app.set('view engine', 'ejs') // view engine +app.use(express.static('public')) //public folder +app.use(express.urlencoded({ extended: true })) //parses request +app.use(express.json()) //json parser +app.use(logger('dev')) // uses morgan -app.set('view engine', 'ejs') -app.use(express.static('public')) -app.use(express.urlencoded({ extended: true })) -app.use(express.json()) -app.use(logger('dev')) // Sessions app.use( session({ @@ -36,11 +44,11 @@ app.use( app.use(passport.initialize()) app.use(passport.session()) -app.use(flash()) +app.use(flash()) // allows for poping showing elements app.use('/', mainRoutes) app.use('/todos', todoRoutes) app.listen(process.env.PORT, ()=>{ - console.log('Server is running, you better catch it!') + console.log(`Server is running, you better catch it! PORT: ${process.env.PORT}`) }) \ No newline at end of file diff --git a/views/login.ejs b/views/login.ejs index 8c2479ce0..57d169e78 100644 --- a/views/login.ejs +++ b/views/login.ejs @@ -7,16 +7,21 @@ Document - <% if (locals.messages.errors) { %> + <% if (locals.messages.errors) { %> //email or pass not valid <% messages.errors.forEach( el => { %>
<%= el.msg %>
<% }) %> <% } %> - <% if (locals.messages.info) { %> + <% if (locals.messages.info) { %> //not found email <% messages.info.forEach( el => { %>
<%= el.msg %>
<% }) %> <% } %> + <% if (locals.messages.success) { %> //not found email + <% messages.success .forEach( el => { %> +
<%= el.msg %>
+ <% }) %> + <% } %>
diff --git a/views/todos.ejs b/views/todos.ejs index d76747a08..6fdc08889 100644 --- a/views/todos.ejs +++ b/views/todos.ejs @@ -12,7 +12,9 @@