Vous êtes sur la page 1sur 7

IWP

Exercise-8

18BCE0557 KUSHAL

Working:
I have made use of ​jwt and cookies​ here. When the user visits signup page the user is
welcomed with a form where when form is submitted then user is redirected back to the home
page and cookie is setup which is his jwt, at now jwt and cookie is used by user id is not used
because of the time constraint.
And in signin- if cookie is still there then do nothing and redirect to home page else create a
cookie with jwt and then redirect. In get request of signin if cookie is present then redirect
immediately to home page. I should be using middleware here but at now it’s done in the apis
itself.

Server is up

Database is up:
User Model

Index.js

const​ ​express​ = ​require​(​'express'​)


​ odyParser​ = ​require​(​'body-parser'​)
const​ b
const​ p​ ath​ = ​require​(​'path'​)
cookieParser​ = ​require​(​'cookie-parser'​);

​ ongoose​ = ​require​(​'./db/mongoose'​)
const​ m
const​ U​ ser​ = ​require​(​'./models/user'​)
const​ ​jwt​ = ​require​(​'jsonwebtoken'​);

const​ ​app​ = ​express​()


app​.​use​(​cookieParser​())
app​.​set​(​'view engine'​, ​'ejs'​)
app​.​set​(​'views'​, ​path​.​join​(​__dirname​, ​'../public/'​));

app​.​use​(​bodyParser​.​urlencoded​({ ​extended​:​ true​ }));


// app.use(express.static(__dirname + '../public/'))

app​.​get​(​''​, (​req​,​ res​) ​=>​ {


// res.json({
// Message: 'Yes I am up!'
// })
res​.​render​(​'home.ejs'​)
})

app​.​get​(​'/signup'​, (​req​,​ res​) ​=>​ {


res​.​render​(​'signup.ejs'​)
})

app​.​post​(​'/signup'​, (​req​,​ res​) ​=>​ {


​User​.​create​(​req​.​body​, (​err​) ​=>​ {
if​ (​err​)
​console​.​log​(​err​)
})
var​ token​ =​ ​jwt​.​sign​({ ​foo​: ​'bar'​ }, ​'secretByKush'​);
res​.​cookie​(​'logged-in'​,​token​, { ​maxAge​: ​900000​, ​httpOnly​:​ true​ });
​console​.​log​(​'code below!!'​)
res​.​redirect​(​'/'​)
})

app​.​get​(​'/signin'​, (​req​,​ res​) ​=>​ {


if​ (​req​.​cookies​){
​ onsole​.​log​(​req​.​cookies​)
c
res​.​render​(​'home.ejs'​)
}​ else​ {
res​.​render​(​'signin.ejs'​)
}

})

app​.​post​(​'/signin'​, (​req​,​ res​) ​=>​ {


if​ (​req​.​cookies​){
​ onsole​.​log​(​req​.​cookies​)
c
res​.​render​(​'home.ejs'​)
}​ else​ {
var​ token​ =​ ​jwt​.​sign​({ ​foo​: ​'bar'​ }, ​'secretByKush'​);
res​.​cookie​(​'logged-in'​,​token​, { ​maxAge​: ​900000​, ​httpOnly​:​ true​ });
​console​.​log​(​'code below!!'​)
res​.​redirect​(​'/'​)
}
})

app​.​listen​(​3000​, () ​=>​ {
​console​.​log​(​'Server is up and running!'​)
})

Signup:
DB:

Vous aimerez peut-être aussi