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

PAYTM App v1 #53

Open
wants to merge 7 commits into
base: main
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
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions backend/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
JWT_SECRET = "Shreyas is a good boy"

MONGODB_CONNECTION_URL = mongodb+srv://shreyasprabhu26:[email protected]/paytm?retryWrites=true&w=majority&appName=Cluster0
1 change: 1 addition & 0 deletions backend/.gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
node_modules
.env
14 changes: 14 additions & 0 deletions backend/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const mongoose = require('mongoose');

async function connectToMongoDb(connection_url) {
try {
await mongoose.connect(connection_url);
console.log("Connected to MongoDB successfully!");
} catch (error) {
console.error("Error connecting to MongoDB:", error);
}
}

module.exports = {
connectToMongoDb,
}
60 changes: 60 additions & 0 deletions backend/controllers/bank.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
const mongoose = require("mongoose")
const Account = require("../models/bank");

async function handleGetBalance(req, res) {
const account = await Account.findOne({
userId: req.userId
});

res.json({
balance: account.balance
})
}

async function handleTransfer(req, res) {
const session = await mongoose.startSession();
try {
session.startTransaction();
const { amount, to } = req.body;

// Fetch the accounts within the transaction
const account = await Account.findOne({ userId: req.userId }).session(session);

if (!account || account.balance < amount) {
await session.abortTransaction();
return res.status(400).json({
message: "Insufficient balance"
});
}

const toAccount = await Account.findOne({ userId: to }).session(session);

if (!toAccount) {
await session.abortTransaction();
return res.status(400).json({
message: "Invalid account"
});
}

// Perform the transfer
await Account.updateOne({ userId: req.userId }, { $inc: { balance: -amount } }).session(session);
await Account.updateOne({ userId: to }, { $inc: { balance: amount } }).session(session);

// Commit the transaction
await session.commitTransaction();

} catch (error) {
await session.abortTransaction();
return res.status(500).json({
message: "Internal Server Error"
});
}
res.json({
message: "Transfer successful"
});
};

module.exports = {
handleGetBalance,
handleTransfer
}
144 changes: 144 additions & 0 deletions backend/controllers/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
const zod = require("zod");
const User = require("../models/user");
const Account = require("../models/bank");
const jwt = require("jsonwebtoken");

const JWT_SECRET = process.env.JWT_SECRET;

const signupBody = zod.object({
username: zod.string().email(),
firstname: zod.string(),
lastname: zod.string(),
password: zod.string()
})

const signinBody = zod.object({
username: zod.string().email(),
password: zod.string()
})


async function handleUserSignUp(req, res) {
const { success } = signupBody.safeParse(req.body)
if (!success) {
return res.status(411).json({
message: "Email already taken / Incorrect inputs"
})
}

const existingUser = await User.findOne({
username: req.body.username
})

if (existingUser) {
return res.status(411).json({
message: "Email already taken/Incorrect inputs"
})
}

const user = await User.create({
username: req.body.username,
firstname: req.body.firstname,
lastname: req.body.lastname,
password: req.body.password,
})
const userId = user._id;

await Account.create({
userId,
balance: 1 + Math.random() * 10000
})


const token = jwt.sign({
userId
}, JWT_SECRET);

res.json({
message: "User created successfully",
token: token
})
}

async function handleUserSignIn(req, res) {
const { success } = signinBody.safeParse(req.body)
if (!success) {
return res.status(411).json({
message: "Email already taken / Incorrect inputs"
})
}

const user = await User.findOne({
username: req.body.username,
password: req.body.password
});

if (user) {
const token = jwt.sign({
userId: user._id
}, JWT_SECRET);

res.json({
token: token
})
return;
}


res.status(411).json({
message: "Error while logging in"
})
}


const updateBody = zod.object({
password: zod.string().optional(),
firstName: zod.string().optional(),
lastName: zod.string().optional(),
})

async function handleUpdateUser(req, res) {
const { success } = updateBody.safeParse(req.body)
if (!success) {
res.status(411).json({
message: "Error while updating information"
})
}

await User.updateOne(req.body, {
_id: req.userId
})

res.json({
message: "Updated successfully"
})
}


async function filterUsers(req, res) {
const filter = req.query.filter || "";

const users = await User.find({
$or: [
{ firstname: { "$regex": filter, "$options": "i" } },
{ lastname: { "$regex": filter, "$options": "i" } }
]
});

res.json({
user: users.map(user => ({
id: user._id,
username: user.username,
firstName: user.firstname,
lastName: user.lastname,
}))
});
}


module.exports = {
handleUserSignUp,
handleUserSignIn,
handleUpdateUser,
filterUsers
}
21 changes: 21 additions & 0 deletions backend/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,24 @@
const express = require("express");
const cors = require("cors");
const { connectToMongoDb } = require("./config");
const userRoute = require("./routes/user");
const bankRoute = require("./routes/bank");
const app = express();

const CONNECTION_URL = process.env.MONGODB_CONNECTION_URL;
const PORT = 3000;

app.use(cors());
app.use(express.json());

app.use("/api/v1/user", userRoute);
app.use("/api/v1/account", bankRoute);

connectToMongoDb(CONNECTION_URL)
.then(() => {
app.listen(PORT, () => console.log(`Server running on port: ${PORT}`));
})
.catch((err) => {
console.error('Failed to connect to MongoDB', err);
process.exit(1);
});
27 changes: 27 additions & 0 deletions backend/middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const jwt = require("jsonwebtoken");

const JWT_SECRET = process.env.JWT_SECRET;

const authMiddleware = (req, res, next) => {
const authHeader = req.headers.authorization;

if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(403).json({});
}

const token = authHeader.split(' ')[1];

try {
const decoded = jwt.verify(token, JWT_SECRET);

req.userId = decoded.userId;

next();
} catch (err) {
return res.status(403).json({});
}
};

module.exports = {
authMiddleware
}
18 changes: 18 additions & 0 deletions backend/models/bank.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const mongoose = require("mongoose");
const UserModel = require("./user")

const accountSchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: UserModel,
required: true
},
balance: {
type: Number,
required: true
}
});

const Account = mongoose.model('Account', accountSchema);

module.exports = Account;
33 changes: 33 additions & 0 deletions backend/models/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const mongoose = require("mongoose");

const UserSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true,
trim: true,
lowercase: true,
minLength: 3,
maxLength: 30
},
firstname: {
type: String,
required: true,
maxLength: 20,
trim: true,
},
lastname: {
type: String,
required: true,
maxLength: 20,
trim: true,
},
password: {
type: String,
required: true,
}
});

const UserModel = mongoose.model("user", UserSchema);

module.exports = UserModel;
Loading