Skip to content

Commit

Permalink
prettierrc
Browse files Browse the repository at this point in the history
  • Loading branch information
bloombar committed Oct 30, 2024
1 parent e70b6d9 commit 7e76e0b
Show file tree
Hide file tree
Showing 26 changed files with 302 additions and 296 deletions.
6 changes: 6 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"tabWidth": 2,
"semi": false,
"arrowParens": "avoid",
"singleQuote": true
}
36 changes: 18 additions & 18 deletions back-end/app.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,26 @@
// import and instantiate express
const express = require("express") // CommonJS import style!
const express = require('express') // CommonJS import style!
const app = express() // instantiate an Express object
const cors = require("cors") // middleware for enabling CORS (Cross-Origin Resource Sharing) requests.
const morgan = require("morgan") // middleware for nice logging of incoming HTTP requests
const path = require("path")
const cookieParser = require("cookie-parser") // middleware useful for parsing cookies in requests
require("dotenv").config({ silent: true }) // load environmental variables from a hidden file named .env
const cors = require('cors') // middleware for enabling CORS (Cross-Origin Resource Sharing) requests.
const morgan = require('morgan') // middleware for nice logging of incoming HTTP requests
const path = require('path')
const cookieParser = require('cookie-parser') // middleware useful for parsing cookies in requests
require('dotenv').config({ silent: true }) // load environmental variables from a hidden file named .env

// the following are used for authentication with JSON Web Tokens
const jwt = require("jsonwebtoken")
const passport = require("passport")
const jwt = require('jsonwebtoken')
const passport = require('passport')

// use this JWT strategy within passport for authentication handling
const jwtStrategy = require("./config/jwt-config.js") // import setup options for using JWT in passport
const jwtStrategy = require('./config/jwt-config.js') // import setup options for using JWT in passport
passport.use(jwtStrategy)

// tell express to use passport middleware
app.use(passport.initialize())

// mongoose models for MongoDB data manipulation
const mongoose = require("mongoose")
const User = require("./models/User.js")
const mongoose = require('mongoose')
const User = require('./models/User.js')

// connect to the database
// console.log(`Conneting to MongoDB at ${process.env.MONGODB_URI}`)
Expand All @@ -34,7 +34,7 @@ try {
}

// set up some useful middleware
app.use(morgan("dev", { skip: (req, res) => process.env.NODE_ENV === "test" })) // log all incoming requests, except when in unit test mode. morgan has a few logging default styles - dev is a nice concise color-coded style
app.use(morgan('dev', { skip: (req, res) => process.env.NODE_ENV === 'test' })) // log all incoming requests, except when in unit test mode. morgan has a few logging default styles - dev is a nice concise color-coded style

// use express's builtin body-parser middleware to parse any data included in a request
app.use(express.json()) // decode JSON-formatted incoming POST data
Expand All @@ -45,14 +45,14 @@ app.use(cookieParser()) // useful middleware for dealing with cookies
app.use(cors({ origin: process.env.FRONT_END_DOMAIN, credentials: true })) // allow incoming requests only from a "trusted" host

// to keep this file neat, we put the logic for the various routes into specialized routing files
const authenticationRoutes = require("./routes/authentication-routes.js")
const cookieRoutes = require("./routes/cookie-routes.js")
const protectedContentRoutes = require("./routes/protected-content-routes.js")
const authenticationRoutes = require('./routes/authentication-routes.js')
const cookieRoutes = require('./routes/cookie-routes.js')
const protectedContentRoutes = require('./routes/protected-content-routes.js')

// use the specialized routing files
app.use("/auth", authenticationRoutes()) // all requests for /auth/* will be handled by the authenticationRoutes router
app.use("/cookie", cookieRoutes()) // all requests for /cookie/* will be handled by the cookieRoutes router
app.use("/protected", protectedContentRoutes()) // all requests for /protected/* will be handled by the protectedRoutes router
app.use('/auth', authenticationRoutes()) // all requests for /auth/* will be handled by the authenticationRoutes router
app.use('/cookie', cookieRoutes()) // all requests for /cookie/* will be handled by the cookieRoutes router
app.use('/protected', protectedContentRoutes()) // all requests for /protected/* will be handled by the protectedRoutes router

// export the express app we created to make it available to other modules
module.exports = app // CommonJS export style!
14 changes: 7 additions & 7 deletions back-end/config/jwt-config.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,27 @@
const mongoose = require("mongoose")
const mongoose = require('mongoose')
const ObjectId = mongoose.Types.ObjectId
const User = require("../models/User.js")
const User = require('../models/User.js')

const passportJWT = require("passport-jwt")
const passportJWT = require('passport-jwt')
const ExtractJwt = passportJWT.ExtractJwt
const JwtStrategy = passportJWT.Strategy

// set up some JWT authentication options for passport
let jwtOptions = {
jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme("jwt"), // look for the Authorization request header
jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('jwt'), // look for the Authorization request header
secretOrKey: process.env.JWT_SECRET, // an arbitrary string used during encryption - see the .env file
}
// console.log(jwtOptions) // debug to make sure the secret from the .env file is loaded correctly

// define the method that is used by passport to verify the contents (i.e. the payload) of the JWT token
const jwtVerifyToken = async function (jwt_payload, next) {
console.log("JWT payload received", jwt_payload) // debugging
console.log('JWT payload received', jwt_payload) // debugging

// check if the token has expired
const expirationDate = new Date(jwt_payload.exp * 1000) // convert from seconds to milliseconds
if (expirationDate < new Date()) {
// the token has expired
return next(null, false, { message: "JWT token has expired." })
return next(null, false, { message: 'JWT token has expired.' })
}

// try to find a matching user in our database
Expand All @@ -34,7 +34,7 @@ const jwtVerifyToken = async function (jwt_payload, next) {
next(null, user)
} else {
// we didn't find the user... fail!
next(null, false, { message: "User not found" })
next(null, false, { message: 'User not found' })
}
}

Expand Down
14 changes: 7 additions & 7 deletions back-end/models/User.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// a mongoose model of a user
const mongoose = require("mongoose")
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const bcrypt = require("bcryptjs")
const jwt = require("jsonwebtoken")
const jwtStrategy = require("../config/jwt-config.js") // import setup options for using JWT in passport
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const jwtStrategy = require('../config/jwt-config.js') // import setup options for using JWT in passport

// this is our mongoose model for a user
const UserSchema = new Schema({
Expand All @@ -20,10 +20,10 @@ const UserSchema = new Schema({

// hash the password before the user is saved
// mongoose provides hooks that allow us to run code before or after specific events
UserSchema.pre("save", function (next) {
UserSchema.pre('save', function (next) {
const user = this
// if the password has not changed, no need to hash it
if (!user.isModified("password")) return next()
if (!user.isModified('password')) return next()
// otherwise, the password is being modified, so hash it
bcrypt.hash(user.password, 10, (err, hash) => {
if (err) return next(err)
Expand Down Expand Up @@ -64,7 +64,7 @@ UserSchema.methods.toAuthJSON = function () {
}

// create a model from this schema
const User = mongoose.model("User", UserSchema)
const User = mongoose.model('User', UserSchema)

// export the model
module.exports = User
102 changes: 51 additions & 51 deletions back-end/routes/authentication-routes.js
Original file line number Diff line number Diff line change
@@ -1,126 +1,126 @@
const express = require("express"); // CommonJS import style!
const express = require('express') // CommonJS import style!

// mongoose models for MongoDB data manipulation
const mongoose = require("mongoose");
const User = require("../models/User.js");
const mongoose = require('mongoose')
const User = require('../models/User.js')

// a method that constains code to handle authentication-specific routes
const authenticationRouter = () => {
// create a new router that we can customize
const router = express.Router();
const router = express.Router()

// a route to handle user signup requests to /auth/signup
router.post("/signup", async (req, res, next) => {
router.post('/signup', async (req, res, next) => {
// console.log(`Incoming signup data: ${JSON.stringify(req.body, null, 0)}`)
// grab the username and password from the POST body
const username = req.body.username;
const password = req.body.password;
const username = req.body.username
const password = req.body.password

if (!username || !password) {
// no username or password received in the POST body... send an error
res.status(401).json({
success: false,
message: `No username or password supplied.`,
});
next();
})
next()
}

// try to create a new user
try {
const user = await new User({ username, password }).save();
const user = await new User({ username, password }).save()
// user saved successfully... send a success response
console.error(`New user: ${user}`);
const token = user.generateJWT(); // generate a signed token
console.error(`New user: ${user}`)
const token = user.generateJWT() // generate a signed token
res.json({
success: true,
message: "User saved successfully.",
message: 'User saved successfully.',
token: token,
username: user.username,
}); // send the token to the client to store
next();
}) // send the token to the client to store
next()
} catch (err) {
// error saving user to database... send an error response
console.error(`Failed to save user: ${err}`);
console.error(`Failed to save user: ${err}`)
res.status(500).json({
success: false,
message: "Error saving user to database.",
message: 'Error saving user to database.',
error: err,
});
next();
})
next()
}
});
})

// a route to handle login attempts requested to /auth/login
router.post("/login", async function (req, res, next) {
router.post('/login', async function (req, res, next) {
// grab the name and password that were submitted as POST body data
const username = req.body.username;
const password = req.body.password;
const username = req.body.username
const password = req.body.password
// console.log(`${username}, ${password}`)

if (!username || !password) {
// no username or password received in the POST body... send an error
res
.status(401)
.json({ success: false, message: `No username or password supplied.` });
next();
.json({ success: false, message: `No username or password supplied.` })
next()
}

// find this user in the database
try {
const user = await User.findOne({ username: username }).exec();
const user = await User.findOne({ username: username }).exec()
// check if user was found
if (!user) {
console.error(`User not found.`);
console.error(`User not found.`)
res.status(401).json({
success: false,
message: "User not found in database.",
});
next();
message: 'User not found in database.',
})
next()
}
// if user exists, check if password is correct
else if (!user.validPassword(password)) {
console.error(`Incorrect password.`);
console.error(`Incorrect password.`)
res.status(401).json({
success: false,
message: "Incorrect password.",
});
next();
message: 'Incorrect password.',
})
next()
}
// user found and password is correct... send a success response
console.log("User logged in successfully.");
const token = user.generateJWT(); // generate a signed token
console.log('User logged in successfully.')
const token = user.generateJWT() // generate a signed token
res.json({
success: true,
message: "User logged in successfully.",
message: 'User logged in successfully.',
token: token,
username: user.username,
}); // send the token to the client to store
next();
}) // send the token to the client to store
next()
} catch (err) {
// check error
console.error(`Error looking up user: ${err}`);
console.error(`Error looking up user: ${err}`)
res.status(500).json({
success: false,
message: "Error looking up user in database.",
message: 'Error looking up user in database.',
error: err,
});
next();
})
next()
}
});
})

// a route to handle logging out requests to /auth/logout
router.get("/logout", function (req, res, next) {
router.get('/logout', function (req, res, next) {
// nothing really to do here... logging out with JWT authentication is handled entirely by the front-end by deleting the token from the browser's memory
res.json({
success: true,
message:
"There is actually nothing to do on the server side... you simply need to delete your token from the browser's local storage!",
});
next();
});
})
next()
})

return router;
};
return router
}

// export the router
module.exports = authenticationRouter;
module.exports = authenticationRouter
14 changes: 7 additions & 7 deletions back-end/routes/cookie-routes.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,30 @@
const express = require("express") // CommonJS import style!
const express = require('express') // CommonJS import style!

// a method that constains code to handle cookie-related routes
const cookieRouter = () => {
// create a new router that we can customize
const router = express.Router()

// a route that sends a response including the Set-Cookie header.
router.get("/set", (req, res) => {
router.get('/set', (req, res) => {
res
.cookie("foo", "bar") // send a cookie in the response with the key 'foo' and value 'bar'
.cookie('foo', 'bar') // send a cookie in the response with the key 'foo' and value 'bar'
.send({
success: true,
message: "Sent a cookie to the browser... hopefully it saved it.",
message: 'Sent a cookie to the browser... hopefully it saved it.',
})
})

// a route that looks for a Cookie header in the request and sends back whatever data was found in it.
router.get("/get", (req, res) => {
router.get('/get', (req, res) => {
const numCookies = Object.keys(req.cookies).length // how many cookies were passed to the server

console.log(`Incoming cookie data: ${JSON.stringify(req.cookies, null, 0)}`)
res.send({
success: numCookies ? true : false,
message: numCookies
? "thanks for sending cookies to the server :)"
: "no cookies sent to server :(",
? 'thanks for sending cookies to the server :)'
: 'no cookies sent to server :(',
cookieData: req.cookies,
})
})
Expand Down
Loading

0 comments on commit 7e76e0b

Please sign in to comment.