Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 3 additions & 16 deletions Auth/Auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,12 @@ exports.register = async (req, res, next) => {
const maxAge = 3 * 60 * 60; // 3hrs in sec
const token = jwt.sign(
{ id: user._id, username, role: user.role },
jwtsecret,
jwtsecret, // used crypto lib
{expiresIn: maxAge, }
);
res.cookie("jwt", token, {
secure: true,
httpOnly: true,
secure: true, // cookie is sent only via http
httpOnly: true, // prevents scripts from browser from reading cookie
maxAge: maxAge * 1000, // 3hrs in ms
});

Expand Down Expand Up @@ -71,19 +71,6 @@ exports.login = async (req, res, next) => {
// find user in db
const user = await User.findOne({ username })
if (!user) {

const maxAge = 3 * 60 * 60; // 3hrs in sec
const token = jwt.sign(
{ id: user._id, username, role: user.role },
jwtsecret,
{expiresIn: maxAge, }
);
res.cookie("jwt", token, {
secure: true,
httpOnly: true,
maxAge: maxAge * 1000, // 3hrs in ms
});

res.status(401).json({
message: "Login not successful",
error: "User not found",
Expand Down
1 change: 1 addition & 0 deletions config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ dotenv.config();
module.exports = {
jwtsecret: process.env.JWTSECRET,
port: process.env.PORT,
hostname: process.env.HOSTNAME
};
12 changes: 6 additions & 6 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@ app.use(express.json());
app.use(cookieParser());

// read env variables from config file
const { port } = require('./config');
const { port,hostname } = require('./config');

// adding routes
// login & register route
app.use("/api/auth", require("./Auth/Route"));

app.get("/admin", adminJWTAuth, (req, res) => res.send("Admin Route"));
app.get("/basic", userJWTAuth, (req, res) => res.send("User Route"));
app.get("/admin", adminJWTAuth, (req, res) => res.send("Admin Dashboard"));
app.get("/basic", userJWTAuth, (req, res) => res.send("User Dahboard"));
app.get("/logout", (req, res) => {res.cookie("jwt", "", { maxAge: "1" })
res.redirect("/")
})
Expand All @@ -36,7 +36,7 @@ const options = {

// creating expresss https server that listens on port 8000
https.createServer(options,app).listen(port, ()=>{
console.log('server is runing at port 8000')
console.log(`Server running at http://${hostname}:${port}/`)
});

// Handling Error
Expand All @@ -45,7 +45,7 @@ process.on("unhandledRejection", err => {
server.close(() => process.exit(1))
})

// try route
// Heart beat
app.get('/', (req,res)=>{
res.send("Hello from express server.")
})