Skip to content

Commit 7e76e0b

Browse files
committed
prettierrc
1 parent e70b6d9 commit 7e76e0b

26 files changed

+302
-296
lines changed

.prettierrc

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"tabWidth": 2,
3+
"semi": false,
4+
"arrowParens": "avoid",
5+
"singleQuote": true
6+
}

back-end/app.js

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,26 @@
11
// import and instantiate express
2-
const express = require("express") // CommonJS import style!
2+
const express = require('express') // CommonJS import style!
33
const app = express() // instantiate an Express object
4-
const cors = require("cors") // middleware for enabling CORS (Cross-Origin Resource Sharing) requests.
5-
const morgan = require("morgan") // middleware for nice logging of incoming HTTP requests
6-
const path = require("path")
7-
const cookieParser = require("cookie-parser") // middleware useful for parsing cookies in requests
8-
require("dotenv").config({ silent: true }) // load environmental variables from a hidden file named .env
4+
const cors = require('cors') // middleware for enabling CORS (Cross-Origin Resource Sharing) requests.
5+
const morgan = require('morgan') // middleware for nice logging of incoming HTTP requests
6+
const path = require('path')
7+
const cookieParser = require('cookie-parser') // middleware useful for parsing cookies in requests
8+
require('dotenv').config({ silent: true }) // load environmental variables from a hidden file named .env
99

1010
// the following are used for authentication with JSON Web Tokens
11-
const jwt = require("jsonwebtoken")
12-
const passport = require("passport")
11+
const jwt = require('jsonwebtoken')
12+
const passport = require('passport')
1313

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

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

2121
// mongoose models for MongoDB data manipulation
22-
const mongoose = require("mongoose")
23-
const User = require("./models/User.js")
22+
const mongoose = require('mongoose')
23+
const User = require('./models/User.js')
2424

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

3636
// set up some useful middleware
37-
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
37+
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
3838

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

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

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

5757
// export the express app we created to make it available to other modules
5858
module.exports = app // CommonJS export style!

back-end/config/jwt-config.js

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,27 @@
1-
const mongoose = require("mongoose")
1+
const mongoose = require('mongoose')
22
const ObjectId = mongoose.Types.ObjectId
3-
const User = require("../models/User.js")
3+
const User = require('../models/User.js')
44

5-
const passportJWT = require("passport-jwt")
5+
const passportJWT = require('passport-jwt')
66
const ExtractJwt = passportJWT.ExtractJwt
77
const JwtStrategy = passportJWT.Strategy
88

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

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

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

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

back-end/models/User.js

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
// a mongoose model of a user
2-
const mongoose = require("mongoose")
2+
const mongoose = require('mongoose')
33
const Schema = mongoose.Schema
4-
const bcrypt = require("bcryptjs")
5-
const jwt = require("jsonwebtoken")
6-
const jwtStrategy = require("../config/jwt-config.js") // import setup options for using JWT in passport
4+
const bcrypt = require('bcryptjs')
5+
const jwt = require('jsonwebtoken')
6+
const jwtStrategy = require('../config/jwt-config.js') // import setup options for using JWT in passport
77

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

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

6666
// create a model from this schema
67-
const User = mongoose.model("User", UserSchema)
67+
const User = mongoose.model('User', UserSchema)
6868

6969
// export the model
7070
module.exports = User
Lines changed: 51 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -1,126 +1,126 @@
1-
const express = require("express"); // CommonJS import style!
1+
const express = require('express') // CommonJS import style!
22

33
// mongoose models for MongoDB data manipulation
4-
const mongoose = require("mongoose");
5-
const User = require("../models/User.js");
4+
const mongoose = require('mongoose')
5+
const User = require('../models/User.js')
66

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

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

1919
if (!username || !password) {
2020
// no username or password received in the POST body... send an error
2121
res.status(401).json({
2222
success: false,
2323
message: `No username or password supplied.`,
24-
});
25-
next();
24+
})
25+
next()
2626
}
2727

2828
// try to create a new user
2929
try {
30-
const user = await new User({ username, password }).save();
30+
const user = await new User({ username, password }).save()
3131
// user saved successfully... send a success response
32-
console.error(`New user: ${user}`);
33-
const token = user.generateJWT(); // generate a signed token
32+
console.error(`New user: ${user}`)
33+
const token = user.generateJWT() // generate a signed token
3434
res.json({
3535
success: true,
36-
message: "User saved successfully.",
36+
message: 'User saved successfully.',
3737
token: token,
3838
username: user.username,
39-
}); // send the token to the client to store
40-
next();
39+
}) // send the token to the client to store
40+
next()
4141
} catch (err) {
4242
// error saving user to database... send an error response
43-
console.error(`Failed to save user: ${err}`);
43+
console.error(`Failed to save user: ${err}`)
4444
res.status(500).json({
4545
success: false,
46-
message: "Error saving user to database.",
46+
message: 'Error saving user to database.',
4747
error: err,
48-
});
49-
next();
48+
})
49+
next()
5050
}
51-
});
51+
})
5252

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

6060
if (!username || !password) {
6161
// no username or password received in the POST body... send an error
6262
res
6363
.status(401)
64-
.json({ success: false, message: `No username or password supplied.` });
65-
next();
64+
.json({ success: false, message: `No username or password supplied.` })
65+
next()
6666
}
6767

6868
// find this user in the database
6969
try {
70-
const user = await User.findOne({ username: username }).exec();
70+
const user = await User.findOne({ username: username }).exec()
7171
// check if user was found
7272
if (!user) {
73-
console.error(`User not found.`);
73+
console.error(`User not found.`)
7474
res.status(401).json({
7575
success: false,
76-
message: "User not found in database.",
77-
});
78-
next();
76+
message: 'User not found in database.',
77+
})
78+
next()
7979
}
8080
// if user exists, check if password is correct
8181
else if (!user.validPassword(password)) {
82-
console.error(`Incorrect password.`);
82+
console.error(`Incorrect password.`)
8383
res.status(401).json({
8484
success: false,
85-
message: "Incorrect password.",
86-
});
87-
next();
85+
message: 'Incorrect password.',
86+
})
87+
next()
8888
}
8989
// user found and password is correct... send a success response
90-
console.log("User logged in successfully.");
91-
const token = user.generateJWT(); // generate a signed token
90+
console.log('User logged in successfully.')
91+
const token = user.generateJWT() // generate a signed token
9292
res.json({
9393
success: true,
94-
message: "User logged in successfully.",
94+
message: 'User logged in successfully.',
9595
token: token,
9696
username: user.username,
97-
}); // send the token to the client to store
98-
next();
97+
}) // send the token to the client to store
98+
next()
9999
} catch (err) {
100100
// check error
101-
console.error(`Error looking up user: ${err}`);
101+
console.error(`Error looking up user: ${err}`)
102102
res.status(500).json({
103103
success: false,
104-
message: "Error looking up user in database.",
104+
message: 'Error looking up user in database.',
105105
error: err,
106-
});
107-
next();
106+
})
107+
next()
108108
}
109-
});
109+
})
110110

111111
// a route to handle logging out requests to /auth/logout
112-
router.get("/logout", function (req, res, next) {
112+
router.get('/logout', function (req, res, next) {
113113
// 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
114114
res.json({
115115
success: true,
116116
message:
117117
"There is actually nothing to do on the server side... you simply need to delete your token from the browser's local storage!",
118-
});
119-
next();
120-
});
118+
})
119+
next()
120+
})
121121

122-
return router;
123-
};
122+
return router
123+
}
124124

125125
// export the router
126-
module.exports = authenticationRouter;
126+
module.exports = authenticationRouter

back-end/routes/cookie-routes.js

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,30 @@
1-
const express = require("express") // CommonJS import style!
1+
const express = require('express') // CommonJS import style!
22

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

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

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

2222
console.log(`Incoming cookie data: ${JSON.stringify(req.cookies, null, 0)}`)
2323
res.send({
2424
success: numCookies ? true : false,
2525
message: numCookies
26-
? "thanks for sending cookies to the server :)"
27-
: "no cookies sent to server :(",
26+
? 'thanks for sending cookies to the server :)'
27+
: 'no cookies sent to server :(',
2828
cookieData: req.cookies,
2929
})
3030
})

0 commit comments

Comments
 (0)