diff --git a/Express-SessionAuth/app.js b/Express-SessionAuth/app.js index 7576358..bd413fc 100755 --- a/Express-SessionAuth/app.js +++ b/Express-SessionAuth/app.js @@ -5,8 +5,6 @@ const cookieParser = require('cookie-parser'); const bodyParser = require('body-parser'); const session = require('express-session'); const FileStore = require('session-file-store')(session); -const passport = require('passport'); -const authenticate = require('./authenticate'); const index = require('./routes/index'); const userRouter = require('./routes/userRouter'); @@ -34,6 +32,9 @@ var app = express(); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); + +// app.use(cookieParser("12345-67890-09876-54321")); // secret key + app.use(session({ name: "session-id", secret: "12345-67890-09876-54321", @@ -41,27 +42,33 @@ app.use(session({ resave: false, store: new FileStore() })); -app.use(passport.initialize()); -app.use(passport.session()); // Required for persistent login sessions -app.use(express.static(path.join(__dirname, 'public'))); // serves static data from public folder // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'pug'); -function auth(req, res, next) { - console.log(req.user); +function showError(next) { + const error = new Error("You are not authenticated"); + error.status = 401; + return next(error); +} + +function auth(request, response, next) { + console.log(request.session); - if (!req.user) { - var err = new Error('You are not authenticated!'); - err.status = 403; - next(err); - } - else { - next(); + if (request.session.user) { + if (request.session.user === "authenticated") { + next(); + } else { + showError(next); + } + } else { + showError(next); } } +app.use(express.static(path.join(__dirname, 'public'))); // serves static data from public folder + app.use('/', index); app.use('/users', userRouter); diff --git a/Express-SessionAuth/models/user.js b/Express-SessionAuth/models/user.js index f7b7a68..8576649 100644 --- a/Express-SessionAuth/models/user.js +++ b/Express-SessionAuth/models/user.js @@ -1,13 +1,20 @@ const mongoose = require('mongoose'); const Schema = mongoose.Schema; -const passportLocalMongoose = require('passport-local-mongoose'); const User = new Schema({ + username: { + type: String, + required: true, + unique: true + }, + password: { + type: String, + required: true + }, admin: { type: Boolean, default: false } }); -User.plugin(passportLocalMongoose); module.exports = mongoose.model('User', User); \ No newline at end of file diff --git a/Express-SessionAuth/package-lock.json b/Express-SessionAuth/package-lock.json index f461785..4c4864b 100755 --- a/Express-SessionAuth/package-lock.json +++ b/Express-SessionAuth/package-lock.json @@ -543,11 +543,6 @@ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" }, - "generaterr": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/generaterr/-/generaterr-1.5.0.tgz", - "integrity": "sha1-sM62zFFk3yoGEzjMNAqGFTlcUvw=" - }, "graceful-fs": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.3.tgz", @@ -861,55 +856,6 @@ "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.2.tgz", "integrity": "sha1-/CidTtiZMRlGDBViUyYs3I3mW/M=" }, - "passport": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/passport/-/passport-0.4.0.tgz", - "integrity": "sha1-xQlWkTR71a07XhgCOMORTRbwWBE=", - "requires": { - "passport-strategy": "1.x.x", - "pause": "0.0.1" - } - }, - "passport-local": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/passport-local/-/passport-local-1.0.0.tgz", - "integrity": "sha1-H+YyaMkudWBmJkN+O5BmYsFbpu4=", - "requires": { - "passport-strategy": "1.x.x" - } - }, - "passport-local-mongoose": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/passport-local-mongoose/-/passport-local-mongoose-5.0.1.tgz", - "integrity": "sha512-VUY5DgBdpjt1tjunJJ1EXV5b2nhMDkXJuhTjyiK660IgIp7kONMyWEe9tGHf8I9tZudXuTF+47JNQLIzU+Hjbw==", - "requires": { - "debug": "^3.1.0", - "generaterr": "^1.5.0", - "passport-local": "^1.0.0", - "scmp": "^2.0.0", - "semver": "^5.5.0" - }, - "dependencies": { - "debug": { - "version": "3.2.6", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", - "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", - "requires": { - "ms": "^2.1.1" - } - }, - "ms": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" - } - } - }, - "passport-strategy": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/passport-strategy/-/passport-strategy-1.0.0.tgz", - "integrity": "sha1-tVOaqPwiWj0a0XlHbd8ja0QPUuQ=" - }, "path-parse": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.6.tgz", @@ -920,11 +866,6 @@ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", "integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w=" }, - "pause": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/pause/-/pause-0.0.1.tgz", - "integrity": "sha1-HUCLP9t2kjuVQ9lvtMnf1TXZy10=" - }, "promise": { "version": "7.3.1", "resolved": "https://registry.npmjs.org/promise/-/promise-7.3.1.tgz", @@ -1151,11 +1092,6 @@ "sparse-bitfield": "^3.0.3" } }, - "scmp": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/scmp/-/scmp-2.0.0.tgz", - "integrity": "sha1-JHEQ7yLM+JexOj8KvdtSeCOTzWo=" - }, "semver": { "version": "5.7.1", "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", diff --git a/Express-SessionAuth/package.json b/Express-SessionAuth/package.json index 1807d04..445748d 100755 --- a/Express-SessionAuth/package.json +++ b/Express-SessionAuth/package.json @@ -17,9 +17,6 @@ "mongoose": "^5.7.11", "mongoose-currency": "^0.2.0", "morgan": "^1.9.1", - "passport": "^0.4.0", - "passport-local": "^1.0.0", - "passport-local-mongoose": "^5.0.1", "pug": "^2.0.4", "serve-favicon": "~2.4.5", "session-file-store": "^1.3.1" diff --git a/Express-SessionAuth/routes/userRouter.js b/Express-SessionAuth/routes/userRouter.js index 68a8953..d76da2a 100755 --- a/Express-SessionAuth/routes/userRouter.js +++ b/Express-SessionAuth/routes/userRouter.js @@ -2,43 +2,85 @@ const express = require('express'); const router = express.Router(); const bodyParser = require('body-parser'); const User = require("../models/user"); -const passport = require('passport'); router.use(bodyParser.json()); +function showAuthError(response, next, message) { + const error = new Error("You are not authenticated"); + response.setHeader("WWW-Authenticate", "Basic"); + error.status = 401; + return next(error); +} + function showError(next, message) { const error = new Error(message); error.status = 403; return next(error); } -router.post("/signup", (req, res, next) => { - User.register(new User({ username: req.body.username }), - req.body.password, (err, user) => { - if (err) { - res.statusCode = 500; - res.setHeader('Content-Type', 'application/json'); - res.json({ err: err }); - } - else { - passport.authenticate('local')(req, res, () => { - res.statusCode = 200; - res.setHeader('Content-Type', 'application/json'); - res.json({ success: true, status: 'Registration Successful!' }); - }); +router.post("/signup", (request, response, next) => { + User.findOne({ username: request.body.username }) + .then((user) => { + if (user !== null) { + showError(next, `User ${request.body.username} already exists`); + } else { + return User.create({ + username: request.body.username, + password: request.body.password + }) } - }); + }) + .then(() => { + response.statusCode = 200; + response.setHeader("Content-type", "application/json"); + response.json({ status: "Registration successful!" }); + }) + .catch((error) => next(error)); }); -router.post('/login', passport.authenticate('local'), (req, res) => { - res.statusCode = 200; - res.setHeader('Content-Type', 'application/json'); - res.json({ success: true, status: 'You are successfully logged in!' }); +router.post("/login", (request, response, next) => { + + if (!request.session.user) { + const authHeader = request.headers.authorization; + if (!authHeader) { + showAuthError(response, next); + } + + const auth = new Buffer.from(authHeader.split(' ')[1], 'base64').toString().split(":"); + const username = auth[0]; + const password = auth[1]; + + User.findOne({ username: username }) + .then((user) => { + if (user === null) { + showError(next, `User ${username} not found`); + } else if (user.password !== password) { + showError(next, "Passwords do not match"); + } else { + request.session.user = 'authenticated'; + response.statusCode = 200; + response.setHeader("Content-type", "application/json"); + response.end("You are authenticated"); + } + }) + .catch((error) => next(error)); + } + else { + + response.statusCode = 200; + response.setHeader("Content-type", "application/json"); + response.end("You are already authenticated"); + } }); -app.get('/logout', function (req, res) { - req.logout(); - res.redirect('/'); +router.get("/logout", (request, response, next) => { + if (request.session) { + request.session.destroy(); + response.clearCookie("session-id"); + response.redirect("/"); + } else { + showError(next, "You are not logged in"); + } }); module.exports = router; diff --git a/ExpressPassport-SessionAuth/app.js b/ExpressPassport-SessionAuth/app.js index bd413fc..7576358 100755 --- a/ExpressPassport-SessionAuth/app.js +++ b/ExpressPassport-SessionAuth/app.js @@ -5,6 +5,8 @@ const cookieParser = require('cookie-parser'); const bodyParser = require('body-parser'); const session = require('express-session'); const FileStore = require('session-file-store')(session); +const passport = require('passport'); +const authenticate = require('./authenticate'); const index = require('./routes/index'); const userRouter = require('./routes/userRouter'); @@ -32,9 +34,6 @@ var app = express(); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); - -// app.use(cookieParser("12345-67890-09876-54321")); // secret key - app.use(session({ name: "session-id", secret: "12345-67890-09876-54321", @@ -42,33 +41,27 @@ app.use(session({ resave: false, store: new FileStore() })); +app.use(passport.initialize()); +app.use(passport.session()); // Required for persistent login sessions +app.use(express.static(path.join(__dirname, 'public'))); // serves static data from public folder // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'pug'); -function showError(next) { - const error = new Error("You are not authenticated"); - error.status = 401; - return next(error); -} - -function auth(request, response, next) { - console.log(request.session); +function auth(req, res, next) { + console.log(req.user); - if (request.session.user) { - if (request.session.user === "authenticated") { - next(); - } else { - showError(next); - } - } else { - showError(next); + if (!req.user) { + var err = new Error('You are not authenticated!'); + err.status = 403; + next(err); + } + else { + next(); } } -app.use(express.static(path.join(__dirname, 'public'))); // serves static data from public folder - app.use('/', index); app.use('/users', userRouter); diff --git a/Express-SessionAuth/authenticate.js b/ExpressPassport-SessionAuth/authenticate.js similarity index 100% rename from Express-SessionAuth/authenticate.js rename to ExpressPassport-SessionAuth/authenticate.js diff --git a/ExpressPassport-SessionAuth/models/user.js b/ExpressPassport-SessionAuth/models/user.js index 8576649..f7b7a68 100644 --- a/ExpressPassport-SessionAuth/models/user.js +++ b/ExpressPassport-SessionAuth/models/user.js @@ -1,20 +1,13 @@ const mongoose = require('mongoose'); const Schema = mongoose.Schema; +const passportLocalMongoose = require('passport-local-mongoose'); const User = new Schema({ - username: { - type: String, - required: true, - unique: true - }, - password: { - type: String, - required: true - }, admin: { type: Boolean, default: false } }); +User.plugin(passportLocalMongoose); module.exports = mongoose.model('User', User); \ No newline at end of file diff --git a/ExpressPassport-SessionAuth/package-lock.json b/ExpressPassport-SessionAuth/package-lock.json index 4c4864b..f461785 100755 --- a/ExpressPassport-SessionAuth/package-lock.json +++ b/ExpressPassport-SessionAuth/package-lock.json @@ -543,6 +543,11 @@ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" }, + "generaterr": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/generaterr/-/generaterr-1.5.0.tgz", + "integrity": "sha1-sM62zFFk3yoGEzjMNAqGFTlcUvw=" + }, "graceful-fs": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.3.tgz", @@ -856,6 +861,55 @@ "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.2.tgz", "integrity": "sha1-/CidTtiZMRlGDBViUyYs3I3mW/M=" }, + "passport": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/passport/-/passport-0.4.0.tgz", + "integrity": "sha1-xQlWkTR71a07XhgCOMORTRbwWBE=", + "requires": { + "passport-strategy": "1.x.x", + "pause": "0.0.1" + } + }, + "passport-local": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/passport-local/-/passport-local-1.0.0.tgz", + "integrity": "sha1-H+YyaMkudWBmJkN+O5BmYsFbpu4=", + "requires": { + "passport-strategy": "1.x.x" + } + }, + "passport-local-mongoose": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/passport-local-mongoose/-/passport-local-mongoose-5.0.1.tgz", + "integrity": "sha512-VUY5DgBdpjt1tjunJJ1EXV5b2nhMDkXJuhTjyiK660IgIp7kONMyWEe9tGHf8I9tZudXuTF+47JNQLIzU+Hjbw==", + "requires": { + "debug": "^3.1.0", + "generaterr": "^1.5.0", + "passport-local": "^1.0.0", + "scmp": "^2.0.0", + "semver": "^5.5.0" + }, + "dependencies": { + "debug": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", + "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + } + } + }, + "passport-strategy": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/passport-strategy/-/passport-strategy-1.0.0.tgz", + "integrity": "sha1-tVOaqPwiWj0a0XlHbd8ja0QPUuQ=" + }, "path-parse": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.6.tgz", @@ -866,6 +920,11 @@ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", "integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w=" }, + "pause": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/pause/-/pause-0.0.1.tgz", + "integrity": "sha1-HUCLP9t2kjuVQ9lvtMnf1TXZy10=" + }, "promise": { "version": "7.3.1", "resolved": "https://registry.npmjs.org/promise/-/promise-7.3.1.tgz", @@ -1092,6 +1151,11 @@ "sparse-bitfield": "^3.0.3" } }, + "scmp": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/scmp/-/scmp-2.0.0.tgz", + "integrity": "sha1-JHEQ7yLM+JexOj8KvdtSeCOTzWo=" + }, "semver": { "version": "5.7.1", "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", diff --git a/ExpressPassport-SessionAuth/package.json b/ExpressPassport-SessionAuth/package.json index 445748d..1807d04 100755 --- a/ExpressPassport-SessionAuth/package.json +++ b/ExpressPassport-SessionAuth/package.json @@ -17,6 +17,9 @@ "mongoose": "^5.7.11", "mongoose-currency": "^0.2.0", "morgan": "^1.9.1", + "passport": "^0.4.0", + "passport-local": "^1.0.0", + "passport-local-mongoose": "^5.0.1", "pug": "^2.0.4", "serve-favicon": "~2.4.5", "session-file-store": "^1.3.1" diff --git a/ExpressPassport-SessionAuth/routes/userRouter.js b/ExpressPassport-SessionAuth/routes/userRouter.js index d76da2a..68a8953 100755 --- a/ExpressPassport-SessionAuth/routes/userRouter.js +++ b/ExpressPassport-SessionAuth/routes/userRouter.js @@ -2,85 +2,43 @@ const express = require('express'); const router = express.Router(); const bodyParser = require('body-parser'); const User = require("../models/user"); +const passport = require('passport'); router.use(bodyParser.json()); -function showAuthError(response, next, message) { - const error = new Error("You are not authenticated"); - response.setHeader("WWW-Authenticate", "Basic"); - error.status = 401; - return next(error); -} - function showError(next, message) { const error = new Error(message); error.status = 403; return next(error); } -router.post("/signup", (request, response, next) => { - User.findOne({ username: request.body.username }) - .then((user) => { - if (user !== null) { - showError(next, `User ${request.body.username} already exists`); - } else { - return User.create({ - username: request.body.username, - password: request.body.password - }) +router.post("/signup", (req, res, next) => { + User.register(new User({ username: req.body.username }), + req.body.password, (err, user) => { + if (err) { + res.statusCode = 500; + res.setHeader('Content-Type', 'application/json'); + res.json({ err: err }); + } + else { + passport.authenticate('local')(req, res, () => { + res.statusCode = 200; + res.setHeader('Content-Type', 'application/json'); + res.json({ success: true, status: 'Registration Successful!' }); + }); } - }) - .then(() => { - response.statusCode = 200; - response.setHeader("Content-type", "application/json"); - response.json({ status: "Registration successful!" }); - }) - .catch((error) => next(error)); + }); }); -router.post("/login", (request, response, next) => { - - if (!request.session.user) { - const authHeader = request.headers.authorization; - if (!authHeader) { - showAuthError(response, next); - } - - const auth = new Buffer.from(authHeader.split(' ')[1], 'base64').toString().split(":"); - const username = auth[0]; - const password = auth[1]; - - User.findOne({ username: username }) - .then((user) => { - if (user === null) { - showError(next, `User ${username} not found`); - } else if (user.password !== password) { - showError(next, "Passwords do not match"); - } else { - request.session.user = 'authenticated'; - response.statusCode = 200; - response.setHeader("Content-type", "application/json"); - response.end("You are authenticated"); - } - }) - .catch((error) => next(error)); - } - else { - - response.statusCode = 200; - response.setHeader("Content-type", "application/json"); - response.end("You are already authenticated"); - } +router.post('/login', passport.authenticate('local'), (req, res) => { + res.statusCode = 200; + res.setHeader('Content-Type', 'application/json'); + res.json({ success: true, status: 'You are successfully logged in!' }); }); -router.get("/logout", (request, response, next) => { - if (request.session) { - request.session.destroy(); - response.clearCookie("session-id"); - response.redirect("/"); - } else { - showError(next, "You are not logged in"); - } +app.get('/logout', function (req, res) { + req.logout(); + res.redirect('/'); }); module.exports = router; diff --git a/Express-SessionAuth/sessions/DVy4soZaFPNpjb39MCw7fQZ287elYi-C.json b/ExpressPassport-SessionAuth/sessions/DVy4soZaFPNpjb39MCw7fQZ287elYi-C.json similarity index 100% rename from Express-SessionAuth/sessions/DVy4soZaFPNpjb39MCw7fQZ287elYi-C.json rename to ExpressPassport-SessionAuth/sessions/DVy4soZaFPNpjb39MCw7fQZ287elYi-C.json diff --git a/Express-SessionAuth/sessions/tho8Ia8PRPrFEUxYDHCBW4WwSHYz2r3B.json b/ExpressPassport-SessionAuth/sessions/tho8Ia8PRPrFEUxYDHCBW4WwSHYz2r3B.json similarity index 100% rename from Express-SessionAuth/sessions/tho8Ia8PRPrFEUxYDHCBW4WwSHYz2r3B.json rename to ExpressPassport-SessionAuth/sessions/tho8Ia8PRPrFEUxYDHCBW4WwSHYz2r3B.json