Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fixes-issue #870 #871

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
The diff you're trying to view is too large. We only load the first 3000 changed files.
4 changes: 4 additions & 0 deletions backend/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
PORT=5000
MONGO_CONN="mongodb+srv://shivam:[email protected]/?retryWrites=true&w=majority&appName=Cluster0"
MONGO_URI="mongodb+srv://shivakvs2003:[email protected]/?retryWrites=true&w=majority&appName=Cluster0"
JWT_SECRET="secret-123"
89 changes: 89 additions & 0 deletions backend/Controllers/AuthController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
const UserModel = require("../Models/User");
const bcrypt = require('bcryptjs');
const jwt=require('jsonwebtoken');
const signup = async (req, res) => {
try {
const { name, email, password } = req.body;

// Check if the user already exists
const user = await UserModel.findOne({ email });
if (user) {
return res.status(409).json({
message: "User already exists, you can login",
success: false
});
}

// Hash the password
const hashedPassword = await bcrypt.hash(password, 10);

// Create a new user instance with hashed password
const userModel = new UserModel({
name,
email,
password: hashedPassword // Set the hashed password here
});

// Save the new user to the database
await userModel.save();

res.status(201).json({
message: "Signup successful",
success: true
});
} catch (err) {
// Log the error for debugging
console.error("Error during signup:", err);

res.status(500).json({
message: "Internal server error",
success: false
});
}
}
const login = async (req, res) => {
try {
const { email, password } = req.body;

// Check if the user already exists
const user = await UserModel.findOne({ email });
const errorMsg='Auth failed email or password is wrong';
if (!user) {
return res.status(403).json({
message: errorMsg,
success: false
});
}

const isPassEqual=await bcrypt.compare(password,user.password);
if(!isPassEqual){
return res.status(403)
.json({message:errorMsg,success:false});
}
const jwtToken=jwt.sign(
{email:user.email,_id:user._id},
process.env.JWT_SECRET,
{expiresIn:'24h'}
)
res.status(200).json({
message: "Login successful",
success: true,
jwtToken,
email,
name:user.name
});
} catch (err) {
// Log the error for debugging
console.error("Error during signup:", err);

res.status(500).json({
message: "Internal server error",
success: false
});
}
}

module.exports = {
signup,
login
};
35 changes: 35 additions & 0 deletions backend/Controllers/TransactionController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const Transaction = require('../Models/Transaction'); // Ensure this path is correct

// Function to get all transactions for a specific user
const getTransactions = async (req, res) => {
try {
// Fetch transactions that belong to the logged-in user
const transactions = await Transaction.find({ userId: req.user._id });
res.json(transactions);
} catch (err) {
res.status(500).json({ message: err.message });
}
};

// Function to add a new transaction for the logged-in user
const addTransaction = async (req, res) => {
const newTransaction = new Transaction({
description: req.body.description,
amount: req.body.amount,
transactionDate: req.body.transactionDate,
userId: req.user._id, // Ensure user ID is associated with the transaction
});

try {
// Save the new transaction to the database
const savedTransaction = await newTransaction.save();
res.status(201).json(savedTransaction);
} catch (err) {
res.status(400).json({ message: err.message });
}
};

module.exports = {
getTransactions,
addTransaction,
};
16 changes: 16 additions & 0 deletions backend/Middlewares/Auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const jwt=require('jsonwebtoken');
const ensureAuthenticated=(req,res,next)=>{
const auth=req.headers['authorization'];
if(!auth){
return res.status(403)
.json({message:'Unauthorized, JWT token is require'});
}
try{
const decoded=jwt.verify(auth,process.env.JWT_SECRET);
req.user=decoded;
}catch(err){
return res.status(403)
.json({message:'Unauthorized, JWT token wrong or expired'});
}
}
module.exports=ensureAuthenticated;
31 changes: 31 additions & 0 deletions backend/Middlewares/AuthValidation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
const Joi=require('joi');
const signupValidation=(req,res,next)=>{
const schema=Joi.object({
name:Joi.string().min(3).max(100).required(),
email:Joi.string().email().required(),
password:Joi.string().min(4).max(100).required()
});
const {error}=schema.validate(req.body);
if(error){
return res.status(400)
.json({message:"Bad request",error})
}
next();
}

const loginValidation=(req,res,next)=>{
const schema=Joi.object({
email:Joi.string().email().required(),
password:Joi.string().min(4).max(100).required()
});
const {error}=schema.validate(req.body);
if(error){
return res.status(400)
.json({message:"Bad request",error})
}
next();
}
module.exports={
signupValidation,
loginValidation
}
21 changes: 21 additions & 0 deletions backend/Middlewares/authMiddleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const jwt = require('jsonwebtoken');
const User = require('../Models/User');

const authMiddleware = async (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
return res.status(401).json({ message: 'Authentication failed: No token provided' });
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = await User.findById(decoded._id);
if (!req.user) {
return res.status(401).json({ message: 'Authentication failed: User not found' });
}
next();
} catch (err) {
res.status(401).json({ message: "Authentication failed: Invalid token." });
}
};

module.exports = authMiddleware;
27 changes: 27 additions & 0 deletions backend/Models/Transaction.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const mongoose = require('mongoose');
//hello
// Define the schema for transactions
const transactionSchema = new mongoose.Schema({
description: {
type: String,
required: true,
},
amount: {
type: String,
required: true,
},
transactionDate: {
type: String,
required: true,
},
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true,
},
});

// Create and export the Transaction model
const Transaction = mongoose.model('Transaction', transactionSchema);

module.exports = Transaction;
27 changes: 27 additions & 0 deletions backend/Models/User.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const mongoose = require('mongoose');

// Define the schema for the user
const UserSchema = new mongoose.Schema({ // Corrected to UserSchema
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true,
}
});

const db1Connection = mongoose.createConnection(process.env.MONGO_CONN, {
serverSelectionTimeoutMS: 30000,
connectTimeoutMS: 30000,
});

const UserModel = db1Connection.model('users', UserSchema);

module.exports = UserModel;
15 changes: 15 additions & 0 deletions backend/Models/userModel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const mongoose=require("mongoose");
const bcrypt=require("bcryptjs");
require('dotenv').config();
const mongo_url=process.env.MONGO_CONN;
//mongodb+srv://shivam:[email protected]/?retryWrites=true&w=majority&appName=Cluster0
const db1Connection=mongoose.createConnection(mongo_url,{
serverSelectionTimeoutMS: 30000,
connectTimeoutMS: 30000,
});
db1Connection.on('connected',()=>{
console.log('connected to the first database');
})
db1Connection.on('error',(err)=>{
console.error('Error connecting to the first database',err);
});
11 changes: 11 additions & 0 deletions backend/Routes/AuthRouter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const express=require('express');
const {signup, login}=require('../Controllers/AuthController');
const { signupValidation } = require('../Middlewares/AuthValidation');
const { loginValidation } = require('../Middlewares/AuthValidation');
const router=express.Router();


router.post('/signup',signupValidation,signup);
router.post('/login',loginValidation,login);

module.exports=router;
10 changes: 10 additions & 0 deletions backend/Routes/TransactionRouter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const express = require('express');
const { getTransactions, addTransaction } = require('../Controllers/TransactionController'); // Ensure the path is correct
const authMiddleware = require('../Middlewares/authMiddleware'); // Correct import without destructuring
const router = express.Router();

// Transaction routes
router.get('/', authMiddleware, getTransactions);
router.post('/', authMiddleware, addTransaction);

module.exports = router;
4 changes: 4 additions & 0 deletions backend/key.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
const crypto = require('crypto');

const secret = crypto.randomBytes(64).toString('hex');
console.log(secret);
12 changes: 12 additions & 0 deletions backend/node_modules/.bin/mime

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

17 changes: 17 additions & 0 deletions backend/node_modules/.bin/mime.cmd

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

28 changes: 28 additions & 0 deletions backend/node_modules/.bin/mime.ps1

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

12 changes: 12 additions & 0 deletions backend/node_modules/.bin/semver

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

17 changes: 17 additions & 0 deletions backend/node_modules/.bin/semver.cmd

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

Loading