Skip to content

Commit

Permalink
Renaming folders
Browse files Browse the repository at this point in the history
  • Loading branch information
richa008 committed Dec 10, 2019
1 parent b1bf81a commit 6826e32
Show file tree
Hide file tree
Showing 13 changed files with 201 additions and 201 deletions.
35 changes: 21 additions & 14 deletions Express-SessionAuth/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -34,34 +32,43 @@ 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",
saveUninitialized: false,
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);

Expand Down
11 changes: 9 additions & 2 deletions Express-SessionAuth/models/user.js
Original file line number Diff line number Diff line change
@@ -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);
64 changes: 0 additions & 64 deletions Express-SessionAuth/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 0 additions & 3 deletions Express-SessionAuth/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
88 changes: 65 additions & 23 deletions Express-SessionAuth/routes/userRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
35 changes: 14 additions & 21 deletions ExpressPassport-SessionAuth/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -32,43 +34,34 @@ 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",
saveUninitialized: false,
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);

Expand Down
File renamed without changes.
11 changes: 2 additions & 9 deletions ExpressPassport-SessionAuth/models/user.js
Original file line number Diff line number Diff line change
@@ -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);
Loading

0 comments on commit 6826e32

Please sign in to comment.