Skip to content

Commit

Permalink
Merge pull request #190 from biswarup-naha/main
Browse files Browse the repository at this point in the history
Fixed: Adding sessions to website #73
  • Loading branch information
VanshKing30 authored May 28, 2024
2 parents 61f3cea + b677300 commit a0aad2a
Show file tree
Hide file tree
Showing 4 changed files with 107 additions and 35 deletions.
115 changes: 82 additions & 33 deletions server/controllers/Auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const bcrypt = require("bcrypt");
const User = require("../models/studentLoginInfo");
const jwt = require("jsonwebtoken");
const Canteen = require("../models/canteenLoginInfo");
const Session = require("../models/session");

require("dotenv").config();

Expand Down Expand Up @@ -38,6 +39,8 @@ exports.studentSignup = async (req, res) => {
password: hashedPassword,
});

await user.save();

return res.status(200).json({
success: true,
message: "User created succesfully",
Expand Down Expand Up @@ -81,22 +84,35 @@ exports.studentLogin = async (req, res) => {
let token = jwt.sign(payload, process.env.JWT_SECRET, {
expiresIn: "2h",
});

// creating a session
const session = new Session({ userId: user._id, token });
await session.save();

user = user.toObject();
user.token = token;
user.password = undefined;
console.log(user);

const options = {
expires: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000),
httpOnly: true,
};
// const options = {
// expires: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000),
// httpOnly: true,
// };

// res.cookie("token", token, options).status(200).json({
// success: true,
// token,
// user,
// message: "User logged in succesfully",
// });

res.cookie("token", token, options).status(200).json({
success: true,
token,
user,
message: "User logged in succesfully",
// Setting cookie
res.cookie("token", token, {
httpOnly: true,
secure: true,
maxAge: 3600000,
});
res.json({ success: true, message: "Logged in successfully", token, user });
} else {
return res.status(403).json({
success: false,
Expand Down Expand Up @@ -127,14 +143,24 @@ exports.studentLogout = async (req, res) => {
}
);

const options = {
httpOnly: true,
};
// const options = {
// httpOnly: true,
// };

return res.status(200).clearCookie("token", options).json({
success: true,
message: "User Logged off successfully.",
});
// return res.status(200).clearCookie("token", options).json({
// success: true,
// message: "User Logged off successfully.",
// });

const token =
req.cookies?.token ||
req?.header("Authorization")?.replace("Bearer ", "");

if (token) {
await Session.findOneAndDelete({ token });
res.clearCookie("token");
}
res.status(200).json({ success: true, message: "Logged out successfully" });
} catch (error) {
console.log(error);
return res.status(500).json({
Expand Down Expand Up @@ -251,18 +277,31 @@ exports.canteenLogin = async (req, res) => {
canteen.password = undefined;
console.log(canteen);

const options = {
expires: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000),
// const options = {
// expires: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000),
// httpOnly: true,
// };

// res.cookie("token", token, options).status(200).json({
// success: true,
// token,
// canteen,
// message: "Canteen logged in succesfully",
// cantId: canteen._id,
// });

// Create session
const session = new Session({ userId: canteen._id, token });
await session.save();

// Set cookie
res.cookie("token", token, {
httpOnly: true,
};

res.cookie("token", token, options).status(200).json({
success: true,
token,
canteen,
message: "Canteen logged in succesfully",
cantId: canteen._id,
secure: true,
maxAge: 3600000,
});
res.json({ success: true, message: "Logged in successfully", token, canteen, cantId: canteen._id });

} else {
return res.status(403).json({
success: false,
Expand Down Expand Up @@ -293,14 +332,24 @@ exports.canteenLogout = async (req, res) => {
}
);

const options = {
httpOnly: true,
};
// const options = {
// httpOnly: true,
// };

return res.status(200).clearCookie("token", options).json({
success: true,
message: "Canteen User Logged off successfully.",
});
// return res.status(200).clearCookie("token", options).json({
// success: true,
// message: "Canteen User Logged off successfully.",
// });

const token =
req.cookies?.token ||
req?.header("Authorization")?.replace("Bearer ", "");

if (token) {
await Session.findOneAndDelete({ token });
res.clearCookie("token");
}
res.status(200).json({ success: true, message: "Logged out successfully" });
} catch (error) {
console.log(error);
return res.status(500).json({
Expand Down
22 changes: 22 additions & 0 deletions server/models/session.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const mongoose = require('mongoose');

const sessionSchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'Student'
},
token: {
type: String,
required: true
},
createdAt: {
type: Date,
default: Date.now,
expires: 3600
}
});

const Session = mongoose.model('Session', sessionSchema);

module.exports = Session;
1 change: 1 addition & 0 deletions src/pages/Login.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ function Login() {
if(formData.accountType === "User"){

const apiUrl = `${process.env.REACT_APP_BASE_URL}/studentLogin`;
// const apiUrl = `http://localhost:4000/api/v1/studentLogin`;

axios.post(apiUrl , formData)
.then((response)=>{
Expand Down
4 changes: 2 additions & 2 deletions src/pages/Signup.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,8 @@ function Signup() {

if (lowerValidated && upperValidated && numberValidated && specialValidated && lengthValidated) {
if (formData.accountType === "User") {
const apiUrl = `${process.env.REACT_APP_BASE_URL}/studentSignup`;
// const apiUrl = `http://localhost:4000/api/v1/studentSignup`;
// const apiUrl = `${process.env.REACT_APP_BASE_URL}/studentSignup`;
const apiUrl = `http://localhost:4000/api/v1/studentSignup`;

axios
.post(apiUrl, formData)
Expand Down

0 comments on commit a0aad2a

Please sign in to comment.