Skip to content

Commit

Permalink
various updates
Browse files Browse the repository at this point in the history
password encrypeds, json webtoken created, login registration code refactor, logic update
  • Loading branch information
sankhadip-roy committed Aug 28, 2024
1 parent 9850fd4 commit 532fd9d
Show file tree
Hide file tree
Showing 8 changed files with 360 additions and 148 deletions.
10 changes: 10 additions & 0 deletions backend/config/generateToken.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const jwt = require('jsonwebtoken');

const generateToken = (id) => {
return jwt.sign({ id }, 'sankha', {
expiresIn: '30d'
}); // process.env.JWT_SECRET later
};
module.exports = generateToken;


74 changes: 74 additions & 0 deletions backend/controllers/userController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
const express = require('express');
const User = require("../models/userModel");
const asyncHandler = require('express-async-handler');
const generateToken = require('../config/generateToken');

//login
const loginController = asyncHandler(async (req, res) => {
const { name, password } = req.body;

const user = await User.findOne({ name: name });

if (user && (await user.matchPassword(password))) {
const respose = {
stat: "Success",
_id: user._id,
name: user.name,
email: user.email,
isAdmin: user.isAdmin,
token: generateToken(user._id),
};
res.json(respose)
} else {
res.status(401);
throw new Error('Invalid name or password or both');
}

});


//registration
const registerController = asyncHandler(async (req, res) => {
const { name, email, password } = req.body;

//check for all fields
if (!name || !email || !password) {
res.send(400);
throw Error("all fields are not filled");
}

//pre existing user
const userExists = await User.findOne({ email: email });
if (userExists) {
throw new Error("User already exists");
}

//username already taken
const usernameExists = await User.findOne({ name: name });
if (usernameExists) {
throw new Error("Username already taken");
}

//create user
const newuser = await User.create({
name,
email,
password,
})

if (newuser) {
res.status(201).json({
_id: newuser._id,
name: newuser.name,
email: newuser.email,
isAdmin: newuser.isAdmin,
token: generateToken(newuser._id),
});
}
else {
res.status(400);
throw new Error('Registration Error');
}
});

module.exports = { loginController, registerController };
13 changes: 12 additions & 1 deletion backend/models/userModel.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const mongoose = require('mongoose')
const bcrypt = require('bcryptjs')

const userSchema = new mongoose.Schema({
name: {
Expand All @@ -19,6 +20,16 @@ const userSchema = new mongoose.Schema({
}
);

const User = mongoose.model("User", userSchema)
userSchema.methods.matchPassword = async function (enteredPassword) {
return await bcrypt.compare(enteredPassword, this.password);
}
userSchema.pre('save', async function (next) {
if (!this.isModified()) {
next();
}
const salt = await bcrypt.genSalt(10);
this.password = await bcrypt.hash(this.password, salt);
})

const User = mongoose.model("User", userSchema)
module.exports = User;
127 changes: 127 additions & 0 deletions backend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,11 @@
"author": "sankhadip roy",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"cors": "^2.8.5",
"express": "^4.19.2",
"express-async-handler": "^1.2.0",
"jsonwebtoken": "^9.0.2",
"mongodb": "^6.8.0",
"mongoose": "^8.5.4",
"socket.io": "^4.7.5"
Expand Down
24 changes: 1 addition & 23 deletions backend/routes/userRoutes.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,6 @@
const express = require('express');
const User = require("../models/userModel");
const Router = express.Router();

function loginController(req, res) {
const { email, password } = req.body;
User.findOne({ email: email })
.then(user => {
if (user) {
if (user.password === password) {
res.json({ "stat": "Success", "user": user.name })
} else {
res.json("The password is incorrect")
}
} else {
res.json("No record existed")
}
})
}

function registerController(req, res) {
User.create(req.body)
.then(users => res.json(users))
.catch(err => res.json(err))
}
const { loginController, registerController } = require("../controllers/userController");

Router.post("/login", loginController);
Router.post("/register", registerController);
Expand Down
Loading

0 comments on commit 532fd9d

Please sign in to comment.