Add passport functions

main
sudoer777 2021-11-24 17:56:04 -07:00
parent 7a62885e8f
commit 33617a82ec
4 changed files with 82 additions and 0 deletions

22
app.js
View File

@ -3,6 +3,11 @@ var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var random = require('./database/accounts/random');
const passport = require('passport');
const session = require('express-session');
const accounts = require('./database/accounts/accounts');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
@ -11,6 +16,23 @@ var manageRouter = require('./routes/manage');
var app = express();
// session setup
app.use(
session({
secret: random.makeid(20),
resave: false,
saveUninitialized: true,
})
);
// passport setup
app.use(passport.initialize());
app.use(passport.session());
//passport.use(accounts.createStrategy());
//passport.serializeUser(accounts.serializeUser());
//passport.deserializeUser(accounts.deserializeUser());
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

View File

@ -0,0 +1,37 @@
const database = require('./../database');
const passport = require('passport');
const passportLocal = require('passport-local');
passport.use(new passportLocal.Strategy((email, password, cb) => {
query = `SELECT id, email, password, admin
FROM accounts.users
WHERE email = $1`;
const result = database.executeQuery(query, [email]);
if(result.length > 0) {
const first = result[0];
bcrypt.compare(password, first[2], function(err, res) {
if(res) {
cb(null, { id: first[0], email: first[1], admin: first[3] })
}
else
{
cb(null, false)
}
})
} else {
cb(null, false)
}
}));
passport.serializeUser((user, done) => {
done(null, user.id)
})
passport.deserializeUser((id, cb) => {
query = `SELECT id, email, admin
FROM accounts.users
WHERE id = $1`;
const result = database.executeQuery(query, [parseInt(id, 10)]);
cb(null, result[0]);
});

View File

@ -0,0 +1,12 @@
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() *
charactersLength));
}
return result;
}
exports.makeid = makeid;

11
routes/accounts.js 100644
View File

@ -0,0 +1,11 @@
const passport = require('passport');
var router = express.Router();
const app = require('../app');
router.post('/login', passport.authenticate('local'), (req, res, next) => {
const { user } = req;
res.json(user);
});
module.exports = router;