Hello guys.
I’m creating a very basic login and logout application using nodejs and expressjs. So far I succeeded in rendering pages, authenticating, creating sessions. But not the logout.
1 const express = require('express')
2 const mysql = require('mysql')
3 const bodyParser = require('body-parser')
4 const {v4:uuid} = require('uuid')
5 const session = require('express-session')
6 const path = require('path')
7 const passport = require('passport')
8 const LocalStrategy = require('passport-local').Strategy
9 const MySQLStore = require('express-mysql-session')(session)
10
11 const DB = mysql.createConnection({
12 host:'localhost',
13 user:'dummy',
14 password:'dummypassword',
15 database: 'workspace'
16 })
17
18 const options = {
19 host:'localhost',
20 user:'dummy',
21 password:'dummypassword',
22 database:'workspace',
23 clearExpired: true,
24 checkExpirationInterval: 1800000,
25 expiration: 900000,
26 endConnectionOnClose: true
27 }
28
29
30 const sessionStore = new MySQLStore(options)
31
32 //CONFIGURING PASSPORT
33 passport.use('local-signin',new LocalStrategy((username,password,done)=>{
34 console.log('Authentication')
35 DB.query("SELECT ID, NAME FROM dummyusertable WHERE NAME=? AND PASSWORD=?",[username,password],(err,rows,fields)=>{
36 if(err)
37 {
38 console.log(err)
39 throw err
40 }
41 if(!rows){
42 return done(null,false,{message: 'Invalid Credentials'})
43 }
44 let user={
45 id: rows[0].ID,
46 name: rows[0].NAME
47 }
48 done(null,user)
49 })
50 }))
51
52 passport.serializeUser((user,done)=>{
53 done(null,user)
54 })
55
56 passport.deserializeUser((user,done)=>{
57 DB.query("SELECT ID, NAME FROM dummyusertable WHERE ID=? AND NAME=?"[user.id,user.name],(err,rows,fields)=>{
58 if(err){
59 console.log(err)
60 throw err
61 }
62 const fetchedUser = user.id===rows[0].ID && user.name === rows[0].NAME? user:false;
63 done(null,fetchedUser)
64 })
65 })
66
67
68 const app = express()
69 app.set('views',path.join(__dirname,'views'))
70 app.set('view engine','ejs')
71
72 app.use(bodyParser.json())
73 app.use(bodyParser.urlencoded({extended:false}))
74
75 app.use(session({
76 store: sessionStore,
77 genid: req=>uuid(),
78 secret: 'Fate STay night unlimited blade works',
79 resave: false,
80 saveUninitialized: false
81 }))
82
83 app.use(passport.initialize())
84 app.use(passport.session())
85
86
87 app.get('/',(req,res)=>{
88 //res.send('Home page')
89 res.render('login')
90 })
91
92 app.post('/login',(req,res,next)=>{
93 passport.authenticate('local-signin',(err,user,info)=>{
94 console.log(info)
95 console.log(user)
96 console.log(info)
97 if(info){
98 console.log(info)
99 return res.render('login')
100 }
101 if(err){
102 console.log(err)
103 return next(err)
104 }
105 if(!user){
106 return res.redirect('/')
107 }
108 console.log(req.session)
109 console.log(req.sessionID)
110 req.login(user,(err)=>{
111 if(err){
112 console.log(err)
113 return next(err)
114 }
115 return res.render('dummy')
116 })
117 })(req,res,next);
118 })
119 //INSERTING THIS PIECE OF CODE IS CAUSING AN ERROR.
120 app.get('/logout',(req,res)=>{
121 req.session.destroy(err=>{
122 if(err){
123 console.log(err)
124 throw err
125 }
126 return res.redirect('/')
127 })
128 })
129 //THE END OF CODE CAUSING ERROR
130 app.listen(3000,()=>{
131 console.log('Listening on port : 3000')
132 })
THE ERROR I got when I typed localhost:3000
.
It was shown twice.
But on removing that piece of code I didn’t any error. Everything was working normal. And the sessions were created in the database as well.
LOGIN PAGE IN BROWSER
DUMMY PAGE IN BROWSER
TERMINAL STATS
LOGIN PAGE CODE
1 <!doctype html>
2 <html>
3 <head>
4 <title> Login page </title>
5 </head>
6 <body>
7 <form action='/login' method='post'>
8 <input type='text' name='username' placeholder='USERNAME'><br>
9 <input type='password' name='password' placeholder='PASSWORD'><br>
10 <button type='submit' name='submit' value='login'>Login</button>
11 </form>
12 </body>
13 </html>
DUMMY PAGE CODE
1 <!doctype>
2 <html>
3 <head>
4 <title> Dummy page </title>
5 </head>
6 <body>
7 <p>
8 I'm baby pop-up shoreditch tattooed stumptown wolf mixtape. Quinoa letterpress gentrify ugh gochujang gastropub echo park. Kitsch iPhone YOLO brooklyn chambray drinking vinegar sustainable man bun synth semiotics woke cloud bread leggings. Fanny pack four loko poke, woke etsy blog food truck. +1 pork belly next level mumblecore la croix hella pok pok subway tile deep v shaman irony. Swag kickstarter small batch, normcore umami meditation kombucha DIY tilde hoodie. 3 wolf moon unicorn four dollar toast, hammock bespoke cold-pressed poutine lomo leggings synth raclette tumblr.
9
10 Selvage kale chips enamel pin chillwave bicycle rights pitchfork microdosing iceland kickstarter green juice poutine. Marfa flannel quinoa lomo yuccie, succulents hella +1 keytar affogato knausgaard 3 wolf moon VHS cronut jean shorts. Fingerstache tbh enamel pin intelligentsia, cornhole skateboard offal subway tile narwhal. Pork belly quinoa jianbing bitters seitan paleo pinterest bushwick lumbersexual dreamcatcher cred readymade palo santo health goth hammock. Marfa kickstarter semiotics edison bulb small batch post-ironic tote bag roof party vexillologist.
11
12 Lumbersexual pug umami fanny pack vegan. Scenester you probably haven't heard of them vegan cloud bread brunch tousled edison bulb pinterest next level. Everyday carry forage banh mi asymmetrical celiac cardigan taxidermy franzen chartreuse thundercats migas humblebrag. Hoodie gluten-free vape gochujang sartorial keffiyeh vexillologist iceland beard man braid XOXO. Food truck kinfolk PBR&B knausgaard lomo, vexillologist church-key chicharrones sustainable ethical tbh fixie neutra vinyl. Vape kitsch hexagon lomo vexillologist letterpress cloud bread typewriter pickled ugh skateboard trust fund photo booth.
13
14 Post-ironic chillwave cronut, wolf pork belly microdosing 90's tattooed four loko dreamcatcher. Vinyl kitsch iPhone, 3 wolf moon beard scenester pinterest kinfolk. Squid sustainable PBR&B echo park, brooklyn hexagon truffaut unicorn pour-over meditation raclette street art. Coloring book fanny pack tousled venmo.
15
16 Man bun gluten-free kombucha before they sold out disrupt mumblecore biodiesel selvage enamel pin gochujang poke jean shorts tote bag hexagon waistcoat. Gochujang thundercats snackwave, hexagon man bun keffiyeh ennui vegan ramps brooklyn deep v church-key bushwick tumblr hammock. Thundercats fixie schlitz, mustache meditation small batch forage artisan mixtape pour-over chartreuse. Etsy cray meditation fashion axe wayfarers, hexagon you probably haven't heard of them gentrify. Williamsburg cray polaroid kitsch, aesthetic art party cardigan pok pok jianbing cred. Iceland swag health goth, taiyaki readymade hot chicken cloud bread yuccie tumeric cliche paleo meh wolf DIY. Blog woke heirloom, enamel pin forage raclette pitchfork ugh sustainable VHS blue bottle tousled.
17
18 Dummy text? More like dummy thicc text, amirite?
19
20 </p>
21 </body>
22 </html>
Any suggestions on how to perform logout?