forked from devleague/express-gallery
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
110 lines (97 loc) · 2.63 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
const express = require('express');
const bodyParser = require('body-parser');
const CONFIG = require('./config/config.json');
const validate = require('./middleware/validation');
const log = require ('./middleware/log');
const app = express();
const authenticate = require('./middleware/authentication');
const passport = require('passport');
const bcrypt = require('bcrypt');
const session = require('express-session');
const RedisStore = require('connect-redis')(session);
const flash = require('connect-flash');
const gallery = require('./routes/gallery');
const db = require('./models');
const Photo = db.Photo;
const User = db.User;
app.use(express.static('./public'));
app.set('view engine', 'pug');
app.set('views', './views');
app.use(bodyParser.urlencoded({ extended: true}));
app.use(flash());
app.use(session({
store: new RedisStore(),
secret: CONFIG.SECRET,
resave: false,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(authenticate.ls);
app.use('/gallery', gallery);
app.use(log);
app.listen(3000, function() {
db.sequelize.sync();
});
app.get('/login', (req, res) => {
res.render('login', {
status: 'valid',
failureMsg: req.flash('error')[0]
});
});
app.get('/logout', (req, res) => {
req.logout();
res.redirect('/');
});
app.post('/login', passport.authenticate('local', {
successRedirect: '/gallery',
failureRedirect: '/login',
failureFlash: 'Invalid login'
}));
let isLoggedIn = (req) => {
if(req.user !== undefined && req.user !== false) {
return true;
}
return false;
};
app.get('/', function(req, res) {
//to view list of gallery photos
if(req.user === undefined) {
username = 'Not logged in';
} else {
username = req.user.username;
}
Photo.findAll({
order: [['id', 'DESC']]
})
.then((photos) => {
res.render('gallery', {
featured: photos.shift(),
gallery: photos,
isLoggedIn: isLoggedIn(req),
username: username
});
});
});
app.post('/users', validate.userValidate, (req, res) => {
//to create a new gallery photo
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(req.body.password, salt, (err, hash) => {
User.create({ username: req.body.username,
password: hash,
emailaddress: req.body.email,
role: 'USER'})
.then((user) => {
res.render('login', {status: 'valid'});
})
.catch((err) => {
//req.flash('info', 'Invalid input in user account fields');
res.render('login', {status: 'invalid'});
});
});
});
});
app.get('/:page', (req, res) => {
res.status(404).render('404');
});
module.exports = app;